Example usage for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECTED

List of usage examples for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECTED

Introduction

In this page you can find the example usage for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECTED.

Prototype

String ACTION_ACL_DISCONNECTED

To view the source code for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECTED.

Click Source Link

Document

Broadcast Action: Indicates a low level (ACL) disconnection from a remote device.

Usage

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();/*  ww  w  . j  a v  a  2 s .c o  m*/
    }

    //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;//ww w  . j  av a2s .  co 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//  w  w  w.  j  a  v a  2s . c  om
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.xclong.vehiclemonitordemo.service.CommunicationService.java

@Override
public void onCreate() {
    super.onCreate();
    TAG = this.getClass().getSimpleName();
    communicationService = CommunicationService.newInstance();
    mNotificationManager = NotificationManagerCompat.from(getApplicationContext());

    Log.e(TAG, "??");
    //TODO /*w w  w.ja  v  a  2s.  c  o m*/
    if (!hasRegesiger) {
        hasRegesiger = true;
        Log.e(TAG, "");
        IntentFilter filter1 = new IntentFilter(Const.ACTION2);
        registerReceiver(receiver, filter1);

        IntentFilter filter2 = new IntentFilter(Const.ACTION3);
        registerReceiver(receiver, filter2);

        IntentFilter filter3 = new IntentFilter(Const.ACTION6);
        registerReceiver(receiver, filter3);

        IntentFilter filter4 = new IntentFilter(Const.ACTION5);
        registerReceiver(receiver, filter4);

        IntentFilter filter5 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        registerReceiver(receiver, filter5);

        IntentFilter filter6 = new IntentFilter(Const.ACTION7);
        registerReceiver(receiver, filter6);

        IntentFilter filter7 = new IntentFilter(Const.ACTION9);
        registerReceiver(receiver, filter7);

    }
    vdao = new VehicledInfoDao(this);
    adao = new AbnormalInfoDao(this);

    connectSocket();
}

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);
    }//from w  w w.ja  v a2s. co 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);/*w ww.j  av a2s .c om*/

    // 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);/*from   ww  w .jav a 2s  .  c om*/

    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.cypress.cysmart.HomePageActivity.java

@Override
protected void onResume() {
    mApplicationInBackground = false;//  w  w  w  . ja v a  2s .  co m
    BLUETOOTH_STATUS_FLAG = true;
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    registerReceiver(mBondStateReceiver, intentFilter);
    super.onResume();
}

From source file:lu.fisch.canze.activities.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    // always create an instance

    // needed to get strings from resources in non-Activity classes
    res = getResources();//from   w  w w.  j  av  a2  s.  c  o  m

    // dataLogger = DataLogger.getInstance();
    dataLogger = new DataLogger();

    debug("MainActivity: onCreate");

    instance = this;

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // navigation bar
    AppSectionsPagerAdapter appSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
    actionBar = getSupportActionBar();
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    //actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    viewPager = (ViewPager) findViewById(R.id.main);
    viewPager.setAdapter(appSectionsPagerAdapter);
    viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            //actionBar.setSelectedNavigationItem(position);
            updateActionBar();
        }
    });
    updateActionBar();

    /*
    for (int i = 0; i < appSectionsPagerAdapter.getCount(); i++) {
    actionBar.addTab(
            actionBar.newTab()
                    .setText(appSectionsPagerAdapter.getPageTitle(i))
                    .setTabListener(MainActivity.this));
    }
    */

    // load the initial "main" fragment
    //loadFragement(new MainFragment());

    setTitle(TAG + " - not connected");
    setBluetoothState(BLUETOOTH_DISCONNECTED);

    // tabs
    //final ActionBar actionBar = getSupportActionBar();
    // Specify that tabs should be displayed in the action bar.

    // open the database
    CanzeDataSource.getInstance(getBaseContext()).open();
    // cleanup
    CanzeDataSource.getInstance().cleanUp();

    // setup cleaning (once every hour)
    Runnable cleanUpRunnable = new Runnable() {
        @Override
        public void run() {
            CanzeDataSource.getInstance().cleanUp();
        }
    };
    Handler handler = new Handler();
    handler.postDelayed(cleanUpRunnable, 60 * 1000);

    // register for bluetooth changes
    IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(broadcastReceiver, intentFilter);

    // configure Bluetooth manager
    BluetoothManager.getInstance().setBluetoothEvent(new BluetoothEvent() {
        @Override
        public void onBeforeConnect() {
            setBluetoothState(BLUETOOTH_SEARCH);
        }

        @Override
        public void onAfterConnect(BluetoothSocket bluetoothSocket) {
            device.init(visible);
            device.registerFilters();

            // set title
            debug("MainActivity: onAfterConnect > set title");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setTitle(TAG + " - connected to <" + bluetoothDeviceName + "@" + bluetoothDeviceAddress
                            + ">");
                    setBluetoothState(BLUETOOTH_CONNECTED);
                }
            });
        }

        @Override
        public void onBeforeDisconnect(BluetoothSocket bluetoothSocket) {
        }

        @Override
        public void onAfterDisconnect() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setTitle(TAG + " - disconnected");
                }
            });
        }
    });
    // detect hardware status
    int BT_STATE = BluetoothManager.getInstance().getHardwareState();
    if (BT_STATE == BluetoothManager.STATE_BLUETOOTH_NOT_AVAILABLE)
        toast("Sorry, but your device doesn't seem to have Bluetooth support!");
    else if (BT_STATE == BluetoothManager.STATE_BLUETOOTH_NOT_ACTIVE) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, 1);
    }

    // load settings
    // - includes the reader
    // - includes the decoder
    //loadSettings(); --> done in onResume

    // load fields from static code
    debug("Loaded fields: " + fields.size());

    // load fields
    //final SharedPreferences settings = getSharedPreferences(PREFERENCES_FILE, 0);
    (new Thread(new Runnable() {
        @Override
        public void run() {
            debug("Loading fields last field values from database");
            for (int i = 0; i < fields.size(); i++) {
                Field field = fields.get(i);
                field.setCalculatedValue(CanzeDataSource.getInstance().getLast(field.getSID()));
                //debug("MainActivity: Setting "+field.getSID()+" = "+field.getValue());
                //f.setValue(settings.getFloat(f.getUniqueID(), 0));
            }
            debug("Loading fields last field values from database (done)");
        }
    })).start();
}