Example usage for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECT_REQUESTED

List of usage examples for android.bluetooth BluetoothDevice ACTION_ACL_DISCONNECT_REQUESTED

Introduction

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

Prototype

String ACTION_ACL_DISCONNECT_REQUESTED

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

Click Source Link

Document

Broadcast Action: Indicates that a low level (ACL) disconnection has been requested for a remote device, and it will soon be disconnected.

Usage

From source file:org.thecongers.mtpms.MainActivity.java

@SuppressLint("HandlerLeak")
@Override/*from  ww  w.j  ava 2s.  c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);

    layoutFront = (LinearLayout) findViewById(R.id.layoutFront);
    layoutRear = (LinearLayout) findViewById(R.id.layoutRear);
    txtFrontPressure = (TextView) findViewById(R.id.txtFrontPressure);
    txtFrontTemperature = (TextView) findViewById(R.id.txtFrontTemperature);
    txtFrontVoltage = (TextView) findViewById(R.id.txtFrontVoltage);
    txtRearPressure = (TextView) findViewById(R.id.txtRearPressure);
    txtRearTemperature = (TextView) findViewById(R.id.txtRearTemperature);
    txtRearVoltage = (TextView) findViewById(R.id.txtRearVoltage);
    txtOutput = (TextView) findViewById(R.id.txtOutput);
    View myView = findViewById(R.id.appLayout);
    root = myView.getRootView();

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Keep screen on
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    sensorDB = new SensorIdDatabase(this);

    // Backgrounds
    background = this.getResources().getDrawable(R.drawable.rectangle_bordered);
    redBackground = this.getResources().getDrawable(R.drawable.rectangle_bordered_red);
    backgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_dark);
    redBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_red_dark);
    txtOutBackground = this.getResources().getDrawable(R.drawable.rectangle);
    txtOutBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_dark);

    // Update textViews with select units
    String pressureFormat = sharedPrefs.getString("prefpressuref", "0");
    String pressureUnit = "psi";
    if (pressureFormat.contains("1")) {
        // KPa
        pressureUnit = "KPa";
    } else if (pressureFormat.contains("2")) {
        // Kg-f
        pressureUnit = "Kg-f";
    } else if (pressureFormat.contains("3")) {
        // Bar
        pressureUnit = "Bar";
    }
    String temperatureUnit = "C";
    if (sharedPrefs.getString("preftempf", "0").contains("0")) {
        // F
        temperatureUnit = "F";
    }

    txtFrontPressure.setText("--- " + pressureUnit);
    txtFrontTemperature.setText("--- " + temperatureUnit);
    txtFrontVoltage.setText("--- V");
    txtRearPressure.setText("--- " + pressureUnit);
    txtRearTemperature.setText("--- " + temperatureUnit);
    txtRearVoltage.setText("--- V");

    // Set initial color scheme
    if (!sharedPrefs.getBoolean("prefNightMode", false)) {
        root.setBackgroundColor(getResources().getColor(android.R.color.white));
        layoutFront.setBackground(background);
        layoutRear.setBackground(background);
        txtFrontPressure.setTextColor(getResources().getColor(android.R.color.black));
        txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.black));
        txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.black));
        txtRearPressure.setTextColor(getResources().getColor(android.R.color.black));
        txtRearTemperature.setTextColor(getResources().getColor(android.R.color.black));
        txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black));
        txtOutput.setBackground(txtOutBackground);
        txtOutput.setTextColor(getResources().getColor(android.R.color.black));
    } else {
        root.setBackgroundColor(getResources().getColor(android.R.color.black));
        layoutFront.setBackground(backgroundDark);
        layoutRear.setBackground(backgroundDark);
        txtFrontPressure.setTextColor(getResources().getColor(android.R.color.white));
        txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.white));
        txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.white));
        txtRearPressure.setTextColor(getResources().getColor(android.R.color.white));
        txtRearTemperature.setTextColor(getResources().getColor(android.R.color.white));
        txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white));
        txtOutput.setBackground(txtOutBackgroundDark);
        txtOutput.setTextColor(getResources().getColor(android.R.color.white));
    }

    // Check if there are sensor to wheel mappings
    if (sharedPrefs.getString("prefFrontID", "").equals("")
            && sharedPrefs.getString("prefRearID", "").equals("")) {
        new AlertDialog.Builder(this).setTitle(R.string.alert_setup_title)
                .setMessage(R.string.alert_setup_message).setNeutralButton(R.string.alert_setup_button, null)
                .show();
    }

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "Serial Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Check if sensor ID is new
                        boolean checkID = sensorDB.sensorIdExists(sensorID.toString());
                        if (!checkID) {
                            // Add sensor ID to db
                            sensorDB.addID(sensorID.toString());
                            Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_newSensor)
                                    + " " + sensorID.toString(), Toast.LENGTH_LONG).show();
                        }
                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        if (!prefFrontID.equals("") || !prefRearID.equals("")) {
                            try {
                                // Get temperature
                                int tempC = Integer.parseInt(hexData[8], 16) - 50;
                                double temp = tempC;
                                String temperatureUnit = "C";
                                // Get tire pressure
                                int psi = Integer.parseInt(hexData[9], 16);
                                double pressure = psi;
                                String pressureUnit = "psi";
                                // Get battery voltage
                                double voltage = Integer.parseInt(hexData[10], 16) / 50;
                                // Get pressure thresholds
                                int fLowPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefFrontLowPressure", "30"));
                                int fHighPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefFrontHighPressure", "46"));
                                int rLowPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefRearLowPressure", "30"));
                                int rHighPressure = Integer
                                        .parseInt(sharedPrefs.getString("prefRearHighPressure", "46"));
                                if (sharedPrefs.getString("preftempf", "0").contains("0")) {
                                    // F
                                    temp = (9.0 / 5.0) * tempC + 32.0;
                                    temperatureUnit = "F";
                                }
                                int formattedTemperature = (int) (temp + 0.5d);
                                String pressureFormat = sharedPrefs.getString("prefpressuref", "0");
                                if (pressureFormat.contains("1")) {
                                    // KPa
                                    pressure = psi * 6.894757293168361;
                                    pressureUnit = "KPa";
                                } else if (pressureFormat.contains("2")) {
                                    // Kg-f
                                    pressure = psi * 0.070306957965539;
                                    pressureUnit = "Kg-f";
                                } else if (pressureFormat.contains("3")) {
                                    // Bar
                                    pressure = psi * 0.0689475729;
                                    pressureUnit = "Bar";
                                }
                                int formattedPressure = (int) (pressure + 0.5d);
                                // Get checksum
                                String checksum = hexData[11];
                                Log.d(TAG,
                                        "Sensor ID: " + sensorID.toString() + ", Sensor Position: " + position
                                                + ", Temperature(" + temperatureUnit + "): "
                                                + String.valueOf(temp) + ", Pressure(" + pressureUnit + "): "
                                                + String.valueOf(pressure) + ", Voltage: "
                                                + String.valueOf(voltage) + ", Checksum: " + checksum
                                                + ", Data: " + sbhex.toString() + ", Bytes:" + msg.arg1);

                                if (sensorID.toString().equals(prefFrontID)) {
                                    Log.d(TAG, "Front ID matched");
                                    // Check for data logging enabled
                                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                                        // Log data
                                        if (logger == null) {
                                            logger = new LogData();
                                        }
                                        logger.write("front", String.valueOf(psi), String.valueOf(tempC),
                                                String.valueOf(voltage));
                                    }

                                    // Set front tire status
                                    if (psi <= fLowPressure) {
                                        frontStatus = 1;
                                    } else if (psi >= fHighPressure) {
                                        frontStatus = 2;
                                    } else {
                                        frontStatus = 0;
                                    }

                                    txtFrontPressure
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    txtFrontTemperature.setText(
                                            String.valueOf(formattedTemperature) + " " + temperatureUnit);
                                    txtFrontVoltage.setText(String.format("%.2f", voltage) + " V");
                                } else if (sensorID.toString().equals(prefRearID)) {
                                    Log.d(TAG, "Rear ID matched");
                                    // Check for data logging enabled
                                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                                        // Log data
                                        if (logger == null) {
                                            logger = new LogData();
                                        }
                                        logger.write("rear", String.valueOf(psi), String.valueOf(tempC),
                                                String.valueOf(voltage));
                                    }

                                    // Set rear tire status
                                    if (psi <= rLowPressure) {
                                        rearStatus = 1;
                                    } else if (psi >= rHighPressure) {
                                        rearStatus = 2;
                                    } else {
                                        rearStatus = 0;
                                    }
                                    txtRearPressure
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    txtRearTemperature.setText(
                                            String.valueOf(formattedTemperature) + " " + temperatureUnit);
                                    txtRearVoltage.setText(String.format("%.2f", voltage) + " V");
                                }
                                // Update txtOutput box and send notification
                                if ((frontStatus == 0) && (rearStatus == 0)) {
                                    txtOutput.setText("");
                                    if (notificationManager != null) {
                                        notificationManager.cancel(0);
                                    }
                                } else if ((frontStatus == 1) && (rearStatus == 0)) {
                                    txtOutput
                                            .setText(getResources().getString(R.string.alert_lowFrontPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 0)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontPressure));
                                } else if ((rearStatus == 1) && (frontStatus == 0)) {
                                    txtOutput.setText(getResources().getString(R.string.alert_lowRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowRearPressure));
                                } else if ((rearStatus == 2) && (frontStatus == 0)) {
                                    txtOutput
                                            .setText(getResources().getString(R.string.alert_highRearPressure));
                                    Notify(getResources().getString(R.string.alert_highRearPressure));
                                } else if ((frontStatus == 1) && (rearStatus == 1)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_lowFrontLowRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontLowRearPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 2)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontHighRearPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontHighRearPressure));
                                } else if ((frontStatus == 1) && (rearStatus == 2)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_lowFrontHighRearPressure));
                                    Notify(getResources().getString(R.string.alert_lowFrontHighRearPressure));
                                } else if ((frontStatus == 2) && (rearStatus == 1)) {
                                    txtOutput.setText(
                                            getResources().getString(R.string.alert_highFrontLowRearPressure));
                                    Notify(getResources().getString(R.string.alert_highFrontLowRearPressure));
                                }
                                // Update color scheme
                                if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                    if (frontStatus == 0) {
                                        layoutFront.setBackground(background);
                                    } else {
                                        layoutFront.setBackground(redBackground);
                                    }
                                    if (rearStatus == 0) {
                                        layoutRear.setBackground(background);
                                    } else {
                                        layoutRear.setBackground(redBackground);
                                    }
                                    root.setBackgroundColor(getResources().getColor(android.R.color.white));
                                    txtOutput.setBackground(txtOutBackground);
                                    txtOutput.setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontPressure
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontTemperature
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtFrontVoltage
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearPressure
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearTemperature
                                            .setTextColor(getResources().getColor(android.R.color.black));
                                    txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black));
                                } else {
                                    if (frontStatus == 0) {
                                        layoutFront.setBackground(backgroundDark);
                                    } else {
                                        layoutFront.setBackground(redBackgroundDark);
                                    }
                                    if (rearStatus == 0) {
                                        layoutRear.setBackground(backgroundDark);
                                    } else {
                                        layoutRear.setBackground(redBackgroundDark);
                                    }
                                    root.setBackgroundColor(getResources().getColor(android.R.color.black));
                                    txtOutput.setBackground(txtOutBackgroundDark);
                                    txtOutput.setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontPressure
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontTemperature
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtFrontVoltage
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearPressure
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearTemperature
                                            .setTextColor(getResources().getColor(android.R.color.white));
                                    txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white));
                                }
                            } catch (NumberFormatException e) {
                                Log.d(TAG, "Malformed message, unexpected value");
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };
    // Light Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        float max = lightSensor.getMaximumRange();
        sensorManager.registerListener(lightSensorEventListener, lightSensor,
                SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
        Log.d(TAG, "Light Sensor Max Value: " + max);
    }
    // Try to connect to iTPMSystem
    btConnect();
}

From source file: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);//  w w w. j  av  a 2s  .c  o m

    View myView = findViewById(R.id.layoutApp);
    root = myView.getRootView();
    layoutIcons = (LinearLayout) findViewById(R.id.layoutIcons);
    layoutMiddleLeft = (LinearLayout) findViewById(R.id.layoutMiddleLeft);
    layoutMiddleRight = (LinearLayout) findViewById(R.id.layoutMiddleRight);
    layoutBottomLeft = (LinearLayout) findViewById(R.id.layoutBottomLeft);
    layoutBottomRight = (LinearLayout) findViewById(R.id.layoutBottomRight);
    imageKillSwitch = (ImageView) findViewById(R.id.imageViewKillSwitch);
    imageLeftArrow = (ImageView) findViewById(R.id.imageViewLeftArrow);
    imageRightArrow = (ImageView) findViewById(R.id.imageViewRightArrow);
    imageHighBeam = (ImageView) findViewById(R.id.imageViewHighBeam);
    imageHeatedGrips = (ImageView) findViewById(R.id.imageViewHeatedGrips);
    imageABS = (ImageView) findViewById(R.id.imageViewABS);
    imageLampf = (ImageView) findViewById(R.id.imageViewLampf);
    imageFuelWarning = (ImageView) findViewById(R.id.imageViewFuelWarning);
    imageFuelLevel = (ImageView) findViewById(R.id.imageViewFuelLevel);
    imageESA = (ImageView) findViewById(R.id.imageViewESA);
    txtSpeed = (TextView) findViewById(R.id.textViewSpeed);
    txtSpeedUnit = (TextView) findViewById(R.id.textViewSpeedUnit);
    txtGear = (TextView) findViewById(R.id.textViewGear);
    txtOdometers = (TextView) findViewById(R.id.textViewOdometer);
    txtESA = (TextView) findViewById(R.id.textViewESA);
    imageButtonTPMS = (ImageButton) findViewById(R.id.imageButtonTPMS);
    imageButtonBluetooth = (ImageButton) findViewById(R.id.imageButtonBluetooth);
    imageButtonPreference = (ImageButton) findViewById(R.id.imageButtonPreference);
    progressFuelLevel = (ProgressBar) findViewById(R.id.progressBarFuelLevel);

    // Backgrounds
    background = R.drawable.rectangle_bordered;
    backgroundDark = R.drawable.rectangle_bordered_dark;

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update layout
    updateLayout();

    if (!sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        imageButtonTPMS.setImageResource(R.mipmap.blank_icon);
        imageButtonTPMS.setEnabled(false);
    } else {
        imageButtonTPMS.setImageResource(R.mipmap.tpms_off);
        imageButtonTPMS.setEnabled(true);
    }

    // Set initial color scheme
    updateColors();
    if (sharedPrefs.getBoolean("prefNightMode", false)) {
        imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
    }

    // Watch for Bluetooth Changes
    IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    this.registerReceiver(btReceiver, filter1);
    this.registerReceiver(btReceiver, filter2);
    this.registerReceiver(btReceiver, filter3);

    // Setup Text To Speech
    text2speech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if (status != TextToSpeech.ERROR) {
                text2speech.setLanguage(Locale.US);
            }
        }
    });

    imageButtonBluetooth.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            canBusConnect();
        }
    });

    imageButtonTPMS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
                iTPMSConnect();
            }
        }
    });

    imageButtonPreference.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu popup = new PopupMenu(MainActivity.this, v);
            popup.getMenuInflater().inflate(R.menu.main, popup.getMenu());
            popup.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_settings:
                        // Settings Menu was selected
                        Intent i = new Intent(getApplicationContext(),
                                org.thecongers.mcluster.UserSettingActivity.class);
                        startActivityForResult(i, SETTINGS_RESULT);
                        return true;
                    case R.id.action_about:
                        // About was selected
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        builder.setTitle(getResources().getString(R.string.alert_about_title));
                        builder.setMessage(readRawTextFile(MainActivity.this, R.raw.about));
                        builder.setPositiveButton(getResources().getString(R.string.alert_about_button), null);
                        builder.show();
                        return true;
                    case R.id.action_exit:
                        // Exit menu item was selected
                        if (logger != null) {
                            logger.shutdown();
                        }
                        finish();
                        System.exit(0);
                    default:
                        return true;
                    }
                }
            });

            popup.show();
        }
    });

    layoutMiddleRight.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int infoViewCurr = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
            if (infoViewCurr < (numInfoViewLayouts - 1)) {
                infoViewCurr = infoViewCurr + 1;
            } else {
                infoViewCurr = 0;
            }
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString("prefInfoView", String.valueOf(infoViewCurr));
            editor.commit();

            //update layout
            updateLayout();
        }
    });

    canBusMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Check to see if message is the correct size
                if (msg.arg1 == 27) {
                    byte[] readBuf = (byte[]) msg.obj;
                    String message = new String(readBuf);

                    //Default Units
                    String speedUnit = "km/h";
                    String odometerUnit = "km";
                    String temperatureUnit = "C";

                    String[] splitMessage = message.split(",");
                    if (splitMessage[0].contains("10C")) {

                        //RPM
                        if (sharedPrefs.getString("prefInfoView", "0").contains("0")) {
                            int rpm = (Integer.parseInt(splitMessage[4], 16) * 255
                                    + Integer.parseInt(splitMessage[3], 16)) / 4;
                            txtInfo = (TextView) findViewById(R.id.textViewInfo);
                            txtInfo.setGravity(Gravity.CENTER | Gravity.BOTTOM);
                            txtInfo.setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
                            txtInfo.setText(Integer.toString(rpm) + " RPM");
                            if (rpm > 8500) {
                                txtInfo.setTextColor(getResources().getColor(R.color.red));
                            } else {
                                txtInfo.setTextColor(getResources().getColor(android.R.color.black));
                            }
                        }

                        //Kill Switch
                        String killSwitchValue = splitMessage[5].substring(1);
                        if (killSwitchValue.contains("5") || killSwitchValue.contains("9")) {
                            //Kill Switch On
                            imageKillSwitch.setImageResource(R.mipmap.kill_switch);
                        } else {
                            //Kill Switch Off
                            imageKillSwitch.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("130")) {
                        //Turn indicators
                        String indicatorValue = splitMessage[8];

                        if (indicatorValue.contains("D7")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        } else if (indicatorValue.contains("E7")) {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else if (indicatorValue.contains("EF")) {
                            imageLeftArrow.setImageResource(R.mipmap.left_arrow);
                            imageRightArrow.setImageResource(R.mipmap.right_arrow);
                        } else {
                            imageLeftArrow.setImageResource(R.mipmap.blank_icon);
                            imageRightArrow.setImageResource(R.mipmap.blank_icon);
                        }

                        //High Beam
                        String highBeamValue = splitMessage[7].substring(1);
                        if (highBeamValue.contains("9")) {
                            //High Beam On
                            imageHighBeam.setImageResource(R.mipmap.high_beam);
                        } else {
                            //High Beam Off
                            imageHighBeam.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("294")) {
                        //Front Wheel Speed
                        double frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                + Integer.parseInt(splitMessage[3], 16)) * 0.063);
                        //If 21" Wheel
                        if (sharedPrefs.getString("prefDistance", "0").contains("1")) {
                            frontSpeed = ((Integer.parseInt(splitMessage[4], 16) * 256.0
                                    + Integer.parseInt(splitMessage[3], 16)) * 0.064);
                        }
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            speedUnit = "MPH";
                            frontSpeed = frontSpeed / 1.609344;
                        }
                        txtSpeed.setText(String.valueOf((int) Math.round(frontSpeed)));
                        txtSpeedUnit.setText(speedUnit);

                        //ABS
                        String absValue = splitMessage[2].substring(0, 1);
                        if (absValue.contains("B")) {
                            //ABS Off
                            imageABS.setImageResource(R.mipmap.abs);
                        } else {
                            //ABS On
                            imageABS.setImageResource(R.mipmap.blank_icon);
                        }

                    } else if (splitMessage[0].contains("2BC")) {
                        //Engine Temperature
                        engineTempC = (Integer.parseInt(splitMessage[3], 16) * 0.75) - 24.0;

                        if (engineTempC >= 115.5) {
                            if (engineTempAlertTriggered == false) {
                                engineTempAlertTriggered = true;
                                speakString(getResources().getString(R.string.engine_temp_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            engineTempAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double engineTemp = engineTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                engineTemp = (int) Math.round((9.0 / 5.0) * engineTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtEngineTemp.setText(String.valueOf(engineTemp) + temperatureUnit);
                        }

                        // Gear
                        String gearValue = splitMessage[6].substring(0, 1);
                        String gear;
                        if (gearValue.contains("1")) {
                            gear = "1";
                        } else if (gearValue.contains("2")) {
                            gear = "N";
                        } else if (gearValue.contains("4")) {
                            gear = "2";
                        } else if (gearValue.contains("7")) {
                            gear = "3";
                        } else if (gearValue.contains("8")) {
                            gear = "4";
                        } else if (gearValue.contains("B")) {
                            gear = "5";
                        } else if (gearValue.contains("D")) {
                            gear = "6";
                        } else {
                            gear = "-";
                        }
                        txtGear.setText(gear);

                        //Air Temperature
                        airTempC = (Integer.parseInt(splitMessage[8], 16) * 0.75) - 48.0;
                        //Freeze Warning
                        if (airTempC <= 0.0) {
                            if (freezeAlertTriggered == false) {
                                freezeAlertTriggered = true;
                                speakString(getResources().getString(R.string.freeze_alert));
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(3));
                                editor.commit();

                                updateLayout();
                            }
                        } else {
                            freezeAlertTriggered = false;
                        }

                        if (sharedPrefs.getString("prefInfoView", "0").contains("3")) {
                            double airTemp = airTempC;
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                airTemp = (int) Math.round((9.0 / 5.0) * airTemp + 32.0);
                                temperatureUnit = "F";
                            }
                            txtAirTemp.setText(String.valueOf(airTemp) + temperatureUnit);
                        }

                    } else if (splitMessage[0].contains("2D0")) {
                        //Info Button
                        String infoButtonValue = splitMessage[6].substring(1);
                        if (infoButtonValue.contains("5")) {
                            //Short Press
                            if (!btnPressed) {
                                int infoButton = Integer.valueOf(sharedPrefs.getString("prefInfoView", "0"));
                                if (infoButton < (numInfoViewLayouts - 1)) {
                                    infoButton = infoButton + 1;
                                } else {
                                    infoButton = 0;
                                }
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(infoButton));
                                editor.commit();

                                //update layout
                                updateLayout();
                                btnPressed = true;
                            }
                        } else if (infoButtonValue.contains("6")) {
                            //Long Press
                        } else {
                            btnPressed = false;
                        }

                        //Heated Grips
                        String heatedGripSwitchValue = splitMessage[8].substring(0, 1);
                        if (heatedGripSwitchValue.contains("C")) {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        } else if (heatedGripSwitchValue.contains("D")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_low_dark);
                            }
                        } else if (heatedGripSwitchValue.contains("E")) {
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high);
                            } else {
                                imageHeatedGrips.setImageResource(R.mipmap.heated_grips_high_dark);
                            }
                        } else {
                            imageHeatedGrips.setImageResource(R.mipmap.blank_icon);
                        }

                        //ESA Damping and Preload
                        String esaDampingValue1 = splitMessage[5].substring(1);
                        String esaDampingValue2 = splitMessage[8].substring(1);
                        String esaPreLoadValue = splitMessage[5].substring(0, 1);
                        if (esaDampingValue1.contains("B") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("B") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("1")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("3")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.smooth_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.smooth_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("4")) {
                            txtESA.setText("SOFT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaDampingValue1.contains("7") && esaDampingValue2.contains("6")) {
                            txtESA.setText("HARD");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.uneven_terrain);
                            } else {
                                imageESA.setImageResource(R.mipmap.uneven_terrain_dark);
                            }
                        } else if (esaPreLoadValue.contains("1")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("2")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("3")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("4")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("5")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("6")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_luggage);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_luggage_dark);
                            }
                        } else if (esaPreLoadValue.contains("7")) {
                            txtESA.setText("COMF");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("8")) {
                            txtESA.setText("NORM");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else if (esaPreLoadValue.contains("9")) {
                            txtESA.setText("SPORT");
                            if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) {
                                imageESA.setImageResource(R.mipmap.helmet_helmet);
                            } else {
                                imageESA.setImageResource(R.mipmap.helmet_helmet_dark);
                            }
                        } else {
                            txtESA.setText("");
                            imageESA.setImageResource(R.mipmap.blank_icon);
                        }

                        //Lamp Fault
                        //TODO: Display/speak Bulb location
                        String lampFaultValue = splitMessage[3].substring(0, 1);
                        if (lampFaultValue.contains("0")) {
                            //None
                            imageLampf.setImageResource(R.mipmap.blank_icon);
                        } else if (lampFaultValue.contains("1")) {
                            //Low Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("4")) {
                            //High Beam
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else if (lampFaultValue.contains("8")) {
                            //Signal Bulb
                            imageLampf.setImageResource(R.mipmap.lampf);
                        } else {
                            //Unknown
                            imageLampf.setImageResource(R.mipmap.lampf);
                        }

                        //Fuel Level
                        double fuelLevelPercent = ((Integer.parseInt(splitMessage[4], 16) - 73) / 182.0)
                                * 100.0;
                        progressFuelLevel.setProgress((int) Math.round(fuelLevelPercent));

                        //Fuel Level Warning
                        double fuelWarning = sharedPrefs.getInt("prefFuelWarning", 30);
                        if (fuelLevelPercent >= fuelWarning) {
                            imageFuelWarning.setImageResource(R.mipmap.blank_icon);
                            fuelAlertTriggered = false;
                            fuelReserveAlertTriggered = false;
                        } else if (fuelLevelPercent == 0) {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelReserveAlertTriggered) {
                                fuelReserveAlertTriggered = true;
                                //Audio Warning
                                speakString(getResources().getString(R.string.fuel_alert_reserve));
                            }
                        } else {
                            //Visual Warning
                            imageFuelWarning.setImageResource(R.mipmap.fuel_warning);
                            if (!fuelAlertTriggered) {
                                fuelAlertTriggered = true;
                                //Audio Warning
                                String fuelAlert = getResources().getString(R.string.fuel_alert_begin)
                                        + String.valueOf((int) Math.round(fuelLevelPercent))
                                        + getResources().getString(R.string.fuel_alert_end);
                                speakString(fuelAlert);
                                //Suggest nearby fuel stations
                                if (!sharedPrefs.getString("prefFuelStation", "0").contains("0")) {
                                    // Display prompt to open google maps
                                    MainActivity.this.runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            AlertDialog.Builder builder = new AlertDialog.Builder(
                                                    MainActivity.this);
                                            builder.setTitle(getResources()
                                                    .getString(R.string.alert_fuel_stations_title));
                                            if (sharedPrefs.getString("prefFuelStation", "0").contains("1")) {
                                                // Search for fuel stations nearby
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_suggestions));
                                            } else if (sharedPrefs.getString("prefFuelStation", "0")
                                                    .contains("2")) {
                                                // Route to nearest fuel station
                                                builder.setMessage(getResources().getString(
                                                        R.string.alert_fuel_stations_message_navigation));
                                            }
                                            builder.setPositiveButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_positive),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Uri gmmIntentUri = null;
                                                            if (sharedPrefs.getString("prefFuelStation", "0")
                                                                    .contains("1")) {
                                                                // Search for fuel stations nearby
                                                                gmmIntentUri = Uri
                                                                        .parse("geo:0,0?q=gas+station");
                                                            } else if (sharedPrefs
                                                                    .getString("prefFuelStation", "0")
                                                                    .contains("2")) {
                                                                // Route to nearest fuel station
                                                                gmmIntentUri = Uri.parse(
                                                                        "google.navigation:q=gas+station");
                                                            }
                                                            Intent mapIntent = new Intent(Intent.ACTION_VIEW,
                                                                    gmmIntentUri);
                                                            mapIntent
                                                                    .setPackage("com.google.android.apps.maps");
                                                            startActivity(mapIntent);
                                                        }
                                                    });
                                            builder.setNegativeButton(
                                                    getResources().getString(
                                                            R.string.alert_fuel_stations_button_negative),
                                                    new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog, int id) {
                                                            dialog.cancel();
                                                        }
                                                    });
                                            builder.show();
                                        }
                                    });
                                }
                            }
                        }
                    } else if (splitMessage[0].contains("3F8")) {
                        String odometerValue = "";
                        for (int i = 4; i > 1; i--) {
                            odometerValue = odometerValue + splitMessage[i];
                        }
                        double odometer = Integer.parseInt(odometerValue, 16);
                        if (sharedPrefs.getString("prefDistance", "0").contains("0")) {
                            odometerUnit = "Miles";
                            odometer = odometer * 0.6214;
                        }
                        txtOdometers.setText(String.valueOf((int) Math.round(odometer)) + " " + odometerUnit);
                    }
                    imageButtonBluetooth.setImageResource(R.mipmap.bluetooth_on);
                    if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                        // Log data
                        if (logger == null) {
                            logger = new LogData();
                        }
                        if (logger != null) {
                            logger.write(message);
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    sensorMessages = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case RECEIVE_MESSAGE:
                // Message received
                Log.d(TAG, "iTPMS Message Received, Length: " + msg.arg1);
                // Check to see if message is the correct size
                if (msg.arg1 == 13) {
                    byte[] readBuf = (byte[]) msg.obj;

                    // Validate against checksum
                    int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8]
                            + readBuf[9] + readBuf[10];
                    if (calculatedCheckSum == readBuf[11]) {
                        // Convert to hex
                        String[] hexData = new String[13];
                        StringBuilder sbhex = new StringBuilder();
                        for (int i = 0; i < msg.arg1; i++) {
                            hexData[i] = String.format("%02X", readBuf[i]);
                            sbhex.append(hexData[i]);
                        }

                        // Get sensor position
                        String position = hexData[3];
                        // Get sensor ID
                        StringBuilder sensorID = new StringBuilder();
                        sensorID.append(hexData[4]);
                        sensorID.append(hexData[5]);
                        sensorID.append(hexData[6]);
                        sensorID.append(hexData[7]);

                        // Only parse message if there is one or more sensor mappings
                        String prefFrontID = sharedPrefs.getString("prefFrontID", "");
                        String prefRearID = sharedPrefs.getString("prefRearID", "");
                        try {
                            // Get temperature
                            int tempC = Integer.parseInt(hexData[8], 16) - 50;
                            double temp = tempC;
                            String temperatureUnit = "C";
                            // Get tire pressure
                            int psi = Integer.parseInt(hexData[9], 16);
                            double pressure = psi;
                            String pressureUnit = "psi";
                            // Get battery voltage
                            double voltage = Integer.parseInt(hexData[10], 16) / 50;
                            // Get pressure thresholds
                            int lowPressure = Integer.parseInt(sharedPrefs.getString("prefLowPressure", "30"));
                            int highPressure = Integer
                                    .parseInt(sharedPrefs.getString("prefHighPressure", "46"));
                            if (sharedPrefs.getString("prefTempF", "0").contains("1")) {
                                // F
                                temp = (9.0 / 5.0) * tempC + 32.0;
                                temperatureUnit = "F";
                            }
                            int formattedTemperature = (int) (temp + 0.5d);
                            String pressureFormat = sharedPrefs.getString("prefPressureF", "0");
                            if (pressureFormat.contains("1")) {
                                // KPa
                                pressure = psi * 6.894757293168361;
                                pressureUnit = "KPa";
                            } else if (pressureFormat.contains("2")) {
                                // Kg-f
                                pressure = psi * 0.070306957965539;
                                pressureUnit = "Kg-f";
                            } else if (pressureFormat.contains("3")) {
                                // Bar
                                pressure = psi * 0.0689475729;
                                pressureUnit = "Bar";
                            }
                            int formattedPressure = (int) (pressure + 0.5d);
                            // Get checksum
                            String checksum = hexData[11];

                            if (Integer.parseInt(hexData[3], 16) <= 2) {
                                Log.d(TAG, "Front ID matched: " + Integer.parseInt(hexData[3], 16));

                                frontPressurePSI = psi;
                                // Set front tire status
                                if (psi <= lowPressure) {
                                    frontStatus = 1;
                                } else if (psi >= highPressure) {
                                    frontStatus = 2;
                                } else {
                                    frontStatus = 0;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtFrontTPMS = (TextView) findViewById(R.id.textViewFrontTPMS);
                                    txtFrontTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtFrontTPMS
                                            .setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (frontStatus != 0) {
                                        txtFrontTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtFrontTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            } else if (Integer.parseInt(hexData[3], 16) > 2) {
                                Log.d(TAG, "Rear ID matched: " + Integer.parseInt(hexData[3], 16));

                                rearPressurePSI = psi;
                                // Set rear tire status
                                if (psi <= lowPressure) {
                                    rearStatus = 4;
                                } else if (psi >= highPressure) {
                                    rearStatus = 5;
                                } else {
                                    rearStatus = 3;
                                }
                                if (sharedPrefs.getString("prefInfoView", "0").contains("2")) {
                                    txtRearTPMS = (TextView) findViewById(R.id.textViewRearTPMS);
                                    txtRearTPMS.setTextSize(TypedValue.COMPLEX_UNIT_SP, 50);
                                    txtRearTPMS.setText(String.valueOf(formattedPressure) + " " + pressureUnit);
                                    if (rearStatus != 3) {
                                        txtRearTPMS.setTextColor(getResources().getColor(R.color.red));
                                    } else {
                                        txtRearTPMS
                                                .setTextColor(getResources().getColor(android.R.color.black));
                                    }
                                }
                            }
                            // Reset icon
                            if ((frontStatus == 0) && (rearStatus == 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_on);
                            }
                            if ((frontStatus != 0) || (rearStatus != 3)) {
                                imageButtonTPMS.setImageResource(R.mipmap.tpms_alert);
                                SharedPreferences.Editor editor = sharedPrefs.edit();
                                editor.putString("prefInfoView", String.valueOf(2));
                                editor.commit();

                                updateLayout();

                                int delay = (Integer
                                        .parseInt(sharedPrefs.getString("prefAudioAlertDelay", "30")) * 1000);
                                String currStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                if (alertTimer == 0) {
                                    alertTimer = System.currentTimeMillis();
                                } else {
                                    long currentTime = System.currentTimeMillis();
                                    long duration = (currentTime - alertTimer);
                                    if (!currStatus.equals(lastStatus) || duration >= delay) {
                                        alertTimer = 0;
                                        if ((frontStatus == 1) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowFrontPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 3)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highFrontPressure));
                                        } else if ((rearStatus == 4) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_lowRearPressure));
                                        } else if ((rearStatus == 5) && (frontStatus == 0)) {
                                            speakString(
                                                    getResources().getString(R.string.alert_highRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontLowRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontHighRearPressure));
                                        } else if ((frontStatus == 1) && (rearStatus == 5)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_lowFrontHighRearPressure));
                                        } else if ((frontStatus == 2) && (rearStatus == 4)) {
                                            speakString(getResources()
                                                    .getString(R.string.alert_highFrontLowRearPressure));
                                        }
                                        lastStatus = (String.valueOf(frontStatus) + String.valueOf(rearStatus));
                                    }
                                }
                            }
                        } catch (NumberFormatException e) {
                            Log.d(TAG, "Malformed message, unexpected value");
                        }
                        if (sharedPrefs.getBoolean("prefDataLogging", false)) {
                            // Log data
                            if (logger == null) {
                                logger = new LogData();
                            }
                            if (logger != null) {
                                logger.write(String.valueOf(sbhex));
                            }
                        }
                    }
                } else {
                    Log.d(TAG, "Malformed message, message length: " + msg.arg1);
                }
                break;
            }
        }
    };

    // Sensor Stuff
    SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    Sensor magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

    // Light
    if (lightSensor == null) {
        Log.d(TAG, "Light sensor not found");
    } else {
        sensorManager.registerListener(sensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
        hasSensor = true;
    }
    // Compass
    sensorManager.registerListener(sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI);
    sensorManager.registerListener(sensorEventListener, magnetometer, SensorManager.SENSOR_DELAY_UI);

    // Try to connect to CANBusGateway
    canBusConnect();
    // Connect to iTPMS if enabled
    if (sharedPrefs.getBoolean("prefEnableTPMS", false)) {
        iTPMSConnect();
    }
}

From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    Bundle intentExtras = intent.getExtras();

    if (owner == null)
        return;//w  w w .j  a  va 2 s  . c  o m
    owner.getWebSocketManager().sendIntentToWebSocket(action, intentExtras);

    //capture the "battery changed" event
    if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
        DeviceInfoOld.battery = level * 100 / scale;
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean bCharging = plugged == BatteryManager.BATTERY_PLUGGED_AC
                || plugged == BatteryManager.BATTERY_PLUGGED_USB;
        owner.setBatteryCharging(bCharging);
        dataMonitorStats.setBattery(bCharging, DeviceInfoOld.battery);
    } else if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
        owner.setBatteryCharging(true);
        dataMonitorStats.setBattery(true, null);
    } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
        owner.setBatteryCharging(false);
        dataMonitorStats.setBattery(false, null);
    } else if (action.equals(Intent.ACTION_VIEW)) {
        //this is supposed to trigger the update event
        //owner.triggerUpdateEvent(false, false);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_UI)) {
        String packagename = intent.getStringExtra("packagename");
        String mypackagename = context.getPackageName();
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(PreferenceKeys.Miscellaneous.YEILDED_SERVICE, packagename).commit();
        // If the UI started on a different MMC app UI, then we stop this service until this UI is launched
        if (!packagename.equals(mypackagename)) // This will exit the service when safe, and won't restart it because it will be yeilded
            owner.restartSelf();
    } else if (action.equals(UPDATE_ACTION)) {
        owner.getEventManager().triggerUpdateEvent(false, false);
    } else if (action.equals(COLDRESET_ACTION)) {
        //this is supposed to trigger the update event
        owner.getGpsManager().coldStart("triggered by user");
    } else if (action.equals(EMAIL_CSV)) {
        //this is supposed to trigger the update event
        owner.requestCsvEmail();
    } else if (action.equals(SPEED_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.MAN_SPEEDTEST, trigger);
    } else if (action.equals(RUN_WEBSOCKET)) {
        //this is supposed to trigger a speed test
        boolean bStart = intent.getBooleanExtra(EXTRA_START_WEBSOCKET, true);
        owner.getWebSocketManager().runWebSocket(bStart);
        //owner.triggerSpeedTest(trigger);
    } else if (action.equals(ACTIVE_TEST)) {
        //this is supposed to trigger a speed test
        int evType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        EventType eventType = EventType.get(evType);
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(eventType, trigger);
    } else if (action.equals(SMS_TEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        //owner.triggerSMSTest(trigger);
        owner.getEventManager().queueActiveTest(EventType.SMS_TEST, trigger);
    } else if (action.contains(SMS_DELIVERED)) {
        //add delivery time to connection history

        int identifier = intent.getIntExtra("identifier", 0); //in case we need to search connection list to find which SMS
        long deliveryTime = 0;

        switch (getResultCode()) {
        case Activity.RESULT_OK:
            deliveryTime = System.currentTimeMillis();
            break;
        case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NO_SERVICE:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_NULL_PDU:
            deliveryTime = -1;
            break;
        case SmsManager.RESULT_ERROR_RADIO_OFF:
            deliveryTime = -1;
            break;
        }

        owner.getEventManager().handleSMSDeliverNotification(identifier, deliveryTime);
    } else if (action.equals(LATENCY_TEST)) {
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_SPEED_TRIGGER, 0);
        owner.getEventManager().queueActiveTest(EventType.LATENCY_TEST, trigger);
        //owner.runLatencyTest(false);
    } else if (action.equals(ACTION_STOP_SPEEDTEST)) {
        owner.getEventManager().killSpeedTest();
    } else if (action.equals(ACTION_STOP_VIDEOTEST)) {
        int testType = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_TEST_TYPE, 0);
        owner.getEventManager().killActiveTest(testType);
    } else if (action.equals(ROAMING_ON)) {
        dataMonitorStats.setRoaming(true);
    } else if (action.equals(ROAMING_OFF)) {
        dataMonitorStats.setRoaming(false);
    } else if (action.equals("android.intent.action.ANY_DATA_STATE")) {
        String apn = intentExtras.getString("apn");
        String state = intentExtras.getString("state");
        String apnType = intentExtras.getString("apnType");
        String extras = apnType + "" + state;
        if (state.equals("CONNECTED") && !apnType.equals("default"))
            extras = extras + "!";
        if (apnType != null && apnType.equals("default") && apn != null) {
            SharedPreferences securePref = MainService.getSecurePreferences(context);
            securePref.edit().putString(PreferenceKeys.Miscellaneous.KEY_APN, apn).commit();
        }

    } else if (action.equals("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN")) {
        String apn = intentExtras.getString("apn");
        String apnType = intentExtras.getString("apnType");
        String extras = apn + "," + apnType;
    } else if (action.equals("android.intent.action.ACTION_DATA_CONNECTION_FAILED")) {
        String phoneName = intentExtras.getString("phoneName");
        String reason = intentExtras.getString("reason");
        String extras = phoneName + "," + reason;
    } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
        if (owner.getUsageLimits().getDormantMode() > 0)
            return;
        // wifi state change may trigger the event queue to be sent
        //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "NETWORK_STATE_CHANGED_ACTION", "");
        owner.wifiStateChange((NetworkInfo) intentExtras.getParcelable(WifiManager.EXTRA_NETWORK_INFO));
        owner.trackAccessPoints(0);
        dataMonitorStats.setWifi(PhoneState.isNetworkWifi(owner));
    } else if (action.equals(WIMAX_STATE_CHANGE)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(1);
        //         owner.trackAccessPoints();
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED)) {
        owner.trackAccessPoints(0);
    } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
        //         BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //         BluetoothClass bclass = device.getBluetoothClass();
        //         int major = bclass.getMajorDeviceClass();
        //         if (major == 1024)
        //            owner.setBTHeadsetState(0);
        //         owner.trackAccessPoints();
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        try {
            int state = intent.getIntExtra("state", -1);
            owner.setHeadsetState(state);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "error receiving Intent.ACTION_HEADSET_PLUG: " + e);
        }
    } else if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        owner.setHeadsetState(state);
    } else if (action.equals(CommonIntentActionsOld.ACTION_START_VOICETEST)) {
        //this is supposed to trigger a speed test
        int trigger = intent.getIntExtra(CommonIntentBundleKeysOld.EXTRA_VQ_TRIGGER, 0);
        owner.getVQManager().runTest(trigger);
    } else if (action.equals(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE)) {
        owner.getVQManager().runTest(10);
    } else if (action.equals(CommonIntentActionsOld.ACTION_STOP_VOICETEST)) {
        owner.getVQManager().killTest();
    } else if (action.equals(RESTART_MMC_SERVICE)) {
        owner.restartNextIdle();

    } else if (action.equals(STOP_TRACKING_ACTION)) {
        owner.getEventManager().stopTracking();
    } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
        try {
            dataMonitorStats.setScreen(false);
            SignalEx mmcSignal = new SignalEx();
            owner.getPhoneStateListener().processNewMMCSignal(mmcSignal);
            if (owner.getTravelDetector() != null) {
                owner.getPhoneState().screenChanged(false);
                owner.getEventManager().screenChanged(false);
            }
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceive",
                    "received action SCREEN_OFF, calling MainService.processNewMMCSignal()", e);
        }
    } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
        dataMonitorStats.setScreen(true);
        if (owner.getTravelDetector() != null) {
            owner.getPhoneState().screenChanged(true);
            owner.getEventManager().screenChanged(true);
        }
    } else if (action.equals(ACTION_ALARM_MINUTE)) {
        // CPU wakes very briefly only in order to spur cellid updates
        owner.getTravelDetector().triggerTravelCheck();
        QosAPI.checkHostApp(context);
    } else if (action.equals(ACTION_TRACKING_5MINUTE)) {
        owner.getTrackingManager().runTracking();
    } else if (action.equals(ACTION_TRACKING_1MINUTE)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "ACTION_TRACKING_1MINUTE");
        owner.getTrackingManager().runTrackingTests();
    } else if (action.equals(ACTION_ALARM_3HOUR)) {
        dataMonitorStats.prepareAllStatistics();
        owner.getEventManager().triggerUpdateEvent(true, false);
        //         Calendar cal = Calendar.getInstance(); 
        //          int hour = cal.get (Calendar.HOUR_OF_DAY); 
        //         //If 12pm to 3 am
        //          if(((hour >= 0 && hour <= 3) || hour == 24) && owner.isNetworkWifi()) {
        //            //See if transit info needs to be downloaded
        //             
        //             //Don't allow the app to shut down until the work is done, keep the CPU running
        //             MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_ALARM_3HOUR, wakelock turned on and checking transit "
        //                   + "info uptodate at 24-hour: " + hour);
        //             wakeLock.acquire();
        //             
        //             downloadAreasIfOutOfDate();
        //          }
    }
    //      else if(action.equals(ACTION_TRANSIT_DL_DONE)) {
    //         //Allow CPU to move on
    //         if(wakeLock != null) {
    //            wakeLock.release(); 
    //            MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "received action ACTION_TRANSIT_DONE, wakelock turned off");
    //         }
    //      }
    //      else if(action.equals(ACTION_TRANSIT_DL_START)) {
    //         //Don't allow the app to shut down until the work is done, keep the CPU running
    //          MMCLogger.logToFile(MMCLogger.Level.DEBUG, TAG, "onReceive", "ACTION_TRANSIT_DL_START, wakelock turned on and downloading transit if was requested");
    //          wakeLock.acquire();
    //          
    //          downloadAreasIfOutOfDate();
    //      }
    else if (action.equals(ACTION_ALARM_SCANAPPS)) {
        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            dataMonitorStats.scanApps();
            dataMonitorStats.getRunningAppsString(false); // for debug
        }

        // Also using this timer for GCM heartbeats (its a 5 minute heartbeat to tell Google Cloud Messaging to check the socket more often for more reliable push messages)
        // 2 independent timers might wake up device twice as often, doubling the battery impact, so I'm forcing it to use one for both cases
        //         boolean useHeartbeat = PreferenceManager.getDefaultSharedPreferences(owner).getBoolean("KEY_GCM_HEARTBEAT", false);
        //         if (useHeartbeat) {
        //            GcmKeepAlive gcm = new GcmKeepAlive(owner);
        //            gcm.broadcastIntents();
        //         }
    } else if (action.equals(ACTION_ALARM_15MINUTE)) {

        int intervalDM = PreferenceManager.getDefaultSharedPreferences(owner)
                .getInt(PreferenceKeys.Miscellaneous.MANAGE_DATAMONITOR, 0);
        // run datamonitor if enabled
        if (intervalDM > 0) {
            boolean firstBucketDone = PreferenceManager.getDefaultSharedPreferences(owner)
                    .getBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, false);
            if (!firstBucketDone) { //if false, first bucket needs to be done
                dataMonitorStats.firstBucket();
                dataMonitorStats.monitor();
                PreferenceManager.getDefaultSharedPreferences(owner).edit()
                        .putBoolean(PreferenceKeys.Miscellaneous.FIRST_BUCKET, true).commit();
                LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, "MMCIntentHandlerOld", "onReceive",
                        "First bucket at: " + System.currentTimeMillis() / 1000);
            } else {
                dataMonitorStats.monitor();
                //MMCLogger.logToFile(MMCLogger.Level.DEBUG, "MMCIntentHandlerOld", "onReceive", "15 min bucket at: " + System.currentTimeMillis()/1000);
            }
        }
        // regardless, still make sure GPS is idle unless needed
        owner.getGpsManager().safeguardGps();
    } else if (action.equals(GPS_STATE_ON)) {
        dataMonitorStats.setGps(true);
    } else if (action.equals(GPS_STATE_OFF)) {
        dataMonitorStats.setGps(false);
    } else if (action.equals(PHONE_CALL_CONNECT)) {
        dataMonitorStats.setPhone(true);
    } else if (action.equals(PHONE_CALL_DISCONNECT)) {
        dataMonitorStats.setPhone(false);
    } else if (action.equals(HANDOFF)) {
        dataMonitorStats.handoff();
    } else if (action.equals(MANUAL_TRANSIT_START)) {
        long lat = intent.getIntExtra("latitude", 0);
        long lon = intent.getIntExtra("longitude", 0);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lon / 1000000.0);
        location.setAccuracy(-3);

        //         PreferenceManager.getDefaultSharedPreferences(owner).edit().putString(
        //                PreferenceKeys.Miscellaneous.SURVEY_COMMAND,).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putString("transitEvent", String.valueOf(lat) + "," + String.valueOf(lon)).commit();
        reportManager.manualTransitEvent = owner.getEventManager().triggerSingletonEvent(EventType.MAN_TRANSIT);
        reportManager.manualTransitEvent.setLocation(location, 0);
        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_TRANSIT_END)) {
        if (reportManager.manualTransitEvent == null)
            return;
        String accelData = intent.getStringExtra("accelerometer");
        int stationFrom = intent.getIntExtra("stationFrom", 0);
        int stationTo = intent.getIntExtra("stationTo", 0);
        int duration = intent.getIntExtra("duration", 0);
        int corrected = intent.getIntExtra("corrected", 0);
        if (corrected != 0) {
            Location location = reportManager.manualTransitEvent.getLocation();
            location.setAccuracy(-4);
        }

        reportManager.manualTransitEvent.setAppData(accelData); //TODO want this to really be in appdata?
        reportManager.manualTransitEvent.setLookupid1(stationFrom);
        reportManager.manualTransitEvent.setLookupid2(stationTo);
        reportManager.manualTransitEvent.setDuration(duration);
        owner.getEventManager().unstageAndUploadEvent(reportManager.manualTransitEvent, null);
        reportManager.manualTransitEvent = null;
    } else if (action.equals(MANUAL_TRANSIT_CANCEL)) {
        if (reportManager.manualTransitEvent != null) {
            owner.getEventManager().unstageEvent(reportManager.manualTransitEvent);
            ReportManager reportManager = ReportManager.getInstance(owner);
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy = 3",
                    new String[] { String.valueOf(reportManager.manualTransitEvent.getEventTimestamp()) });
            reportManager.manualTransitEvent = null;
        }
    } else if (action.equals(MANUAL_PLOTTING_START)) {
        int floor = intent.getIntExtra("floor", 0);
        //         int type = intent.getIntExtra("type", -1);  //1(indoor) or 2(outdoor)
        int topFloor = intent.getIntExtra("top", -1);
        int lat = intent.getIntExtra("latitude", -1);
        int lng = intent.getIntExtra("longitude", -1);
        long osm_id = intent.getLongExtra("osm_id", 0);
        String poly = intent.getStringExtra("poly");

        reportManager.manualPlottingEvent = owner.getEventManager()
                .triggerSingletonEvent(EventType.MAN_PLOTTING);
        reportManager.manualPlottingEvent.setEventIndex(floor);
        reportManager.manualPlottingEvent.setDuration(topFloor);
        reportManager.manualPlottingEvent.setBuildingID(osm_id);
        reportManager.manualPlottingEvent.setAppData(poly);
        Location location = new Location("");
        location.setLatitude(lat / 1000000.0);
        location.setLongitude(lng / 1000000.0);
        location.setAccuracy(-1);
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "latitude",
                Double.toString(location.getLatitude()));
        reportManager.updateEventField(reportManager.manualPlottingEvent.getLocalID(), "longitude",
                Double.toString(location.getLongitude()));

        reportManager.manualPlottingEvent.setLocation(location, 0);
        presetEventId(reportManager.manualPlottingEvent); // reserve an EventID for this manual sampling event, to be used for Share links

        owner.getTravelDetector().setTravelling(false);
    } else if (action.equals(MANUAL_PLOTTING_END)) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceive", "MANUAL_PLOTTING_END");
        //         owner.getEventManager().unstageEvent(manulaPlottingEvent); //does not upload
        if (reportManager.manualPlottingEvent != null)
            owner.getEventManager().unstageAndUploadEvent(reportManager.manualPlottingEvent, null);
        //After the event was submitted, reset it so we don't restore an old event in ManualMapping
        reportManager.manualPlottingEvent = null;
    } else if (action.equals(MANUAL_PLOTTING_CANCEL)) {
        if (reportManager.manualPlottingEvent != null) {
            reportManager.getDBProvider().delete(TablesEnum.LOCATIONS.getContentUri(),
                    "timestamp > ? And accuracy < 0",
                    new String[] { String.valueOf(reportManager.manualPlottingEvent.getEventTimestamp()) });
            reportManager.manualPlottingEvent = null;

        }
    }
    //      else if(intent.getAction().equals(MMS_RECEIVED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_RECEIVED", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(MMS_SENT)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived MMS_SENT", intentExtras.toString());
    //      }
    //      else if(intent.getAction().equals(SMS_REJECTED)) {
    //         LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "onReceived SMS_REJECTED", intentExtras.toString());
    //      }
    else if (intent.getAction().equals(SMS_RECEIVED)) {
        SmsMessage[] msgs = null;
        //         String msg_from;
        if (intentExtras == null)
            return;

        Object[] pdus = (Object[]) intentExtras.get("pdus");
        msgs = new SmsMessage[pdus.length];
        String[] msgBody = new String[msgs.length];
        for (int i = 0; i < msgs.length; i++) {
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            //            msg_from = msgs[i].getOriginatingAddress();
            String msg = msgs[i].getMessageBody().trim();
            if (msg.length() > 10) {
                msg = msg.substring(1, msg.length() - 1);
                msg = "{" + msg + "}";
            }

            msgBody[i] = msg;

        }
        handleCommands(msgBody, true, 0);
    } else if (action.equals(VIEWING_SIGNAL)) {
        owner.setEnggQueryTime();
    } else if (intent.getAction().equals(SURVEY)) {
        if (intentExtras == null)
            return;

        int surveyid = intentExtras.getInt(SURVEY_EXTRA);
        postSurvey(surveyid);
    } else if (intent.getAction().equals(GCM_MESSAGE)) {
        if (intentExtras == null)
            return;
        try {
            String msg = intentExtras.getString(GCM_MESSAGE_EXTRA);
            long starttime = intentExtras.getLong("GCM_STARTTIME_EXTRA");
            EventResponse eventResponse = gson.fromJson(msg, EventResponse.class);
            eventResponse.init();
            eventResponse.setStartTime(starttime);
            eventResponse.handleEventResponse(owner, true);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "onReceived GCM_MESSAGE", "exception", e);
        }
    } else if (intent.getAction().equals(COMMAND)) {
        if (intentExtras == null)
            return;

        String commands = intentExtras.getString(COMMAND_EXTRA);
        if (commands == null)
            return;
        long starttime = intent.getLongExtra("STARTTIME_EXTRA", 0);
        String[] msgs = null;
        try {
            JSONArray cmds = new JSONArray(commands);
            msgs = new String[cmds.length()];
            for (int j = 0; j < cmds.length(); j++)
                msgs[j] = cmds.getJSONObject(j).toString();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }
        //commands = commands.replace("[", "");
        //commands = commands.replace("]", "");
        //String msgs[] = commands.split("/");
        handleCommands(msgs, false, starttime);
    }

    else if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
        int val = 0;
        val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        String msg = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE");
        String msg2 = intent.getStringExtra("android.telecom.extra.CALL_DISCONNECT_MESSAGE");
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "String CALL_DISCONNECT_CAUSE", msg);
        //MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "Int CALL_DISCONNECT_CAUSE", ""+val);
    } else if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
        String phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
        //if (phoneNumber != null)
        //    MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "NEW_OUTGOING_CALL", phoneNumber);
    }

    else if (intent.getAction().equals("android.intent.action.PRECISE_CALL_STATE")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state_ringing = intent.getIntExtra("ringing_state", -1);
        int state_foreground = intent.getIntExtra("foreground_state", -1);
        int state_background = intent.getIntExtra("background_state", -1);

        int disconnect_cause = intent.getIntExtra("disconnect_cause", -1);
        int precise_disconnect_cause = intent.getIntExtra("precise_disconnect_cause", -1);
        PreciseCallCodes precisecall = new PreciseCallCodes(state_ringing, state_foreground, state_background,
                disconnect_cause, precise_disconnect_cause);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "PRECISE_CALL_STATE", precisecall.toString());
        owner.getPhoneStateListener().onPreciseCallState(precisecall);
    } else if (intent.getAction().equals("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED")) {
        int val = 0;
        //val = intent.getIntExtra("android.telecom.extra.CALL_DISCONNECT_CAUSE", -1);
        int state = intent.getIntExtra("state", -1);
        int networkType = intent.getIntExtra("networkType", -1);
        String reason = intent.getStringExtra("reason");
        String failCause = intent.getStringExtra("failCause");
        String apnType = intent.getStringExtra("apnType");
        String apn = intent.getStringExtra("apn");
        Object linkProperties = intent.getParcelableExtra("linkProperties");
        if (!apnType.equals("default"))
            return;
        //         if (failCause != null && failCause.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
        //         else if (reason != null && reason.length() > 0)
        //         {
        //            String msg = String.format("state:%d,netType:%d,apnType:%s,reason:%s\r\nfailCause:%s", state,networkType,apnType,reason,failCause);
        //            MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            if (linkProperties != null)
        //            {
        //               msg = String.format("PRECISE_DATA_CONNECTION_STATE_CHANGED  linkProperties:%s", linkProperties.toString());
        //               MMCLogger.logToFile(MMCLogger.Level.ERROR, TAG, "PRECISE_DATA_CONNECTION_STATE_CHANGED", msg);
        //            }
        //         }
    } else if (intent.getAction().equals("org.restcomm.android.CONNECT_FAILED")
            || intent.getAction().equals("org.restcomm.android.CALL_STATE")
            || intent.getAction().equals("org.restcomm.android.DISCONNECT_ERROR")) {
        owner.getPhoneStateListener().getRestCommManager().handleIntent(owner, intent);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_DISCONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String cause = intent.getStringExtra(EXTRA_RADIOLOG_DISC_CAUSE);
        owner.getPhoneStateListener().onDisconnect(time, cause);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_CONNECT)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String state = intent.getStringExtra(EXTRA_RADIOLOG_CONN_STATE);
        owner.getPhoneStateListener().onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_NEIGHBORS)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String neighbors = intent.getStringExtra(EXTRA_RADIOLOG_NEIGHBORS);
        //owner.onConnect(time, state);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMODE)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String jsonstr = intent.getStringExtra(EXTRA_RADIOLOG_SVC_JSON);
        JSONObject json = null;
        try {
            json = new JSONObject(jsonstr);
        } catch (Exception e) {
        }
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMode(time, json, values, name);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_SERVICEMENU)) {
        String time = intent.getStringExtra(EXTRA_RADIOLOG_TIME);
        String values = intent.getStringExtra(EXTRA_RADIOLOG_SVC_TEXT);
        String name = intent.getStringExtra(EXTRA_RADIOLOG_SVC_NAME);
        owner.getPhoneStateListener().onServiceMenu(time, values, name);
    } else if (intent.getAction().equals(ACTION_MMCSYS_VERSION)) {
        Integer version = intent.getIntExtra(EXTRA_MMCSYS_VERSION, 0);
        owner.onSvcModeVersion(version);
    } else if (intent.getAction().equals(ACTION_RADIOLOG_ERROR)) {
        String error = intent.getStringExtra(EXTRA_RADIOLOG_ERROR);
        String details = intent.getStringExtra(EXTRA_RADIOLOG_ERROR_DETAIL);
        LoggerUtil.logToFile(LoggerUtil.Level.ERROR, "RilReader", error, details);
        //owner.onConnect(time, state);
    }

}

From source file:ibme.sleepap.recording.SignalsRecorder.java

/**
 * Called when the activity is first created. onStart() is called
 * immediately afterwards.// w  w w  .ja v a  2s. c  o m
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.signals_recorder);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // Log both handled and unhandled issues.
    if (sharedPreferences.getBoolean(Constants.PREF_WRITE_LOG, Constants.DEFAULT_WRITE_LOG)) {
        String bugDirPath = Environment.getExternalStorageDirectory().toString() + "/"
                + getString(R.string.app_name) + "/" + Constants.FILENAME_LOG_DIRECTORY;
        File bugDir = new File(bugDirPath);
        if (!bugDir.exists()) {
            bugDir.mkdirs();
        }
        String handledFileName = bugDirPath + "/logcat" + System.currentTimeMillis() + ".trace";
        String unhandledFileName = bugDirPath + "/unhandled" + System.currentTimeMillis() + ".trace";
        // Log any warning or higher, and write it to handledFileName.
        String[] cmd = new String[] { "logcat", "-f", handledFileName, "*:W" };
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (IOException e1) {
            Log.e(Constants.CODE_APP_TAG, "Error creating bug files", e1);
        }
        Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(unhandledFileName));
    }

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    extras = getIntent().getBundleExtra(Constants.EXTRA_RECORDING_SETTINGS);
    actigraphyEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_ACTIGRAPHY, false);
    audioEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_AUDIO, false);
    ppgEnabled = extras.getBoolean(Constants.EXTRA_COLLECT_PPG, false);
    dateTimeString = DateFormat.format(Constants.PARAM_DATE_FORMAT, System.currentTimeMillis()).toString();
    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    magnetometer = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    String appDirPath = Environment.getExternalStorageDirectory().toString() + "/"
            + getString(R.string.app_name);
    filesDirPath = appDirPath + "/" + dateTimeString + "/";
    lastAccelerometerRecordedTime = 0;
    lastPositionChangeTime = System.currentTimeMillis();
    PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.CODE_APP_TAG);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    actigraphyQueue = new LinkedList<Double>();
    positionDisplay = (TextView) findViewById(R.id.position);
    recordingSign = (ImageView) findViewById(R.id.recordingSign);

    for (int i = 0; i < 5; ++i) {
        totalPositionTime[i] = 0;
    }

    // Battery check receiver.
    registerReceiver(this.batteryLevelReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    // Button to stop the recording.
    Button stopButton = (Button) findViewById(R.id.buttonStop);
    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewNext) {
            stopRecording();
        }
    });

    // Button to reconnect the bluetooth.
    reconnectButton = (Button) findViewById(R.id.reconnectButton);
    reconnectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View viewNext) {
            String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS,
                    Constants.DEFAULT_MAC_ADDRESS);
            noninManager = null;
            noninManager = new NoninManager(getApplicationContext(), bluetoothAdapter, macAddress,
                    new PpgHandler(SignalsRecorder.this));
            noninManager.start();
            reconnectButton.setEnabled(false);
            reconnectButton.setClickable(false);
        }
    });

    // Create a folder for the recordings, and delete any extra recordings.
    File dir = new File(filesDirPath);
    if (!dir.exists()) {
        dir.mkdirs();
        File appDir = new File(appDirPath);

        // Create a list of recordings in the app directory. These
        // are named by the date on which they were formed and so can be in
        // date order (earliest first).
        String[] recordingDirs = appDir.list();
        Arrays.sort(recordingDirs);

        // How many more recordings do we have in the app directory than are
        // specified in the settings? Should account for questionnaires
        // file,
        // which must exist for the user to have gotten to this stage
        // (checklist).

        int numberRecordings = 0;
        for (String folderOrFileName : recordingDirs) {
            if (!folderOrFileName.equals(Constants.FILENAME_QUESTIONNAIRE)
                    && !folderOrFileName.equals(Constants.FILENAME_LOG_DIRECTORY)
                    && !folderOrFileName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) {
                numberRecordings++;
            }
        }

        int extraFiles = numberRecordings - Integer.parseInt(sharedPreferences
                .getString(Constants.PREF_NUMBER_RECORDINGS, Constants.DEFAULT_NUMBER_RECORDINGS));

        if (extraFiles > 0) {
            // Too many recordings. Delete the earliest n, where n is the
            // number of extra files.
            boolean success;
            int nDeleted = 0;
            for (String candidateFolderName : recordingDirs) {
                if (nDeleted >= extraFiles) {
                    // We've deleted enough already.
                    break;
                }
                if (candidateFolderName.equals(Constants.FILENAME_QUESTIONNAIRE)
                        || candidateFolderName.equals(Constants.FILENAME_LOG_DIRECTORY)
                        || candidateFolderName.equals(Constants.FILENAME_FEEDBACK_DIRECTORY)) {
                    // Don't delete questionnaire file or log/feedback
                    // directory.
                    continue;
                }
                // See if the path is a directory, and skip it if it isn't.
                File candidateFolder = new File(appDir, candidateFolderName);
                if (!candidateFolder.isDirectory()) {
                    continue;
                }
                // If we've got to this stage, the file is the earliest
                // recording and should be deleted. Delete files in
                // recording first.
                success = Utils.deleteDirectory(candidateFolder);
                if (success) {
                    nDeleted++;
                }
            }
        }
    }

    // Copy latest questionnaire File
    try {
        File latestQuestionnaireFile = new File(appDirPath, Constants.FILENAME_QUESTIONNAIRE);
        InputStream in = new FileInputStream(latestQuestionnaireFile);
        OutputStream out = new FileOutputStream(new File(filesDirPath, Constants.FILENAME_QUESTIONNAIRE));
        // Copy the bits from instream to outstream
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    } catch (FileNotFoundException e) {
        Log.e(Constants.CODE_APP_TAG, "FileNotFoundException copying Questionnaire file.");
    } catch (IOException e) {
        Log.e(Constants.CODE_APP_TAG, "IOException copying Questionnaire file.");
    }

    // Create txt files.
    orientationFile = new File(filesDirPath, Constants.FILENAME_ORIENTATION);
    accelerationFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_RAW);
    actigraphyFile = new File(filesDirPath, Constants.FILENAME_ACCELERATION_PROCESSED);
    audioProcessedFile = new File(filesDirPath, Constants.FILENAME_AUDIO_PROCESSED);
    bodyPositionFile = new File(filesDirPath, Constants.FILENAME_POSITION);
    ppgFile = new File(filesDirPath, Constants.FILENAME_PPG);
    spo2File = new File(filesDirPath, Constants.FILENAME_SPO2);
    audioRawFile = new File(filesDirPath, Constants.FILENAME_AUDIO_RAW);

    /** Recording starts here. */
    // Log start time so recording can begin in 30 minutes.
    startTime = Calendar.getInstance(Locale.getDefault());
    finishRecordingFlag = false;
    recordingStartDelayMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences
            .getString(Constants.PREF_RECORDING_START_DELAY, Constants.DEFAULT_RECORDING_START_DELAY));
    recordingDurationMs = Constants.CONST_MILLIS_IN_MINUTE * Integer.parseInt(sharedPreferences
            .getString(Constants.PREF_RECORDING_DURATION, Constants.DEFAULT_RECORDING_DURATION));
    if (recordingStartDelayMs > 0) {
        startRecordingFlag = false;
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
        dialogBuilder.setTitle(getString(R.string.delayAlertTitle))
                .setMessage(getString(R.string.delayAlertMessage1) + " "
                        + sharedPreferences.getString(Constants.PREF_RECORDING_START_DELAY,
                                Constants.DEFAULT_RECORDING_START_DELAY)
                        + " " + getString(R.string.delayAlertMessage2))
                .setPositiveButton(getString(R.string.ok), null);
        delayAlertDialog = dialogBuilder.create();
        delayAlertDialog.show();
    } else {
        startRecordingFlag = true;
        // Notify user
        Intent notificationIntent = new Intent(SignalsRecorder.this, SignalsRecorder.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        if (sharedPreferences.getBoolean(Constants.PREF_NOTIFICATIONS, Constants.DEFAULT_NOTIFICATIONS)) {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                    .setSmallIcon(R.drawable.notification_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.deviceaccessmic))
                    .setContentTitle("SleepAp").setContentText(getString(R.string.startedRecordingNotification))
                    .setAutoCancel(false).setOngoing(true).setContentIntent(pendingIntent);
            notificationManager.notify(Constants.CODE_APP_NOTIFICATION_ID, builder.build());
            recordingSign.setVisibility(View.VISIBLE);
        }
    }

    // Start audio recording.
    if (audioEnabled) {
        extAudioRecorder = new ExtAudioRecorder(this);
        extAudioRecorder.setOutputFile(audioRawFile);
        extAudioRecorder.setShouldWrite(startRecordingFlag);
        extAudioRecorder.setAudioProcessedFile(audioProcessedFile);
        extAudioRecorder.prepare();
        extAudioRecorder.start();
    }

    // Start PPG recording.
    if (ppgEnabled && bluetoothAdapter != null) {
        String macAddress = sharedPreferences.getString(Constants.PREF_MAC_ADDRESS,
                Constants.DEFAULT_MAC_ADDRESS);
        noninManager = new NoninManager(this, bluetoothAdapter, macAddress,
                new PpgHandler(SignalsRecorder.this));
        noninManager.start();
    }

    // Start actigraphy recording.
    if (actigraphyEnabled) {
        sensorManager.registerListener(this, accelerometer, 1000000
                / (Constants.PARAM_SAMPLERATE_ACCELEROMETER * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER));
        sensorManager.registerListener(this, magnetometer, 1000000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER);
    }
    wakeLock.acquire();

    // Set up listener so that if Bluetooth connection is lost we set give
    // the user an option to reconnect.
    if (ppgEnabled) {
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);

        registerReceiver(bluetoothDisconnectReceiver, filter);
    }

    // Start graphs update.
    graphUpdateTask = new UserInterfaceUpdater();
    graphUpdateTask.execute();
}

From source file:org.restcomm.app.qoslib.Services.Intents.IntentHandler.java

public IntentFilter declareIntentFilters() {
    IntentFilter intentFilter = new IntentFilter(IntentHandler.UPDATE_ACTION);
    intentFilter.addAction(IntentHandler.START_TRACKING_ACTION);
    intentFilter.addAction(IntentHandler.TRACK_REMOTE);
    intentFilter.addAction(IntentHandler.STOP_TRACKING_ACTION);
    intentFilter.addAction(IntentHandler.SPEED_TEST);
    intentFilter.addAction(IntentHandler.RUN_WEBSOCKET);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_START_UI);

    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_LOCATION_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_CELL_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_GPS_STATUS_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_SIGNAL_STRENGTH_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_EVENT_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_NEIGHBOR_UPDATE);
    intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_NETWORK_UPDATE);
    //intentFilter.addAction(CommonIntentBundleKeysOld.ACTION_RX_TX);

    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_RESULT);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_ERROR);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_COMPLETE);
    intentFilter.addAction(IntentHandler.ACTION_SPEEDTEST_CANCELLED);

    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_RESULT);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_ERROR);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_COMPLETE);
    intentFilter.addAction(IntentHandler.ACTION_WEBTEST_CANCELLED);

    //do not add filter if sms test permissions aren't all allowed
    if (PreferenceKeys.getSMSPermissionsAllowed(owner, true))
        intentFilter.addAction(IntentHandler.SMS_TEST);

    intentFilter.addAction(IntentHandler.SMS_DELIVERED);
    intentFilter.addAction(IntentHandler.LATENCY_TEST);
    intentFilter.addAction(IntentHandler.ACTION_STOP_SPEEDTEST);
    intentFilter.addAction(IntentHandler.RESTART_MMC_SERVICE);
    intentFilter.addAction(IntentHandler.COLDRESET_ACTION);
    intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
    intentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
    intentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    intentFilter.addAction(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(IntentHandler.COMMAND);
    intentFilter.addAction(IntentHandler.SURVEY);
    //intentFilter.addAction(Intent.ACTION_VIEW);
    //intentFilter.addAction("android.intent.PHONE_STATE");
    intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_TRACKING_5MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_TRACKING_1MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_3HOUR);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_15MINUTE);
    intentFilter.addAction(IntentHandler.ACTION_ALARM_SCANAPPS);
    intentFilter.addAction(IntentHandler.EMAIL_CSV);
    intentFilter.addAction(IntentHandler.GPS_STATE_OFF);
    intentFilter.addAction(IntentHandler.GPS_STATE_ON);
    intentFilter.addAction(IntentHandler.PHONE_CALL_CONNECT);
    intentFilter.addAction(IntentHandler.PHONE_CALL_DISCONNECT);
    intentFilter.addAction(IntentHandler.HANDOFF);
    //intentFilter.addAction(IntentHandler.SMS_SENT);
    intentFilter.addAction(IntentHandler.SMS_RECEIVED);
    intentFilter.addAction(Intent.ACTION_SEND);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_START);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_END);
    intentFilter.addAction(IntentHandler.MANUAL_PLOTTING_CANCEL);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_START);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_END);
    intentFilter.addAction(IntentHandler.MANUAL_TRANSIT_CANCEL);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
    intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);

    intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
    intentFilter.addAction(IntentHandler.ROAMING_ON);
    intentFilter.addAction(IntentHandler.ROAMING_OFF);

    intentFilter.addAction(IntentHandler.VIEWING_SIGNAL);
    intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
    intentFilter.addAction("android.intent.action.PRECISE_CALL_STATE");
    intentFilter.addAction("android.intent.action.PRECISE_DATA_CONNECTION_STATE_CHANGED");
    intentFilter.addAction("android.intent.action.PHONE_STATE");
    intentFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");

    intentFilter.addAction("android.intent.action.DATA_CONNECTION_CONNECTED_TO_PROVISIONING_APN");
    intentFilter.addAction("android.intent.action.ANY_DATA_STATE");
    intentFilter.addAction("android.intent.action.ACTION_DATA_CONNECTION_FAILED");

    intentFilter.addAction(CommonIntentActionsOld.ACTION_BLUETOOTH_ENDDOWNLOAD);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_START_VOICETEST);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_STOP_VOICETEST);
    intentFilter.addAction(CommonIntentActionsOld.ACTION_TEST_VQ_DEVICE);

    intentFilter.addAction(IntentHandler.ACTIVE_TEST);
    intentFilter.addAction(IntentHandler.ACTION_STOP_VIDEOTEST);
    intentFilter.addAction(IntentHandler.GCM_MESSAGE);

    intentFilter.addAction("org.restcomm.android.CONNECT_FAILED");
    intentFilter.addAction("org.restcomm.android.CALL_STATE");
    intentFilter.addAction("org.restcomm.android.DISCONNECT_ERROR");

    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_DISCONNECT);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_CONNECT);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_NEIGHBORS);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_SERVICEMODE);
    intentFilter.addAction(IntentHandler.ACTION_RADIOLOG_SERVICEMENU);
    intentFilter.addAction(IntentHandler.ACTION_MMCSYS_VERSION);

    //intentFilter.addAction(Intent.ACTION_APP_ERROR);
    int raisePriority = owner.getPackageManager().checkPermission("android.permission.RAISED_THREAD_PRIORITY",
            owner.getPackageName());/*from w  ww . ja  va 2s  . c o  m*/
    // With permission to raise priority for SMS messages
    if (raisePriority == 0)
        intentFilter.setPriority(9999999);

    return intentFilter;
}