List of usage examples for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED
String ACTION_ACL_CONNECTED
To view the source code for android.bluetooth BluetoothDevice ACTION_ACL_CONNECTED.
Click Source Link
From source file:com.example.android.classical.MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE); GlobalVar.currentDeviceMacAddress = wm.getConnectionInfo().getMacAddress(); IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); registerReceiver(mReceiver, intentFilter); intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(mReceiver, intentFilter); intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, intentFilter); if (savedInstanceState == null) { FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); BluetoothChatFragment fragment = new BluetoothChatFragment(); transaction.replace(R.id.sample_content_fragment, fragment); transaction.commit();//from w w w . j a va2 s . c om } //new Thread(){ // @Override public void run() { // while(true) { // Intent intentService = new Intent(MainActivity.this, TaskIntentService.class); // intentService.putExtra(TaskIntentService.MESSAGE_TYPE, MessageType.toInt(MessageType.BALL_EVENT)); // intentService.putExtra(TaskIntentService.EVENT_TYPE, EventType.BALL_CONNECTED); // startService(intentService); // SystemClock.sleep(2000); // } // } //}.start(); }
From source file:com.manuelmazzuola.speedtogglebluetooth.service.MonitorSpeed.java
@Override public int onStartCommand(Intent intent, int flags, int startId) { running = Boolean.TRUE;// w ww.ja v a2 s. c o m lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); provider = lm.NETWORK_PROVIDER; oldLocation = lm.getLastKnownLocation(provider); IntentFilter filters = new IntentFilter(); // When to turn off bluetooth filters.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); // When hold bluetooth on filters.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); // When user directly turn on or off bluetooth filters.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(bluetoothListener, filters); lm.requestLocationUpdates(provider, 45 * 1000, 0f, this); Intent stopIntent = new Intent(this, MainActivity.class); stopIntent.putExtra("close", "close"); PendingIntent stopPendingIntent = PendingIntent.getActivity(this, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder note = new NotificationCompat.Builder(getApplicationContext()) .setContentTitle(DEFAULT_TITLE).setContentText(DEFAULT_MESSAGE) .setDefaults(Notification.DEFAULT_VIBRATE).setAutoCancel(true).setContentIntent(stopPendingIntent) .setSmallIcon(R.drawable.ic_action_bluetooth); note.getNotification().flags |= Notification.FLAG_AUTO_CANCEL; Notification notification = note.build(); notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL; startForeground(intentId, note.build()); return START_NOT_STICKY; }
From source file:org.thecongers.mtpms.MainActivity.java
@SuppressLint("HandlerLeak") @Override//from www .ja v a 2s . co m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle(R.string.app_name); layoutFront = (LinearLayout) findViewById(R.id.layoutFront); layoutRear = (LinearLayout) findViewById(R.id.layoutRear); txtFrontPressure = (TextView) findViewById(R.id.txtFrontPressure); txtFrontTemperature = (TextView) findViewById(R.id.txtFrontTemperature); txtFrontVoltage = (TextView) findViewById(R.id.txtFrontVoltage); txtRearPressure = (TextView) findViewById(R.id.txtRearPressure); txtRearTemperature = (TextView) findViewById(R.id.txtRearTemperature); txtRearVoltage = (TextView) findViewById(R.id.txtRearVoltage); txtOutput = (TextView) findViewById(R.id.txtOutput); View myView = findViewById(R.id.appLayout); root = myView.getRootView(); sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Watch for Bluetooth Changes IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); this.registerReceiver(btReceiver, filter1); this.registerReceiver(btReceiver, filter2); this.registerReceiver(btReceiver, filter3); sensorDB = new SensorIdDatabase(this); // Backgrounds background = this.getResources().getDrawable(R.drawable.rectangle_bordered); redBackground = this.getResources().getDrawable(R.drawable.rectangle_bordered_red); backgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_dark); redBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_red_dark); txtOutBackground = this.getResources().getDrawable(R.drawable.rectangle); txtOutBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_dark); // Update textViews with select units String pressureFormat = sharedPrefs.getString("prefpressuref", "0"); String pressureUnit = "psi"; if (pressureFormat.contains("1")) { // KPa pressureUnit = "KPa"; } else if (pressureFormat.contains("2")) { // Kg-f pressureUnit = "Kg-f"; } else if (pressureFormat.contains("3")) { // Bar pressureUnit = "Bar"; } String temperatureUnit = "C"; if (sharedPrefs.getString("preftempf", "0").contains("0")) { // F temperatureUnit = "F"; } txtFrontPressure.setText("--- " + pressureUnit); txtFrontTemperature.setText("--- " + temperatureUnit); txtFrontVoltage.setText("--- V"); txtRearPressure.setText("--- " + pressureUnit); txtRearTemperature.setText("--- " + temperatureUnit); txtRearVoltage.setText("--- V"); // Set initial color scheme if (!sharedPrefs.getBoolean("prefNightMode", false)) { root.setBackgroundColor(getResources().getColor(android.R.color.white)); layoutFront.setBackground(background); layoutRear.setBackground(background); txtFrontPressure.setTextColor(getResources().getColor(android.R.color.black)); txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.black)); txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.black)); txtRearPressure.setTextColor(getResources().getColor(android.R.color.black)); txtRearTemperature.setTextColor(getResources().getColor(android.R.color.black)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black)); txtOutput.setBackground(txtOutBackground); txtOutput.setTextColor(getResources().getColor(android.R.color.black)); } else { root.setBackgroundColor(getResources().getColor(android.R.color.black)); layoutFront.setBackground(backgroundDark); layoutRear.setBackground(backgroundDark); txtFrontPressure.setTextColor(getResources().getColor(android.R.color.white)); txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.white)); txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.white)); txtRearPressure.setTextColor(getResources().getColor(android.R.color.white)); txtRearTemperature.setTextColor(getResources().getColor(android.R.color.white)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white)); txtOutput.setBackground(txtOutBackgroundDark); txtOutput.setTextColor(getResources().getColor(android.R.color.white)); } // Check if there are sensor to wheel mappings if (sharedPrefs.getString("prefFrontID", "").equals("") && sharedPrefs.getString("prefRearID", "").equals("")) { new AlertDialog.Builder(this).setTitle(R.string.alert_setup_title) .setMessage(R.string.alert_setup_message).setNeutralButton(R.string.alert_setup_button, null) .show(); } sensorMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Message received Log.d(TAG, "Serial Message Received, Length: " + msg.arg1); // Check to see if message is the correct size if (msg.arg1 == 13) { byte[] readBuf = (byte[]) msg.obj; // Validate against checksum int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8] + readBuf[9] + readBuf[10]; if (calculatedCheckSum == readBuf[11]) { // Convert to hex String[] hexData = new String[13]; StringBuilder sbhex = new StringBuilder(); for (int i = 0; i < msg.arg1; i++) { hexData[i] = String.format("%02X", readBuf[i]); sbhex.append(hexData[i]); } // Get sensor position String position = hexData[3]; // Get sensor ID StringBuilder sensorID = new StringBuilder(); sensorID.append(hexData[4]); sensorID.append(hexData[5]); sensorID.append(hexData[6]); sensorID.append(hexData[7]); // Check if sensor ID is new boolean checkID = sensorDB.sensorIdExists(sensorID.toString()); if (!checkID) { // Add sensor ID to db sensorDB.addID(sensorID.toString()); Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_newSensor) + " " + sensorID.toString(), Toast.LENGTH_LONG).show(); } // Only parse message if there is one or more sensor mappings String prefFrontID = sharedPrefs.getString("prefFrontID", ""); String prefRearID = sharedPrefs.getString("prefRearID", ""); if (!prefFrontID.equals("") || !prefRearID.equals("")) { try { // Get temperature int tempC = Integer.parseInt(hexData[8], 16) - 50; double temp = tempC; String temperatureUnit = "C"; // Get tire pressure int psi = Integer.parseInt(hexData[9], 16); double pressure = psi; String pressureUnit = "psi"; // Get battery voltage double voltage = Integer.parseInt(hexData[10], 16) / 50; // Get pressure thresholds int fLowPressure = Integer .parseInt(sharedPrefs.getString("prefFrontLowPressure", "30")); int fHighPressure = Integer .parseInt(sharedPrefs.getString("prefFrontHighPressure", "46")); int rLowPressure = Integer .parseInt(sharedPrefs.getString("prefRearLowPressure", "30")); int rHighPressure = Integer .parseInt(sharedPrefs.getString("prefRearHighPressure", "46")); if (sharedPrefs.getString("preftempf", "0").contains("0")) { // F temp = (9.0 / 5.0) * tempC + 32.0; temperatureUnit = "F"; } int formattedTemperature = (int) (temp + 0.5d); String pressureFormat = sharedPrefs.getString("prefpressuref", "0"); if (pressureFormat.contains("1")) { // KPa pressure = psi * 6.894757293168361; pressureUnit = "KPa"; } else if (pressureFormat.contains("2")) { // Kg-f pressure = psi * 0.070306957965539; pressureUnit = "Kg-f"; } else if (pressureFormat.contains("3")) { // Bar pressure = psi * 0.0689475729; pressureUnit = "Bar"; } int formattedPressure = (int) (pressure + 0.5d); // Get checksum String checksum = hexData[11]; Log.d(TAG, "Sensor ID: " + sensorID.toString() + ", Sensor Position: " + position + ", Temperature(" + temperatureUnit + "): " + String.valueOf(temp) + ", Pressure(" + pressureUnit + "): " + String.valueOf(pressure) + ", Voltage: " + String.valueOf(voltage) + ", Checksum: " + checksum + ", Data: " + sbhex.toString() + ", Bytes:" + msg.arg1); if (sensorID.toString().equals(prefFrontID)) { Log.d(TAG, "Front ID matched"); // Check for data logging enabled if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } logger.write("front", String.valueOf(psi), String.valueOf(tempC), String.valueOf(voltage)); } // Set front tire status if (psi <= fLowPressure) { frontStatus = 1; } else if (psi >= fHighPressure) { frontStatus = 2; } else { frontStatus = 0; } txtFrontPressure .setText(String.valueOf(formattedPressure) + " " + pressureUnit); txtFrontTemperature.setText( String.valueOf(formattedTemperature) + " " + temperatureUnit); txtFrontVoltage.setText(String.format("%.2f", voltage) + " V"); } else if (sensorID.toString().equals(prefRearID)) { Log.d(TAG, "Rear ID matched"); // Check for data logging enabled if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } logger.write("rear", String.valueOf(psi), String.valueOf(tempC), String.valueOf(voltage)); } // Set rear tire status if (psi <= rLowPressure) { rearStatus = 1; } else if (psi >= rHighPressure) { rearStatus = 2; } else { rearStatus = 0; } txtRearPressure .setText(String.valueOf(formattedPressure) + " " + pressureUnit); txtRearTemperature.setText( String.valueOf(formattedTemperature) + " " + temperatureUnit); txtRearVoltage.setText(String.format("%.2f", voltage) + " V"); } // Update txtOutput box and send notification if ((frontStatus == 0) && (rearStatus == 0)) { txtOutput.setText(""); if (notificationManager != null) { notificationManager.cancel(0); } } else if ((frontStatus == 1) && (rearStatus == 0)) { txtOutput .setText(getResources().getString(R.string.alert_lowFrontPressure)); Notify(getResources().getString(R.string.alert_lowFrontPressure)); } else if ((frontStatus == 2) && (rearStatus == 0)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontPressure)); Notify(getResources().getString(R.string.alert_highFrontPressure)); } else if ((rearStatus == 1) && (frontStatus == 0)) { txtOutput.setText(getResources().getString(R.string.alert_lowRearPressure)); Notify(getResources().getString(R.string.alert_lowRearPressure)); } else if ((rearStatus == 2) && (frontStatus == 0)) { txtOutput .setText(getResources().getString(R.string.alert_highRearPressure)); Notify(getResources().getString(R.string.alert_highRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 1)) { txtOutput.setText( getResources().getString(R.string.alert_lowFrontLowRearPressure)); Notify(getResources().getString(R.string.alert_lowFrontLowRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 2)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontHighRearPressure)); Notify(getResources().getString(R.string.alert_highFrontHighRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 2)) { txtOutput.setText( getResources().getString(R.string.alert_lowFrontHighRearPressure)); Notify(getResources().getString(R.string.alert_lowFrontHighRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 1)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontLowRearPressure)); Notify(getResources().getString(R.string.alert_highFrontLowRearPressure)); } // Update color scheme if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { if (frontStatus == 0) { layoutFront.setBackground(background); } else { layoutFront.setBackground(redBackground); } if (rearStatus == 0) { layoutRear.setBackground(background); } else { layoutRear.setBackground(redBackground); } root.setBackgroundColor(getResources().getColor(android.R.color.white)); txtOutput.setBackground(txtOutBackground); txtOutput.setTextColor(getResources().getColor(android.R.color.black)); txtFrontPressure .setTextColor(getResources().getColor(android.R.color.black)); txtFrontTemperature .setTextColor(getResources().getColor(android.R.color.black)); txtFrontVoltage .setTextColor(getResources().getColor(android.R.color.black)); txtRearPressure .setTextColor(getResources().getColor(android.R.color.black)); txtRearTemperature .setTextColor(getResources().getColor(android.R.color.black)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black)); } else { if (frontStatus == 0) { layoutFront.setBackground(backgroundDark); } else { layoutFront.setBackground(redBackgroundDark); } if (rearStatus == 0) { layoutRear.setBackground(backgroundDark); } else { layoutRear.setBackground(redBackgroundDark); } root.setBackgroundColor(getResources().getColor(android.R.color.black)); txtOutput.setBackground(txtOutBackgroundDark); txtOutput.setTextColor(getResources().getColor(android.R.color.white)); txtFrontPressure .setTextColor(getResources().getColor(android.R.color.white)); txtFrontTemperature .setTextColor(getResources().getColor(android.R.color.white)); txtFrontVoltage .setTextColor(getResources().getColor(android.R.color.white)); txtRearPressure .setTextColor(getResources().getColor(android.R.color.white)); txtRearTemperature .setTextColor(getResources().getColor(android.R.color.white)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white)); } } catch (NumberFormatException e) { Log.d(TAG, "Malformed message, unexpected value"); } } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; // Light Sensor Stuff SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if (lightSensor == null) { Log.d(TAG, "Light sensor not found"); } else { float max = lightSensor.getMaximumRange(); sensorManager.registerListener(lightSensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); hasSensor = true; Log.d(TAG, "Light Sensor Max Value: " + max); } // Try to connect to iTPMSystem btConnect(); }
From source file:com.sssemil.advancedsettings.MainService.java
@Override public void onCreate() { super.onCreate(); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE); mDisplayManager.registerDisplayListener(this, null); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(mReceiver, filter); filter = new IntentFilter(); filter.addAction("android.intent.action.ACTION_SHUTDOWN"); registerReceiver(mReceiverOnPowerOff, filter); int timeout = Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(this) .getString("screen_timeout_settings", String.valueOf( Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0)))); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, timeout); }//w ww . j ava 2s . c o m String app = mSharedPreferences.getString("on_theatre_mode_launch_app", "null"); if (!app.equals("null") && !Utils.isPackageInstalled(app, this, 0)) { mSharedPreferences.edit().putString("on_theatre_mode_launch_app", "null").apply(); } new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } try { Settings.System.putInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, Integer.parseInt(PreferenceManager.getDefaultSharedPreferences(MainService.this) .getString("screen_timeout_settings", String.valueOf(Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_OFF_TIMEOUT, 0))))); } catch (SecurityException e) { e.printStackTrace(); } } }).start(); //language settings provider installer new Thread(new Runnable() { @Override public void run() { try { if (!Utils.isPackageInstalled("sssemil.com.languagesettingsprovider", MainService.this, LANG_PROVIDER_VERSION_CODE)) { File apk = new File(Environment.getExternalStorageDirectory(), "wear_languagesettingsprovider-release.apk"); if (apk.exists()) { Log.i(TAG, "apk exists"); apk.delete(); } InputStream inputStream = getAssets().open("wear_languagesettingsprovider-release.apk"); FileOutputStream file = new FileOutputStream(apk); byte buf[] = new byte[4096]; int len = inputStream.read(buf); while (len > 0) { file.write(buf, 0, len); len = inputStream.read(buf); } file.close(); if (apk.exists()) { Log.i(TAG, "installing...."); ShellUtils.CommandResult result = ShellUtils .execCommand("su -c pm install -r " + apk.getPath(), true); if (result.errorMsg == null) { Log.i(TAG, "done"); } else { Log.e(TAG, "failed?"); } } } } catch (IOException e) { e.printStackTrace(); } } }).start(); //vibration intensity stuff try { int amp = Integer.parseInt(mSharedPreferences.getString("vibration_intensity", String.valueOf(Utils.getDeviceCfg(MainService.this).vibroIntensetyDefault))); ProcessBuilder pb = new ProcessBuilder("su", "-c", "echo", amp + ">", Utils.getDeviceCfg(MainService.this).vibroIntensetyPath); pb.start().waitFor(); } catch (InterruptedException | IOException | NullPointerException e) { Log.d(TAG, "catch " + e.toString() + " hit in run", e); } /*new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(1000); int i = Settings.Global.getInt(getContentResolver(), "theater_mode_on"); Log.i("theater_mode_on", String.valueOf(i)); } catch (Settings.SettingNotFoundException | InterruptedException e) { e.printStackTrace(); } } } }).start();*/ GlobalContentObserver contentObserver = new GlobalContentObserver(new Handler()); this.getApplicationContext().getContentResolver() .registerContentObserver(android.provider.Settings.Global.CONTENT_URI, true, contentObserver); }
From source file:com.yohpapa.research.simplemusicplayer.PlaybackService.java
private MediaPlayer initializePlayer() { MediaPlayer player = new MediaPlayer(); player.setAudioStreamType(AudioManager.STREAM_MUSIC); player.setOnPreparedListener(this); player.setOnCompletionListener(this); player.setOnErrorListener(this); player.setOnSeekCompleteListener(this); player.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK); IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); filter.addAction(Intent.ACTION_HEADSET_PLUG); filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED); filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED); registerReceiver(audioOutputChangedEventReceiver, filter); return player; }
From source file:com.air.mobilebrowser.BrowserActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ttsPlayer = new TTSPlayer(this); // Allow for out-of-band additions to thread queue (mainly for cleanup) mHandler = new Handler(); // Prevents user from taking screenshots. getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Load layout mWebView = new AIRWebView(this, this); mWebView.requestFocus(View.FOCUS_DOWN); setContentView(R.layout.activity_browser); FrameLayout layout = (FrameLayout) findViewById(R.id.sec_webview); layout.addView(((AIRWebView) mWebView).getLayout()); // Initialize device monitoring mDeviceStatus = new DeviceStatus(this, this); mDeviceStatus.registerReceivers(this); // By default, lock to landscape setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); mDeviceStatus.lockedOrientation = "landscape"; // Configure the webview configureWebView(mWebView);/*from w ww. j a va 2 s. c o m*/ // Configure Debug Console if (mIsDebugEnabled) { findViewById(R.id.slidingDrawer1).setVisibility(View.VISIBLE); findViewById(R.id.addressBarWrapper).setVisibility(View.VISIBLE); findViewById(R.id.goButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String url = ((EditText) findViewById(R.id.address_bar)).getText().toString(); mWebView.loadUrl(url); } }); } // Load the content SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String url = preferences.getString("pref_default_url", getString(R.string.url_default_location)); // For testing, uncomment the following line to use a custom url: // Check for Internet connectivity if (mDeviceStatus.connectivity == DeviceStatus.CONNECTIVITY_CONNECTED) { mWebView.loadUrl(url); } else { mWebView.loadUrl("about:none"); } // Register BroadcastListener for service intents mSBReceiver = new SBReceiver(this); LocalBroadcastManager.getInstance(super.getApplicationContext()).registerReceiver(mSBReceiver, new IntentFilter(super.getResources().getString(R.string.intent_black_logtag))); LocalBroadcastManager.getInstance(super.getApplicationContext()).registerReceiver(mSBReceiver, new IntentFilter(super.getResources().getString(R.string.intent_micmutechanged))); LocalBroadcastManager.getInstance(super.getApplicationContext()).registerReceiver(mSBReceiver, new IntentFilter(super.getResources().getString(R.string.intent_keyboardchange))); // add receiver for bluetooth keyboard connection/disconnection events LocalBroadcastManager.getInstance(super.getApplicationContext()).registerReceiver(mSBReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED)); LocalBroadcastManager.getInstance(super.getApplicationContext()).registerReceiver(mSBReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED)); IntentFilter testFilter = new IntentFilter(Intent.CATEGORY_HOME); super.getApplicationContext().registerReceiver(mSBReceiver, testFilter); // Get AudioManger mAudioManager = (AudioManager) super.getApplicationContext().getSystemService(Context.AUDIO_SERVICE); // Configure JS Command Processing configureJSCmdHandling(); // Begin monitoring for focus change. startService(new Intent(getApplicationContext(), ActivityWatchService.class)); }
From source file:org.thecongers.mcluster.MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_main); setTitle(R.string.app_name);// ww w . ja v a2 s.c o m View myView = findViewById(R.id.layoutApp); root = myView.getRootView(); layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons); layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft); layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight); layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft); layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight); imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch); imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow); imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow); imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam); imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips); imageABS = (ImageView) findViewById(R.id.imageViewABS); imageLampf = (ImageView) findViewById(R.id.imageViewLampf); imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning); imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel); imageESA = (ImageView) findViewById(R.id.imageViewESA); txtSpeed = (TextView) findViewById(R.id.textViewSpeed); txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit); txtGear = (TextView) findViewById(R.id.textViewGear); txtOdometers = (TextView) findViewById(R.id.textViewOdometer); txtESA = (TextView) findViewById(R.id.textViewESA); imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS); imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth); imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference); progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel); // Backgrounds background = R.drawable.rectangle_bordered; backgroundDark = R.drawable.rectangle_bordered_dark; sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Update layout updateLayout(); if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) { imageButtonTPMS.setImageResource(R.mipmap.blank_icon); imageButtonTPMS.setEnabled(false); } else { imageButtonTPMS.setImageResource(R.mipmap.tpms_off); imageButtonTPMS.setEnabled(true); } // Set initial color scheme updateColors(); if (sharedPrefs.getBoolean("prefNightMode", false)) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark); } // Watch for Bluetooth Changes IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); this.registerReceiver(btReceiver, filter1); this.registerReceiver(btReceiver, filter2); this.registerReceiver(btReceiver, filter3); // Setup Text To Speech text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() { @Override public void onInit(int status) { if (status != TextToSpeech.ERROR) { text2speech.setLanguage(Locale.US); } } }); imageButtonBluetooth.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { canBusConnect(); } }); imageButtonTPMS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (sharedPrefs.getBoolean("prefEnableTPMS", false)) { iTPMSConnect(); } } }); imageButtonPreference.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PopupMenu popup = new PopupMenu(MainActivity.this, v); popup.getMenuInflater().inflate(R.menu.main, popup.getMenu()); popup.setOnMenuItemClickListener(new OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // Settings Menu was selected Intent i = new Intent(getApplicationContext(), org.thecongers.mcluster.UserSettingActivity.class); startActivityForResult(i, SETTINGS_RESULT); return true; case R.id.action_about: // About was selected AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle(getResources().getString(R.string.alert_about_title)); builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about)); builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null); builder.show(); return true; case R.id.action_exit: // Exit menu item was selected if (logger != null) { logger.shutdown(); } finish(); System.exit(0); default: return true; } } }); popup.show(); } }); layoutMiddleRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0")); if (infoViewCurr < (numInfoViewLayouts - 1)) { infoViewCurr = infoViewCurr + 1; } else { infoViewCurr = 0; } SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(infoViewCurr)); editor.commit(); //update layout updateLayout(); } }); canBusMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Check to see if message is the correct size if (msg.arg1 == 27) { byte[] readBuf = (byte[]) msg.obj; String message = new String(readBuf); //Default Units String speedUnit = "km/h"; String odometerUnit = "km"; String temperatureUnit = "C"; String[] splitMessage = message.split(","); if (splitMessage[0].contains("10C")) { //RPM if (sharedPrefs.getString("prefInfoView", "0").contains("0")) { int rpm = (Integer.parseInt(splitMessage[4], 16) * 255 + Integer.parseInt(splitMessage[3], 16)) / 4; txtInfo = (TextView) findViewById(R.id.textViewInfo); txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM); txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40); txtInfo.setText(Integer.toString(rpm) + " RPM"); if (rpm > 8500) { txtInfo.setTextColor(getResources().getColor(R.color.red)); } else { txtInfo.setTextColor(getResources().getColor(android.R.color.black)); } } //Kill Switch String killSwitchValue = splitMessage[5].substring(1); if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) { //Kill Switch On imageKillSwitch.setImageResource(R.mipmap.kill_switch); } else { //Kill Switch Off imageKillSwitch.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("130")) { //Turn indicators String indicatorValue = splitMessage[8]; if (indicatorValue.contains("D7")) { imageLeftArrow.setImageResource(R.mipmap.left_arrow); imageRightArrow.setImageResource(R.mipmap.blank_icon); } else if (indicatorValue.contains("E7")) { imageLeftArrow.setImageResource(R.mipmap.blank_icon); imageRightArrow.setImageResource(R.mipmap.right_arrow); } else if (indicatorValue.contains("EF")) { imageLeftArrow.setImageResource(R.mipmap.left_arrow); imageRightArrow.setImageResource(R.mipmap.right_arrow); } else { imageLeftArrow.setImageResource(R.mipmap.blank_icon); imageRightArrow.setImageResource(R.mipmap.blank_icon); } //High Beam String highBeamValue = splitMessage[7].substring(1); if (highBeamValue.contains("9")) { //High Beam On imageHighBeam.setImageResource(R.mipmap.high_beam); } else { //High Beam Off imageHighBeam.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("294")) { //Front Wheel Speed double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0 + Integer.parseInt(splitMessage[3], 16)) * 0.063); //If 21" Wheel if (sharedPrefs.getString("prefDistance", "0").contains("1")) { frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0 + Integer.parseInt(splitMessage[3], 16)) * 0.064); } if (sharedPrefs.getString("prefDistance", "0").contains("0")) { speedUnit = "MPH"; frontSpeed = frontSpeed / 1.609344; } txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed))); txtSpeedUnit.setText(speedUnit); //ABS String absValue = splitMessage[2].substring(0, 1); if (absValue.contains("B")) { //ABS Off imageABS.setImageResource(R.mipmap.abs); } else { //ABS On imageABS.setImageResource(R.mipmap.blank_icon); } } else if (splitMessage[0].contains("2BC")) { //Engine Temperature engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0; if (engineTempC >= 115.5) { if (engineTempAlertTriggered == false) { engineTempAlertTriggered = true; speakString(getResources().getString(R.string.engine_temp_alert)); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(3)); editor.commit(); updateLayout(); } } else { engineTempAlertTriggered = false; } if (sharedPrefs.getString("prefInfoView", "0").contains("3")) { double engineTemp = engineTempC; if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // F engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0); temperatureUnit = "F"; } txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit); } // Gear String gearValue = splitMessage[6].substring(0, 1); String gear; if (gearValue.contains("1")) { gear = "1"; } else if (gearValue.contains("2")) { gear = "N"; } else if (gearValue.contains("4")) { gear = "2"; } else if (gearValue.contains("7")) { gear = "3"; } else if (gearValue.contains("8")) { gear = "4"; } else if (gearValue.contains("B")) { gear = "5"; } else if (gearValue.contains("D")) { gear = "6"; } else { gear = "-"; } txtGear.setText(gear); //Air Temperature airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0; //Freeze Warning if (airTempC <= 0.0) { if (freezeAlertTriggered == false) { freezeAlertTriggered = true; speakString(getResources().getString(R.string.freeze_alert)); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(3)); editor.commit(); updateLayout(); } } else { freezeAlertTriggered = false; } if (sharedPrefs.getString("prefInfoView", "0").contains("3")) { double airTemp = airTempC; if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // F airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0); temperatureUnit = "F"; } txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit); } } else if (splitMessage[0].contains("2D0")) { //Info Button String infoButtonValue = splitMessage[6].substring(1); if (infoButtonValue.contains("5")) { //Short Press if (!btnPressed) { int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0")); if (infoButton < (numInfoViewLayouts - 1)) { infoButton = infoButton + 1; } else { infoButton = 0; } SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(infoButton)); editor.commit(); //update layout updateLayout(); btnPressed = true; } } else if (infoButtonValue.contains("6")) { //Long Press } else { btnPressed = false; } //Heated Grips String heatedGripSwitchValue = splitMessage[8].substring(0, 1); if (heatedGripSwitchValue.contains("C")) { imageHeatedGrips.setImageResource(R.mipmap.blank_icon); } else if (heatedGripSwitchValue.contains("D")) { if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low); } else { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark); } } else if (heatedGripSwitchValue.contains("E")) { if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high); } else { imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark); } } else { imageHeatedGrips.setImageResource(R.mipmap.blank_icon); } //ESA Damping and Preload String esaDampingValue1 = splitMessage[5].substring(1); String esaDampingValue2 = splitMessage[8].substring(1); String esaPreLoadValue = splitMessage[5].substring(0, 1); if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.smooth_terrain); } else { imageESA.setImageResource(R.mipmap.smooth_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) { txtESA.setText("SOFT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) { txtESA.setText("HARD"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.uneven_terrain); } else { imageESA.setImageResource(R.mipmap.uneven_terrain_dark); } } else if (esaPreLoadValue.contains("1")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("2")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("3")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet); } else { imageESA.setImageResource(R.mipmap.helmet_dark); } } else if (esaPreLoadValue.contains("4")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("5")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("6")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_luggage); } else { imageESA.setImageResource(R.mipmap.helmet_luggage_dark); } } else if (esaPreLoadValue.contains("7")) { txtESA.setText("COMF"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else if (esaPreLoadValue.contains("8")) { txtESA.setText("NORM"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else if (esaPreLoadValue.contains("9")) { txtESA.setText("SPORT"); if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { imageESA.setImageResource(R.mipmap.helmet_helmet); } else { imageESA.setImageResource(R.mipmap.helmet_helmet_dark); } } else { txtESA.setText(""); imageESA.setImageResource(R.mipmap.blank_icon); } //Lamp Fault //TODO: Display/speak Bulb location String lampFaultValue = splitMessage[3].substring(0, 1); if (lampFaultValue.contains("0")) { //None imageLampf.setImageResource(R.mipmap.blank_icon); } else if (lampFaultValue.contains("1")) { //Low Beam imageLampf.setImageResource(R.mipmap.lampf); } else if (lampFaultValue.contains("4")) { //High Beam imageLampf.setImageResource(R.mipmap.lampf); } else if (lampFaultValue.contains("8")) { //Signal Bulb imageLampf.setImageResource(R.mipmap.lampf); } else { //Unknown imageLampf.setImageResource(R.mipmap.lampf); } //Fuel Level double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0) * 100.0; progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent)); //Fuel Level Warning double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30); if (fuelLevelPercent >= fuelWarning) { imageFuelWarning.setImageResource(R.mipmap.blank_icon); fuelAlertTriggered = false; fuelReserveAlertTriggered = false; } else if (fuelLevelPercent == 0) { //Visual Warning imageFuelWarning.setImageResource(R.mipmap.fuel_warning); if (!fuelReserveAlertTriggered) { fuelReserveAlertTriggered = true; //Audio Warning speakString(getResources().getString(R.string.fuel_alert_reserve)); } } else { //Visual Warning imageFuelWarning.setImageResource(R.mipmap.fuel_warning); if (!fuelAlertTriggered) { fuelAlertTriggered = true; //Audio Warning String fuelAlert = getResources().getString(R.string.fuel_alert_begin) + String.valueOf((int) Math.round(fuelLevelPercent)) + getResources().getString(R.string.fuel_alert_end); speakString(fuelAlert); //Suggest nearby fuel stations if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) { // Display prompt to open google maps MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { AlertDialog.Builder builder = new AlertDialog.Builder( MainActivity.this); builder.setTitle(getResources() .getString(R.string.alert_fuel_stations_title)); if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) { // Search for fuel stations nearby builder.setMessage(getResources().getString( R.string.alert_fuel_stations_message_suggestions)); } else if (sharedPrefs.getString("prefFuelStation", "0") .contains("2")) { // Route to nearest fuel station builder.setMessage(getResources().getString( R.string.alert_fuel_stations_message_navigation)); } builder.setPositiveButton( getResources().getString( R.string.alert_fuel_stations_button_positive), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri gmmIntentUri = null; if (sharedPrefs.getString("prefFuelStation", "0") .contains("1")) { // Search for fuel stations nearby gmmIntentUri = Uri .parse("geo:0,0?q=gas+station"); } else if (sharedPrefs .getString("prefFuelStation", "0") .contains("2")) { // Route to nearest fuel station gmmIntentUri = Uri.parse( "google.navigation:q=gas+station"); } Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri); mapIntent .setPackage("com.google.android.apps.maps"); startActivity(mapIntent); } }); builder.setNegativeButton( getResources().getString( R.string.alert_fuel_stations_button_negative), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder.show(); } }); } } } } else if (splitMessage[0].contains("3F8")) { String odometerValue = ""; for (int i = 4; i > 1; i--) { odometerValue = odometerValue + splitMessage[i]; } double odometer = Integer.parseInt(odometerValue, 16); if (sharedPrefs.getString("prefDistance", "0").contains("0")) { odometerUnit = "Miles"; odometer = odometer * 0.6214; } txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit); } imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on); if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } if (logger != null) { logger.write(message); } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; sensorMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Message received Log.d(TAG, "iTPMS Message Received, Length: " + msg.arg1); // Check to see if message is the correct size if (msg.arg1 == 13) { byte[] readBuf = (byte[]) msg.obj; // Validate against checksum int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8] + readBuf[9] + readBuf[10]; if (calculatedCheckSum == readBuf[11]) { // Convert to hex String[] hexData = new String[13]; StringBuilder sbhex = new StringBuilder(); for (int i = 0; i < msg.arg1; i++) { hexData[i] = String.format("%02X", readBuf[i]); sbhex.append(hexData[i]); } // Get sensor position String position = hexData[3]; // Get sensor ID StringBuilder sensorID = new StringBuilder(); sensorID.append(hexData[4]); sensorID.append(hexData[5]); sensorID.append(hexData[6]); sensorID.append(hexData[7]); // Only parse message if there is one or more sensor mappings String prefFrontID = sharedPrefs.getString("prefFrontID", ""); String prefRearID = sharedPrefs.getString("prefRearID", ""); try { // Get temperature int tempC = Integer.parseInt(hexData[8], 16) - 50; double temp = tempC; String temperatureUnit = "C"; // Get tire pressure int psi = Integer.parseInt(hexData[9], 16); double pressure = psi; String pressureUnit = "psi"; // Get battery voltage double voltage = Integer.parseInt(hexData[10], 16) / 50; // Get pressure thresholds int lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30")); int highPressure = Integer .parseInt(sharedPrefs.getString("prefHighPressure", "46")); if (sharedPrefs.getString("prefTempF", "0").contains("1")) { // F temp = (9.0 / 5.0) * tempC + 32.0; temperatureUnit = "F"; } int formattedTemperature = (int) (temp + 0.5d); String pressureFormat = sharedPrefs.getString("prefPressureF", "0"); if (pressureFormat.contains("1")) { // KPa pressure = psi * 6.894757293168361; pressureUnit = "KPa"; } else if (pressureFormat.contains("2")) { // Kg-f pressure = psi * 0.070306957965539; pressureUnit = "Kg-f"; } else if (pressureFormat.contains("3")) { // Bar pressure = psi * 0.0689475729; pressureUnit = "Bar"; } int formattedPressure = (int) (pressure + 0.5d); // Get checksum String checksum = hexData[11]; if (Integer.parseInt(hexData[3], 16) <= 2) { Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16)); frontPressurePSI = psi; // Set front tire status if (psi <= lowPressure) { frontStatus = 1; } else if (psi >= highPressure) { frontStatus = 2; } else { frontStatus = 0; } if (sharedPrefs.getString("prefInfoView", "0").contains("2")) { txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS); txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50); txtFrontTPMS .setText(String.valueOf(formattedPressure) + " " + pressureUnit); if (frontStatus != 0) { txtFrontTPMS.setTextColor(getResources().getColor(R.color.red)); } else { txtFrontTPMS .setTextColor(getResources().getColor(android.R.color.black)); } } } else if (Integer.parseInt(hexData[3], 16) > 2) { Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16)); rearPressurePSI = psi; // Set rear tire status if (psi <= lowPressure) { rearStatus = 4; } else if (psi >= highPressure) { rearStatus = 5; } else { rearStatus = 3; } if (sharedPrefs.getString("prefInfoView", "0").contains("2")) { txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS); txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50); txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit); if (rearStatus != 3) { txtRearTPMS.setTextColor(getResources().getColor(R.color.red)); } else { txtRearTPMS .setTextColor(getResources().getColor(android.R.color.black)); } } } // Reset icon if ((frontStatus == 0) && (rearStatus == 3)) { imageButtonTPMS.setImageResource(R.mipmap.tpms_on); } if ((frontStatus != 0) || (rearStatus != 3)) { imageButtonTPMS.setImageResource(R.mipmap.tpms_alert); SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("prefInfoView", String.valueOf(2)); editor.commit(); updateLayout(); int delay = (Integer .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000); String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus)); if (alertTimer == 0) { alertTimer = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); long duration = (currentTime - alertTimer); if (!currStatus.equals(lastStatus) || duration >= delay) { alertTimer = 0; if ((frontStatus == 1) && (rearStatus == 3)) { speakString( getResources().getString(R.string.alert_lowFrontPressure)); } else if ((frontStatus == 2) && (rearStatus == 3)) { speakString( getResources().getString(R.string.alert_highFrontPressure)); } else if ((rearStatus == 4) && (frontStatus == 0)) { speakString( getResources().getString(R.string.alert_lowRearPressure)); } else if ((rearStatus == 5) && (frontStatus == 0)) { speakString( getResources().getString(R.string.alert_highRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 4)) { speakString(getResources() .getString(R.string.alert_lowFrontLowRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 5)) { speakString(getResources() .getString(R.string.alert_highFrontHighRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 5)) { speakString(getResources() .getString(R.string.alert_lowFrontHighRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 4)) { speakString(getResources() .getString(R.string.alert_highFrontLowRearPressure)); } lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus)); } } } } catch (NumberFormatException e) { Log.d(TAG, "Malformed message, unexpected value"); } if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } if (logger != null) { logger.write(String.valueOf(sbhex)); } } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; // Sensor Stuff SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); // Light if (lightSensor == null) { Log.d(TAG, "Light sensor not found"); } else { sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); hasSensor = true; } // Compass sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI); sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI); // Try to connect to CANBusGateway canBusConnect(); // Connect to iTPMS if enabled if (sharedPrefs.getBoolean("prefEnableTPMS", false)) { iTPMSConnect(); } }
From source file:com.cw.litenote.main.MainAct.java
void doCreate(Bundle savedInstanceState) { System.out.println("MainAct / _doCreate"); // Will create default contents: by assets or by initial tables if (Pref.getPref_will_create_default_content(this)) { if (Define.DEFAULT_CONTENT == Define.BY_ASSETS) createDefaultContent_byAssets(); else if ((Define.DEFAULT_CONTENT == Define.BY_INITIAL_TABLES) && (Define.INITIAL_FOLDERS_COUNT > 0)) createDefaultContent_byInitialTables(); }// w ww .j a v a 2s . c o m mFolderTitles = new ArrayList<>(); // Context context = getApplicationContext(); //Add note with the link which got from other App String intentLink = mMainUi.addNote_IntentLink(getIntent(), mAct); if (!Util.isEmptyString(intentLink)) { finish(); // LiteNote not running at first, keep closing return; } else { // check DB final boolean ENABLE_DB_CHECK = false;//true;//false if (ENABLE_DB_CHECK) { // list all folder tables FolderUi.listAllFolderTables(mAct); // recover focus DB_folder.setFocusFolder_tableId(Pref.getPref_focusView_folder_tableId(this)); DB_page.setFocusPage_tableId(Pref.getPref_focusView_page_tableId(this)); } //if(ENABLE_DB_CHECK) // get focus folder table Id, default folder table Id: 1 DB_drawer dB_drawer = new DB_drawer(this); dB_drawer.open(); if (savedInstanceState == null) { for (int i = 0; i < dB_drawer.getFoldersCount(false); i++) { if (dB_drawer.getFolderTableId(i, false) == Pref.getPref_focusView_folder_tableId(this)) { FolderUi.setFocus_folderPos(i); System.out.println("MainAct / _mainAction / FolderUi.getFocus_folderPos() = " + FolderUi.getFocus_folderPos()); } } Audio_manager.setPlayerState(Audio_manager.PLAYER_AT_STOP); } dB_drawer.close(); // enable ActionBar app icon to behave as action to toggle nav drawer // getActionBar().setDisplayHomeAsUpEnabled(true); // getActionBar().setHomeButtonEnabled(true); // getActionBar().setBackgroundDrawable(new ColorDrawable(ColorSet.getBarColor(mAct))); mContext = getBaseContext(); // add on back stack changed listener mFragmentManager = getSupportFragmentManager(); mOnBackStackChangedListener = this; mFragmentManager.addOnBackStackChangedListener(mOnBackStackChangedListener); } isAddedOnNewIntent = false; // Register Bluetooth device receiver if (Build.VERSION.SDK_INT < 21) { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); this.registerReceiver(bluetooth_device_receiver, filter); } else // if(Build.VERSION.SDK_INT >= 21) { // Media session: to receive media button event of bluetooth device // new media browser instance and create BackgroundAudioService instance: support notification if (mMediaBrowserCompat == null) { mMediaBrowserCompat = new MediaBrowserCompat(mAct, new ComponentName(mAct, BackgroundAudioService.class), mMediaBrowserCompatConnectionCallback, mAct.getIntent().getExtras()); if (!mMediaBrowserCompat.isConnected()) mMediaBrowserCompat.connect();//cf: https://stackoverflow.com/questions/43169875/mediabrowser-subscribe-doesnt-work-after-i-get-back-to-activity-1-from-activity mCurrentState = STATE_PAUSED; } } // init audio parameters MainAct.mPlaying_folderPos = -1; Audio_manager.setPlayerState(Audio_manager.PLAYER_AT_STOP); TabsHost.audioPlayTabPos = -1; }
From source file:com.cw.litenote.note.Note.java
@Override protected void onResume() { super.onResume(); System.out.println("Note / _onResume"); setLayoutView();//from ww w . jav a2 s. c om isPagerActive = true; if (canShowFullScreenPicture()) Note.setPictureMode(); else Note.setViewAllMode(); setOutline(act); // Register Bluetooth device receiver if (Build.VERSION.SDK_INT < 21) { IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); this.registerReceiver(mReceiver, filter); } else // Build.VERSION.SDK_INT >= 21 { // Media session: to receive media button event of bluetooth device // new media browser instance and create BackgroundAudioService instance: support notification if (MainAct.mMediaBrowserCompat == null) { MainAct.mMediaBrowserCompat = new MediaBrowserCompat(act, new ComponentName(act, BackgroundAudioService.class), MainAct.mMediaBrowserCompatConnectionCallback, act.getIntent().getExtras()); } if (!MainAct.mMediaBrowserCompat.isConnected()) MainAct.mMediaBrowserCompat.connect(); MainAct.mCurrentState = MainAct.STATE_PAUSED; } }
From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Bundle intentExtras = intent.getExtras(); if (owner == null) return;// www. j a v a 2s . c o m owner.getWebSocketManager().sendIntentToWebSocket(action, intentExtras); //capture the "battery changed" event if (action.equals(Intent.ACTION_BATTERY_CHANGED)) { int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); DeviceInfoOld.battery = level * 100 / scale; int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1); boolean bCharging = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB; owner.setBatteryCharging(bCharging); dataMonitorStats.setBattery(bCharging, DeviceInfoOld.battery); } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) { owner.setBatteryCharging(true); dataMonitorStats.setBattery(true, null); } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) { owner.setBatteryCharging(false); dataMonitorStats.setBattery(false, null); } else if (action.equals(Intent.ACTION_VIEW)) { //this is supposed to trigger the update event //owner.triggerUpdateEvent(false, false); } else if (action.equals(CommonIntentActionsOld.ACTION_START_UI)) { String packagename = intent.getStringExtra("packagename"); String mypackagename = context.getPackageName(); PreferenceManager.getDefaultSharedPreferences(context).edit() .putString(PreferenceKeys.Miscellaneous.YEILDED_SERVICE, packagename).commit(); // If the UI started on a different MMC app UI, then we stop this service until this UI is launched if (!packagename.equals(mypackagename)) // This will exit the service when safe, and won't restart it because it will be yeilded owner.restartSelf(); } else if (action.equals(UPDATE_ACTION)) { owner.getEventManager().triggerUpdateEvent(false, false); } else if (action.equals(COLDRESET_ACTION)) { //this is supposed to trigger the update event owner.getGpsManager().coldStart("triggered by user"); } else if (action.equals(EMAIL_CSV)) { //this is supposed to trigger the update event owner.requestCsvEmail(); } else if (action.equals(SPEED_TEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); //owner.triggerSMSTest(trigger); owner.getEventManager().queueActiveTest(EventType.MAN_SPEEDTEST, trigger); } else if (action.equals(RUN_WEBSOCKET)) { //this is supposed to trigger a speed test boolean bStart = intent.getBooleanExtra(EXTRA_START_WEBSOCKET, true); owner.getWebSocketManager().runWebSocket(bStart); //owner.triggerSpeedTest(trigger); } else if (action.equals(ACTIVE_TEST)) { //this is supposed to trigger a speed test int evType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0); EventType eventType = EventType.get(evType); int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); owner.getEventManager().queueActiveTest(eventType, trigger); } else if (action.equals(SMS_TEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); //owner.triggerSMSTest(trigger); owner.getEventManager().queueActiveTest(EventType.SMS_TEST, trigger); } else if (action.contains(SMS_DELIVERED)) { //add delivery time to connection history int identifier = intent.getIntExtra("identifier", 0); //in case we need to search connection list to find which SMS long deliveryTime = 0; switch (getResultCode()) { case Activity.RESULT_OK: deliveryTime = System.currentTimeMillis(); break; case SmsManager.RESULT_ERROR_GENERIC_FAILURE: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_NO_SERVICE: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_NULL_PDU: deliveryTime = -1; break; case SmsManager.RESULT_ERROR_RADIO_OFF: deliveryTime = -1; break; } owner.getEventManager().handleSMSDeliverNotification(identifier, deliveryTime); } else if (action.equals(LATENCY_TEST)) { int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0); owner.getEventManager().queueActiveTest(EventType.LATENCY_TEST, trigger); //owner.runLatencyTest(false); } else if (action.equals(ACTION_STOP_SPEEDTEST)) { owner.getEventManager().killSpeedTest(); } else if (action.equals(ACTION_STOP_VIDEOTEST)) { int testType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0); owner.getEventManager().killActiveTest(testType); } else if (action.equals(ROAMING_ON)) { dataMonitorStats.setRoaming(true); } else if (action.equals(ROAMING_OFF)) { dataMonitorStats.setRoaming(false); } else if (action.equals("android.intent.action.ANY_DATA_STATE")) { String apn = intentExtras.getString("apn"); String state = intentExtras.getString("state"); String apnType = intentExtras.getString("apnType"); String extras = apnType + "" + state; if (state.equals("CONNECTED") && !apnType.equals("default")) extras = extras + "!"; if (apnType != null && apnType.equals("default") && apn != null) { SharedPreferences securePref = MainService.getSecurePreferences(context); securePref.edit().putString(PreferenceKeys.Miscellaneous.KEY_APN, apn).commit(); } } else if (action.equals("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN")) { String apn = intentExtras.getString("apn"); String apnType = intentExtras.getString("apnType"); String extras = apn + "," + apnType; } else if (action.equals("android.intent.action.ACTION_DATA_CONNECTION_FAILED")) { String phoneName = intentExtras.getString("phoneName"); String reason = intentExtras.getString("reason"); String extras = phoneName + "," + reason; } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { if (owner.getUsageLimits().getDormantMode() > 0) return; // wifi state change may trigger the event queue to be sent //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "NETWORK_STATE_CHANGED_ACTION", ""); owner.wifiStateChange((NetworkInfo) intentExtras.getParcelable(WifiManager.EXTRA_NETWORK_INFO)); owner.trackAccessPoints(0); dataMonitorStats.setWifi(PhoneState.isNetworkWifi(owner)); } else if (action.equals(WIMAX_STATE_CHANGE)) { owner.trackAccessPoints(0); } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { // BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // BluetoothClass bclass = device.getBluetoothClass(); // int major = bclass.getMajorDeviceClass(); // if (major == 1024) // owner.setBTHeadsetState(1); // owner.trackAccessPoints(); } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) { owner.trackAccessPoints(0); } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { // BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // BluetoothClass bclass = device.getBluetoothClass(); // int major = bclass.getMajorDeviceClass(); // if (major == 1024) // owner.setBTHeadsetState(0); // owner.trackAccessPoints(); } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { try { int state = intent.getIntExtra("state", -1); owner.setHeadsetState(state); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive", "error receiving Intent.ACTION_HEADSET_PLUG: " + e); } } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) { int state = intent.getIntExtra("state", -1); owner.setHeadsetState(state); } else if (action.equals(CommonIntentActionsOld.ACTION_START_VOICETEST)) { //this is supposed to trigger a speed test int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_VQ_TRIGGER, 0); owner.getVQManager().runTest(trigger); } else if (action.equals(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE)) { owner.getVQManager().runTest(10); } else if (action.equals(CommonIntentActionsOld.ACTION_STOP_VOICETEST)) { owner.getVQManager().killTest(); } else if (action.equals(RESTART_MMC_SERVICE)) { owner.restartNextIdle(); } else if (action.equals(STOP_TRACKING_ACTION)) { owner.getEventManager().stopTracking(); } else if (action.equals(Intent.ACTION_SCREEN_OFF)) { try { dataMonitorStats.setScreen(false); SignalEx mmcSignal = new SignalEx(); owner.getPhoneStateListener().processNewMMCSignal(mmcSignal); if (owner.getTravelDetector() != null) { owner.getPhoneState().screenChanged(false); owner.getEventManager().screenChanged(false); } } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive", "received action SCREEN_OFF, calling MainService.processNewMMCSignal()", e); } } else if (action.equals(Intent.ACTION_SCREEN_ON)) { dataMonitorStats.setScreen(true); if (owner.getTravelDetector() != null) { owner.getPhoneState().screenChanged(true); owner.getEventManager().screenChanged(true); } } else if (action.equals(ACTION_ALARM_MINUTE)) { // CPU wakes very briefly only in order to spur cellid updates owner.getTravelDetector().triggerTravelCheck(); QosAPI.checkHostApp(context); } else if (action.equals(ACTION_TRACKING_5MINUTE)) { owner.getTrackingManager().runTracking(); } else if (action.equals(ACTION_TRACKING_1MINUTE)) { LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "ACTION_TRACKING_1MINUTE"); owner.getTrackingManager().runTrackingTests(); } else if (action.equals(ACTION_ALARM_3HOUR)) { dataMonitorStats.prepareAllStatistics(); owner.getEventManager().triggerUpdateEvent(true, false); // Calendar cal = Calendar.getInstance(); // int hour = cal.get (Calendar.HOUR_OF_DAY); // //If 12pm to 3 am // if(((hour >= 0 && hour <= 3) || hour == 24) && owner.isNetworkWifi()) { // //See if transit info needs to be downloaded // // //Don't allow the app to shut down until the work is done, keep the CPU running // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_ALARM_3HOUR, wakelock turned on and checking transit " // + "info uptodate at 24-hour: " + hour); // wakeLock.acquire(); // // downloadAreasIfOutOfDate(); // } } // else if(action.equals(ACTION_TRANSIT_DL_DONE)) { // //Allow CPU to move on // if(wakeLock != null) { // wakeLock.release(); // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "received action ACTION_TRANSIT_DONE, wakelock turned off"); // } // } // else if(action.equals(ACTION_TRANSIT_DL_START)) { // //Don't allow the app to shut down until the work is done, keep the CPU running // MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_TRANSIT_DL_START, wakelock turned on and downloading transit if was requested"); // wakeLock.acquire(); // // downloadAreasIfOutOfDate(); // } else if (action.equals(ACTION_ALARM_SCANAPPS)) { int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner) .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0); // run datamonitor if enabled if (intervalDM > 0) { dataMonitorStats.scanApps(); dataMonitorStats.getRunningAppsString(false); // for debug } // Also using this timer for GCM heartbeats (its a 5 minute heartbeat to tell Google Cloud Messaging to check the socket more often for more reliable push messages) // 2 independent timers might wake up device twice as often, doubling the battery impact, so I'm forcing it to use one for both cases // boolean useHeartbeat = PreferenceManager.getDefaultSharedPreferences(owner).getBoolean("KEY_GCM_HEARTBEAT", false); // if (useHeartbeat) { // GcmKeepAlive gcm = new GcmKeepAlive(owner); // gcm.broadcastIntents(); // } } else if (action.equals(ACTION_ALARM_15MINUTE)) { int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner) .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0); // run datamonitor if enabled if (intervalDM > 0) { boolean firstBucketDone = PreferenceManager.getDefaultSharedPreferences(owner) .getBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, false); if (!firstBucketDone) { //if false, first bucket needs to be done dataMonitorStats.firstBucket(); dataMonitorStats.monitor(); PreferenceManager.getDefaultSharedPreferences(owner).edit() .putBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, true).commit(); LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "First bucket at: " + System.currentTimeMillis() / 1000); } else { dataMonitorStats.monitor(); //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "15 min bucket at: " + System.currentTimeMillis()/1000); } } // regardless, still make sure GPS is idle unless needed owner.getGpsManager().safeguardGps(); } else if (action.equals(GPS_STATE_ON)) { dataMonitorStats.setGps(true); } else if (action.equals(GPS_STATE_OFF)) { dataMonitorStats.setGps(false); } else if (action.equals(PHONE_CALL_CONNECT)) { dataMonitorStats.setPhone(true); } else if (action.equals(PHONE_CALL_DISCONNECT)) { dataMonitorStats.setPhone(false); } else if (action.equals(HANDOFF)) { dataMonitorStats.handoff(); } else if (action.equals(MANUAL_TRANSIT_START)) { long lat = intent.getIntExtra("latitude", 0); long lon = intent.getIntExtra("longitude", 0); Location location = new Location(""); location.setLatitude(lat / 1000000.0); location.setLongitude(lon / 1000000.0); location.setAccuracy(-3); // PreferenceManager.getDefaultSharedPreferences(owner).edit().putString( // PreferenceKeys.Miscellaneous.SURVEY_COMMAND,).commit(); PreferenceManager.getDefaultSharedPreferences(owner).edit() .putString("transitEvent", String.valueOf(lat) + "," + String.valueOf(lon)).commit(); reportManager.manualTransitEvent = owner.getEventManager().triggerSingletonEvent(EventType.MAN_TRANSIT); reportManager.manualTransitEvent.setLocation(location, 0); owner.getTravelDetector().setTravelling(false); } else if (action.equals(MANUAL_TRANSIT_END)) { if (reportManager.manualTransitEvent == null) return; String accelData = intent.getStringExtra("accelerometer"); int stationFrom = intent.getIntExtra("stationFrom", 0); int stationTo = intent.getIntExtra("stationTo", 0); int duration = intent.getIntExtra("duration", 0); int corrected = intent.getIntExtra("corrected", 0); if (corrected != 0) { Location location = reportManager.manualTransitEvent.getLocation(); location.setAccuracy(-4); } reportManager.manualTransitEvent.setAppData(accelData); //TODO want this to really be in appdata? reportManager.manualTransitEvent.setLookupid1(stationFrom); reportManager.manualTransitEvent.setLookupid2(stationTo); reportManager.manualTransitEvent.setDuration(duration); owner.getEventManager().unstageAndUploadEvent(reportManager.manualTransitEvent, null); reportManager.manualTransitEvent = null; } else if (action.equals(MANUAL_TRANSIT_CANCEL)) { if (reportManager.manualTransitEvent != null) { owner.getEventManager().unstageEvent(reportManager.manualTransitEvent); ReportManager reportManager = ReportManager.getInstance(owner); reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(), "timestamp > ? And accuracy = 3", new String[] { String.valueOf(reportManager.manualTransitEvent.getEventTimestamp()) }); reportManager.manualTransitEvent = null; } } else if (action.equals(MANUAL_PLOTTING_START)) { int floor = intent.getIntExtra("floor", 0); // int type = intent.getIntExtra("type", -1); //1(indoor) or 2(outdoor) int topFloor = intent.getIntExtra("top", -1); int lat = intent.getIntExtra("latitude", -1); int lng = intent.getIntExtra("longitude", -1); long osm_id = intent.getLongExtra("osm_id", 0); String poly = intent.getStringExtra("poly"); reportManager.manualPlottingEvent = owner.getEventManager() .triggerSingletonEvent(EventType.MAN_PLOTTING); reportManager.manualPlottingEvent.setEventIndex(floor); reportManager.manualPlottingEvent.setDuration(topFloor); reportManager.manualPlottingEvent.setBuildingID(osm_id); reportManager.manualPlottingEvent.setAppData(poly); Location location = new Location(""); location.setLatitude(lat / 1000000.0); location.setLongitude(lng / 1000000.0); location.setAccuracy(-1); reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "latitude", Double.toString(location.getLatitude())); reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "longitude", Double.toString(location.getLongitude())); reportManager.manualPlottingEvent.setLocation(location, 0); presetEventId(reportManager.manualPlottingEvent); // reserve an EventID for this manual sampling event, to be used for Share links owner.getTravelDetector().setTravelling(false); } else if (action.equals(MANUAL_PLOTTING_END)) { LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "MANUAL_PLOTTING_END"); // owner.getEventManager().unstageEvent(manulaPlottingEvent); //does not upload if (reportManager.manualPlottingEvent != null) owner.getEventManager().unstageAndUploadEvent(reportManager.manualPlottingEvent, null); //After the event was submitted, reset it so we don't restore an old event in ManualMapping reportManager.manualPlottingEvent = null; } else if (action.equals(MANUAL_PLOTTING_CANCEL)) { if (reportManager.manualPlottingEvent != null) { reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(), "timestamp > ? And accuracy < 0", new String[] { String.valueOf(reportManager.manualPlottingEvent.getEventTimestamp()) }); reportManager.manualPlottingEvent = null; } } // else if(intent.getAction().equals(MMS_RECEIVED)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_RECEIVED", intentExtras.toString()); // } // else if(intent.getAction().equals(MMS_SENT)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_SENT", intentExtras.toString()); // } // else if(intent.getAction().equals(SMS_REJECTED)) { // LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived SMS_REJECTED", intentExtras.toString()); // } else if (intent.getAction().equals(SMS_RECEIVED)) { SmsMessage[] msgs = null; // String msg_from; if (intentExtras == null) return; Object[] pdus = (Object[]) intentExtras.get("pdus"); msgs = new SmsMessage[pdus.length]; String[] msgBody = new String[msgs.length]; for (int i = 0; i < msgs.length; i++) { msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); // msg_from = msgs[i].getOriginatingAddress(); String msg = msgs[i].getMessageBody().trim(); if (msg.length() > 10) { msg = msg.substring(1, msg.length() - 1); msg = "{" + msg + "}"; } msgBody[i] = msg; } handleCommands(msgBody, true, 0); } else if (action.equals(VIEWING_SIGNAL)) { owner.setEnggQueryTime(); } else if (intent.getAction().equals(SURVEY)) { if (intentExtras == null) return; int surveyid = intentExtras.getInt(SURVEY_EXTRA); postSurvey(surveyid); } else if (intent.getAction().equals(GCM_MESSAGE)) { if (intentExtras == null) return; try { String msg = intentExtras.getString(GCM_MESSAGE_EXTRA); long starttime = intentExtras.getLong("GCM_STARTTIME_EXTRA"); EventResponse eventResponse = gson.fromJson(msg, EventResponse.class); eventResponse.init(); eventResponse.setStartTime(starttime); eventResponse.handleEventResponse(owner, true); } catch (Exception e) { LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceived GCM_MESSAGE", "exception", e); } } else if (intent.getAction().equals(COMMAND)) { if (intentExtras == null) return; String commands = intentExtras.getString(COMMAND_EXTRA); if (commands == null) return; long starttime = intent.getLongExtra("STARTTIME_EXTRA", 0); String[] msgs = null; try { JSONArray cmds = new JSONArray(commands); msgs = new String[cmds.length()]; for (int j = 0; j < cmds.length(); j++) msgs[j] = cmds.getJSONObject(j).toString(); } catch (JSONException e) { // TODO Auto-generated catch block //e.printStackTrace(); } //commands = commands.replace("[", ""); //commands = commands.replace("]", ""); //String msgs[] = commands.split("/"); handleCommands(msgs, false, starttime); } else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) { int val = 0; val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); String msg = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE"); String msg2 = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_MESSAGE"); //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "String CALL_DISCONNECT_CAUSE", msg); //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "Int CALL_DISCONNECT_CAUSE", ""+val); } else if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) { String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER); //if (phoneNumber != null) // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "NEW_OUTGOING_CALL", phoneNumber); } else if (intent.getAction().equals("android.intent.action.PRECISE_CALL_STATE")) { int val = 0; //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); int state_ringing = intent.getIntExtra("ringing_state", -1); int state_foreground = intent.getIntExtra("foreground_state", -1); int state_background = intent.getIntExtra("background_state", -1); int disconnect_cause = intent.getIntExtra("disconnect_cause", -1); int precise_disconnect_cause = intent.getIntExtra("precise_disconnect_cause", -1); PreciseCallCodes precisecall = new PreciseCallCodes(state_ringing, state_foreground, state_background, disconnect_cause, precise_disconnect_cause); LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "PRECISE_CALL_STATE", precisecall.toString()); owner.getPhoneStateListener().onPreciseCallState(precisecall); } else if (intent.getAction().equals("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED")) { int val = 0; //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1); int state = intent.getIntExtra("state", -1); int networkType = intent.getIntExtra("networkType", -1); String reason = intent.getStringExtra("reason"); String failCause = intent.getStringExtra("failCause"); String apnType = intent.getStringExtra("apnType"); String apn = intent.getStringExtra("apn"); Object linkProperties = intent.getParcelableExtra("linkProperties"); if (!apnType.equals("default")) return; // if (failCause != null && failCause.length() > 0) // { // String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // if (linkProperties != null) // { // msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED linkProperties:%s", linkProperties.toString()); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // } // } // else if (reason != null && reason.length() > 0) // { // String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // if (linkProperties != null) // { // msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED linkProperties:%s", linkProperties.toString()); // MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg); // } // } } else if (intent.getAction().equals("org.restcomm.android.CONNECT_FAILED") || intent.getAction().equals("org.restcomm.android.CALL_STATE") || intent.getAction().equals("org.restcomm.android.DISCONNECT_ERROR")) { owner.getPhoneStateListener().getRestCommManager().handleIntent(owner, intent); } else if (intent.getAction().equals(ACTION_RADIOLOG_DISCONNECT)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String cause = intent.getStringExtra(EXTRA_RADIOLOG_DISC_CAUSE); owner.getPhoneStateListener().onDisconnect(time, cause); } else if (intent.getAction().equals(ACTION_RADIOLOG_CONNECT)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String state = intent.getStringExtra(EXTRA_RADIOLOG_CONN_STATE); owner.getPhoneStateListener().onConnect(time, state); } else if (intent.getAction().equals(ACTION_RADIOLOG_NEIGHBORS)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String neighbors = intent.getStringExtra(EXTRA_RADIOLOG_NEIGHBORS); //owner.onConnect(time, state); } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMODE)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String jsonstr = intent.getStringExtra(EXTRA_RADIOLOG_SVC_JSON); JSONObject json = null; try { json = new JSONObject(jsonstr); } catch (Exception e) { } String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT); String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME); owner.getPhoneStateListener().onServiceMode(time, json, values, name); } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMENU)) { String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME); String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT); String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME); owner.getPhoneStateListener().onServiceMenu(time, values, name); } else if (intent.getAction().equals(ACTION_MMCSYS_VERSION)) { Integer version = intent.getIntExtra(EXTRA_MMCSYS_VERSION, 0); owner.onSvcModeVersion(version); } else if (intent.getAction().equals(ACTION_RADIOLOG_ERROR)) { String error = intent.getStringExtra(EXTRA_RADIOLOG_ERROR); String details = intent.getStringExtra(EXTRA_RADIOLOG_ERROR_DETAIL); LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "RilReader", error, details); //owner.onConnect(time, state); } }