Example usage for android.hardware SensorManager getDefaultSensor

List of usage examples for android.hardware SensorManager getDefaultSensor

Introduction

In this page you can find the example usage for android.hardware SensorManager getDefaultSensor.

Prototype

public Sensor getDefaultSensor(int type) 

Source Link

Document

Use this method to get the default sensor for a given type.

Usage

From source file:net.line2soft.preambul.views.SlippyMapActivity.java

/**
 * Init map's overlays (compass, buttons, ...), attach listener.
 * You can launch map on normal or edit mode (to pick a position).
 * @param addFavorite If true, edit mode (to add favorite), if false normal mode
 *//* w w  w . j  a v  a  2 s . c o  m*/
private void initMap(boolean addFavorite) {
    if (addFavorite == false) {
        //Launch map in normal mode
        findViewById(R.id.list_item).setVisibility(View.VISIBLE);
        findViewById(R.id.drawer).setVisibility(View.VISIBLE);

        //Add listener on excursions button
        ImageButton btExcursionsImg = (ImageButton) findViewById(R.id.imageButton1);
        btExcursionsImg.setOnClickListener(listener);
        btExcursionsImg.setVisibility(View.VISIBLE);
        findViewById(R.id.excursionButton).setVisibility(View.VISIBLE);
        ((ImageButton) findViewById(R.id.imageRight)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.imageLeft)).setOnClickListener(listener);
        ((ImageButton) findViewById(R.id.favoritesButton)).setOnClickListener(listener);

        //Display POIs on map
        try {
            PointOfInterest[] pois = MapController.getInstance(this).getCurrentLocation().getPOIs(this);
            Drawable icon = null;
            OverlayItem item = null;
            boolean displayPoiType = true;
            for (PointOfInterest poi : pois) {
                displayPoiType = PreferenceManager.getDefaultSharedPreferences(this)
                        .getBoolean("type" + poi.getType().getId(), true);
                if (displayPoiType) {
                    icon = (poi.getType().getIcon() == null) ? poi.getType().getCategory().getIcon()
                            : poi.getType().getIcon();
                    item = new OverlayItem(poi.getPoint(), poi.getName(), poi.getComment(),
                            BalloonItemizedOverlay.boundLeftCenter(icon));
                    overlayPoiItemMarker.addItem(item, poi);
                }
            }
        } catch (Exception e) {
            displayInfo(getString(R.string.message_map_poi_load_error));
            e.printStackTrace();
        }

        //Display favorites on map
        try {
            HashMap<String, NamedPoint> favorites = MapController.getInstance(this).getCurrentLocation()
                    .getNamedFavorites(this);
            Drawable icon = getResources().getDrawable(R.drawable.marker_favorite);
            OverlayItem item = null;
            for (NamedPoint favPoint : favorites.values()) {
                item = new OverlayItem(favPoint.getPoint(), favPoint.getName(), favPoint.getComment(),
                        BalloonItemizedOverlay.boundLeftCenter(icon));
                overlayPoiItemMarker.addItem(item, favPoint);
            }
        } catch (IOException e) {
            displayInfo(getString(R.string.message_map_favorite_load_error));
            e.printStackTrace();
        }

        //Display excursions and instruction on map
        int pathToDisplay = MapController.getInstance(this).getPathToDisplay();
        displayExcursion(pathToDisplay);
        int instructionToDisplay = MapController.getInstance(this).getInstructionToDisplay() - 1;
        //Set instruction, only if > 0 because if instruction=0, was set when displaying excursion
        if (instructionToDisplay > 0) {
            setNavigationInstructionToDisplay(instructionToDisplay);
        }
        //Display of the bookmarksButton
        boolean displaybookmarksButton = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayBookmarksButton", true);
        ImageButton img = (ImageButton) findViewById(R.id.favoritesButton);
        if (displaybookmarksButton) {
            img.setVisibility(View.VISIBLE);
        } else {
            img.setVisibility(View.GONE);
        }
        //Display point
        GeoPoint pointToDisplay = MapController.getInstance(this).getPointToDisplay();
        if (pointToDisplay != null) {
            displayPosition(pointToDisplay.getLatitude(), pointToDisplay.getLongitude());
            MapController.getInstance(this).setPointToDisplay(null);
        }
        //Launch compass
        boolean displayCompass = PreferenceManager.getDefaultSharedPreferences(this)
                .getBoolean("displayCompass", true);
        CompassView cpv = (CompassView) findViewById(R.id.compass);
        CompassView cpvBig = (CompassView) findViewById(R.id.compassBig);
        if (displayCompass) {
            SensorManager mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            Sensor mAccelerometer = mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            Sensor mField = mySensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
            if (mField != null && mAccelerometer != null) {
                mySensorManager.registerListener(listener, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
                mySensorManager.registerListener(listener, mField, SensorManager.SENSOR_DELAY_UI);
                cpv.setOnClickListener(listener);
                if (isCompassAccurate) {
                    cpv.setVisibility(View.VISIBLE);
                } else {
                    displayInfo(getString(R.string.message_compass_not_accurate));
                    cpv.setVisibility(View.GONE);
                }
                cpvBig.setVisibility(View.GONE);
                cpvBig.setOnClickListener(listener);
            } else {
                cpv.setVisibility(View.GONE);
                cpvBig.setVisibility(View.GONE);
            }
        } else {
            cpv.setVisibility(View.GONE);
            cpvBig.setVisibility(View.GONE);
        }

        //Hide validate button
        findViewById(R.id.validatePositionButton).setVisibility(View.GONE);
        findViewById(R.id.imageViewValidate).setVisibility(View.GONE);
        findViewById(R.id.mapPointer).setVisibility(View.GONE);
    } else {
        //Launch map in edit mode, to set coordinates of a favorite
        findViewById(R.id.list_item).setVisibility(View.GONE);
        findViewById(R.id.compass).setVisibility(View.GONE);
        findViewById(R.id.drawer).setVisibility(View.GONE);
        findViewById(R.id.favoritesButton).setVisibility(View.GONE);

        findViewById(R.id.mapPointer).setVisibility(View.VISIBLE);

        //Display validate button and add listener
        findViewById(R.id.validatePositionButton).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setVisibility(View.VISIBLE);
        findViewById(R.id.imageViewValidate).setOnClickListener(listener);

        this.addFavorite = false;
    }
}

From source file:com.google.android.apps.santatracker.dasherdancer.DasherDancerActivity.java

@Override
public void onResume() {
    super.onResume();
    SensorManager manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    Sensor accel = manager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    manager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
    mDetector.start(manager);//from www  .j  a v  a 2 s .  co  m

    if (mInitialized) {
        //Start the animation for the first character.
        mPager.postDelayed(new Runnable() {

            @Override
            public void run() {
                loadAnimation(true, sCharacters[mPager.getCurrentItem()].getDuration(Character.ANIM_IDLE),
                        sCharacters[mPager.getCurrentItem()].getFrameIndices(Character.ANIM_IDLE),
                        sCharacters[mPager.getCurrentItem()].getFrames(Character.ANIM_IDLE));
            }

        }, 300);
    } else {
        if (mLoadAllBitmapsTask != null) {
            mLoadAllBitmapsTask.cancel(true);
        }
        mLoadAllBitmapsTask = new LoadAllBitmapsTask();
        mLoadAllBitmapsTask.execute(sCharacters[mPager.getCurrentItem()]);
    }
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupAccel() {
    SensorManager mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    Sensor mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

    mSensorManager.registerListener(new SensorEventListener() {
        @Override/*from w ww  .j  a  v  a  2s.  c o  m*/
        public void onSensorChanged(SensorEvent event) {
            if (!Moving && currentTrottle > 20) {
                float[] filtered = new float[3];
                lowPass(event.values, filtered);

                float x = getAverageX(filtered[0]);
                float y = getAverageY(filtered[1]);

                currentXOffset += x * multiValue;
                currentYOffset += y * multiValue;

                if (currentXOffset > maxOffset) {
                    currentXOffset = maxOffset;
                } else if (currentXOffset < -maxOffset) {
                    currentXOffset = -maxOffset;
                }

                if (currentYOffset > maxOffset) {
                    currentYOffset = maxOffset;
                } else if (currentYOffset < -maxOffset) {
                    currentYOffset = -maxOffset;
                }

                if (PitchCorrection != (int) currentYOffset && RollCorrection != (int) currentXOffset) {
                    PitchCorrection = (int) currentYOffset;
                    RollCorrection = -(int) currentXOffset;

                    JSONObject msg = new JSONObject();
                    try {
                        msg.put("action", "correction_update");
                        msg.put("pitch", PitchCorrection);
                        msg.put("roll", RollCorrection);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    sendTextMessage(msg.toString());
                    updateThrottle(currentTrottle);
                }
            } else if (!Moving && currentTrottle <= 20) {
                PitchCorrection = 0;
                RollCorrection = 0;

                JSONObject msg = new JSONObject();
                try {
                    msg.put("action", "correction_update");
                    msg.put("pitch", PitchCorrection);
                    msg.put("roll", RollCorrection);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendTextMessage(msg.toString());
                updateThrottle(currentTrottle);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    }, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static void enableDeviceMotion(boolean enable) {
    LayerView v = GeckoApp.mAppContext.getLayerController().getView();
    SensorManager sm = (SensorManager) v.getContext().getSystemService(Context.SENSOR_SERVICE);

    if (gAccelerometerSensor == null || gOrientationSensor == null) {
        gAccelerometerSensor = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        gOrientationSensor = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    }//from  w w  w.  java 2s.c o  m

    if (enable) {
        if (gAccelerometerSensor != null)
            sm.registerListener(GeckoApp.mAppContext, gAccelerometerSensor, SensorManager.SENSOR_DELAY_GAME);
        if (gOrientationSensor != null)
            sm.registerListener(GeckoApp.mAppContext, gOrientationSensor, SensorManager.SENSOR_DELAY_GAME);
    } else {
        if (gAccelerometerSensor != null)
            sm.unregisterListener(GeckoApp.mAppContext, gAccelerometerSensor);
        if (gOrientationSensor != null)
            sm.unregisterListener(GeckoApp.mAppContext, gOrientationSensor);
    }
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static void enableSensor(int aSensortype) {
    SensorManager sm = (SensorManager) GeckoApp.mAppContext.getSystemService(Context.SENSOR_SERVICE);

    switch (aSensortype) {
    case SENSOR_PROXIMITY:
        if (gProximitySensor == null)
            gProximitySensor = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sm.registerListener(GeckoApp.mAppContext, gProximitySensor, SensorManager.SENSOR_DELAY_GAME);
        break;//from   w w  w  .j ava  2s.  c  o  m
    }
}

From source file:tv.piratemedia.flightcontroller.BluetoothComputerFragment.java

public void setupGyro() {
    final Handler TimeoutHandler = new Handler();
    SensorManager mSensorManager;
    Sensor mSensor;/*from  w ww  .  j  a v  a 2  s .  co m*/

    mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
    mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);

    SensorEventListener sensorListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            int X = (int) (event.values[0] / 2.0f);
            int Y = (int) (event.values[1] / 2.0f);
            int Z = (int) (event.values[2] / 2.0f);
            Y = -Y;

            //Log.d("gyro", "X: " + X + " Y: " + Y + " Z: " + Z);
            if (currentPitch != Y || currentRoll != X || currentYaw != Z) {
                if (!Moving && currentTrottle > 10) {
                    if ((PitchCorrection < MaxCorrectionValue || Y < 0)
                            && (PitchCorrection > -MaxCorrectionValue || Y > 0)) {
                        PitchCorrection += Y;
                        if (PitchCorrection > MaxCorrectionValue) {
                            PitchCorrection = MaxCorrectionValue;
                        } else if (PitchCorrection < -MaxCorrectionValue) {
                            PitchCorrection = -MaxCorrectionValue;
                        }
                    }
                    if ((RollCorrection < MaxCorrectionValue || X < 0)
                            && (RollCorrection > -MaxCorrectionValue || X > 0)) {
                        RollCorrection += X;
                        if (RollCorrection > MaxCorrectionValue) {
                            RollCorrection = MaxCorrectionValue;
                        } else if (RollCorrection < -MaxCorrectionValue) {
                            RollCorrection = -MaxCorrectionValue;
                        }
                    }
                    updateThrottle(currentTrottle);
                } else if (currentTrottle <= 10) {
                    PitchCorrection = 0;
                    RollCorrection = 0;
                }
                currentPitch = Y;
                currentRoll = X;
                currentYaw = Z;

                JSONObject msg = new JSONObject();
                try {
                    msg.put("action", "gyro_update");
                    msg.put("x", currentRoll);
                    msg.put("y", currentPitch);
                    msg.put("z", currentYaw);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                sendTextMessage(msg.toString());
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };

    if (mSensor != null) {
        mSensorManager.registerListener(sensorListener, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
    } else {
        Toast.makeText(getActivity().getApplicationContext(), "No Gravity Sensor on device", Toast.LENGTH_LONG)
                .show();
    }
}

From source file:com.google.android.apps.santatracker.games.gumball.TiltGameFragment.java

/**
 * Continue the paused game.//  w w w.  j a  v a 2  s.  co m
 * Restart the countdown timer and hide the pause game screen.
 */
private void unPauseGame() {
    mViewPauseButton.setVisibility(View.VISIBLE);
    mViewPlayButton.setVisibility(View.GONE);
    mViewMatchPauseOverlay.setVisibility(View.GONE);
    mViewCancelBar.setVisibility(View.GONE);
    mCountDownTimer = new GameCountdown(mFramesPerSecond, mTimeLeftInMillis);
    mCountDownTimer.start();
    mGameView.setGameCountDown(mCountDownTimer);
    wasPaused = false;
    SensorManager sensorManager = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
    Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    if (sensor != null) {
        sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
    }
    if (Utils.hasKitKat()) {
        ImmersiveModeHelper.setImmersiveSticky(getActivity().getWindow());
    }
}

From source file:com.google.android.apps.santatracker.games.gumball.TiltGameFragment.java

@Override
public void onResume() {
    super.onResume();

    // Resume the game play if the game was not paused
    if (!wasPaused) {
        mRotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        SensorManager sensorManager = (SensorManager) getActivity().getSystemService(Activity.SENSOR_SERVICE);
        Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (sensor != null) {
            sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_GAME);
        }//from w ww . j  av a 2s . c o m
        mCountDownTimer = new GameCountdown(mFramesPerSecond, mTimeLeftInMillis);
        mCountDownTimer.start();
        mGameView.setGameCountDown(mCountDownTimer);
    }

    // Start the game loop if it is not initialised yet
    if (mGameThread == null) {
        mGameThread = new Runnable() {
            public void run() {
                synchronized (mWorld) {
                    if (!wasPaused) {
                        if (mCurrentLevelNum == 0) {
                            mCurrentLevelNum++;
                            loadLevel(mCurrentLevelNum);
                        }
                        mWorld.update();
                        mGameView.invalidate();
                    }
                }
                getActivity().getWindow().getDecorView().postDelayed(mGameThread, 10);
            }
        };
    }
    getActivity().getWindow().getDecorView().postDelayed(mGameThread, 1000);

    loadBackgroundMusic();
    updateSignInButtonVisibility();
}

From source file:com.coincide.alphafitness.ui.Fragment_Main.java

@Override
public void onResume() {
    super.onResume();
    //        getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);

    Database db = Database.getInstance(getActivity());

    if (BuildConfig.DEBUG)
        db.logState();//from w  w  w .ja v a2  s. c  o m
    // read todays offset
    todayOffset = db.getSteps(Util.getToday());

    SharedPreferences prefs = getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE);

    goal = prefs.getInt("goal", Fragment_Settings.DEFAULT_GOAL);
    since_boot = db.getCurrentSteps(); // do not use the value from the sharedPreferences
    int pauseDifference = since_boot - prefs.getInt("pauseCount", since_boot);

    // register a sensorlistener to live update the UI if a step is taken
    if (!prefs.contains("pauseCount")) {
        SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (sensor == null) {
            new AlertDialog.Builder(getActivity()).setTitle(R.string.no_sensor)
                    .setMessage(R.string.no_sensor_explain)
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(final DialogInterface dialogInterface) {
                            getActivity().finish();
                        }
                    }).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).create().show();
        } else {
            sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI, 0);
        }
    }

    since_boot -= pauseDifference;

    total_start = db.getTotalWithoutToday();
    total_days = db.getDays();

    db.close();

    SharedPreferences sharedpreferences = getActivity().getSharedPreferences(MyPREFERENCES,
            Context.MODE_PRIVATE);
    mBodyWeight = Float.parseFloat(sharedpreferences.getString(sp_weight, "0"));

    stepsDistanceChanged();

}

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

@SuppressLint("HandlerLeak")
@Override//from  w  w  w . j  a  va 2 s . 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();
}