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:com.coincide.alphafitness.ui.Fragment_Main.java

public void startStopService() {
    SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    if (getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE).contains("pauseCount")) { // currently paused -> now resumed
        sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI,
                0);//from  w w w.java2  s  .co  m

    } else {
        sm.unregisterListener(this);

    }

    sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER), SensorManager.SENSOR_DELAY_UI, 0);

    getActivity().startService(new Intent(getActivity(), SensorListener.class));
    //.putExtra("action", SensorListener.ACTION_PAUSE));
}

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

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_split_count:
        Dialog_Split.getDialog(getActivity(), total_start + Math.max(todayOffset + since_boot, 0)).show();
        return true;
    case R.id.action_pause:
        SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Drawable d;/*  w ww. j a  va 2  s. co  m*/
        if (getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE).contains("pauseCount")) { // currently paused -> now resumed
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
            item.setTitle(R.string.pause);
            d = getResources().getDrawable(R.drawable.ic_pause);
        } else {
            sm.unregisterListener(this);
            item.setTitle(R.string.resume);
            d = getResources().getDrawable(R.drawable.ic_resume);
        }
        d.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        item.setIcon(d);
        getActivity().startService(new Intent(getActivity(), SensorListener.class).putExtra("action",
                SensorListener.ACTION_PAUSE));
        return true;
    default:
        return ((Activity_Main) getActivity()).optionsItemSelected(item);
    }
}

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

@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {
    //        final View v = inflater.inflate(R.layout.fragment_overview, null);
    View v = null;// w  w w  . java  2s .  co  m

    v = inflater.inflate(R.layout.fragment_main, container, false);

    //        stepsView = (TextView) v.findViewById(R.id.steps);
    //        totalView = (TextView) v.findViewById(R.id.total);
    totalView = (TextView) v.findViewById(R.id.tv_distance);
    tv_avg = (TextView) v.findViewById(R.id.tv_avg);
    tv_max = (TextView) v.findViewById(R.id.tv_max);
    tv_min = (TextView) v.findViewById(R.id.tv_min);
    //        averageView = (TextView) v.findViewById(R.id.average);

    /*
            pg = (PieChart) v.findViewById(R.id.graph);
            
            // slice for the steps taken today
            sliceCurrent = new PieModel("", 0, Color.parseColor("#99CC00"));
            pg.addPieSlice(sliceCurrent);
            
            // slice for the "missing" steps until reaching the goal
            sliceGoal = new PieModel("", Fragment_Settings.DEFAULT_GOAL, Color.parseColor("#CC0000"));
            pg.addPieSlice(sliceGoal);
            
            pg.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(final View view) {
        showSteps = !showSteps;
        stepsDistanceChanged();
    }
            });
            
            pg.setDrawValueInPie(false);
            pg.setUsePieRotation(true);
            pg.startAnimation();
    */

    /*
    * MainActivity
    * */
    // Always cast your custom Toolbar here, and set it as the ActionBar.
    Toolbar tb = (Toolbar) v.findViewById(R.id.toolbar);
    ((AppCompatActivity) getActivity()).setSupportActionBar(tb);

    TextView tv_tb_center = (TextView) tb.findViewById(R.id.tv_tb_center);
    tv_tb_center.setText("ALPHA FITNESS");

    /*   ImageButton imgbtn_cart = (ImageButton) tb.findViewById(R.id.imgbtn_cart);
       imgbtn_cart.setVisibility(View.GONE);*/

    tb.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });

    // Get the ActionBar here to configure the way it behaves.
    final ActionBar ab = ((AppCompatActivity) getActivity()).getSupportActionBar();
    //ab.setHomeAsUpIndicator(R.drawable.ic_menu); // set a custom icon for the default home button
    ab.setDisplayShowHomeEnabled(false); // show or hide the default home button
    ab.setDisplayHomeAsUpEnabled(false);
    ab.setDisplayShowCustomEnabled(false); // enable overriding the default toolbar layout
    ab.setDisplayShowTitleEnabled(false); // disable the default title element here (for centered title)

    tv_duration = (TextView) v.findViewById(R.id.tv_duration);

    startButton = (Button) v.findViewById(R.id.btn_start);
    if (isButtonStartPressed) {
        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {
        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    startButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            onSWatchStart();
        }
    });
    iv_profile = (ImageView) v.findViewById(R.id.iv_profile);
    iv_profile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Database db = Database.getInstance(getActivity());
            tot_workouts = db.getTotWorkouts();
            tot_workTime = db.getWorkTime();
            Log.e("Tot Work time", tot_workTime + "");
            //                int seconds = (int) (tot_workTime / 1000) % 60;
            //                int minutes = (int) ((tot_workTime / (1000 * 60)) % 60);

            long millis = tot_workTime * 100; // obtained from StopWatch
            long hours = (millis / 1000) / 3600;
            long minutes = (millis / 1000) / 60;
            long seconds = (millis / 1000) % 60;

            db.close();

            Intent i = new Intent(getActivity(), ProfileActivity.class);
            i.putExtra("avg_distance", avg_distance + "");
            i.putExtra("all_distance", all_distance + "");
            i.putExtra("avg_time", tv_duration.getText().toString());
            i.putExtra("all_time", tv_duration.getText().toString());
            i.putExtra("avg_calories", avg_calories + "");
            i.putExtra("all_calories", all_calories + "");
            i.putExtra("tot_workouts", tot_workouts + "");
            i.putExtra("avg_workouts", tot_workouts + "");

            i.putExtra("tot_workTime", hours + " hrs " + minutes + " min " + seconds + " sec");

            startActivity(i);

        }
    });

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        // Initializing
        mMarkerPoints = new ArrayList<LatLng>();

        // Getting reference to SupportMapFragment of the activity_main
        //            SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
        MapFragment fm = (MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map);

        // Getting Map for the SupportMapFragment
        mGoogleMap = fm.getMap();

        // Enable MyLocation Button in the Map
        mGoogleMap.setMyLocationEnabled(true);

        // Getting LocationManager object from System Service LOCATION_SERVICE
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE);

        // Creating a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Getting the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Getting Current Location From GPS
        Location location;
        if (provider != null) {

            if (ActivityCompat.checkSelfPermission(getActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(getActivity(),
                            Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return null;
            }
            location = locationManager.getLastKnownLocation(provider);
            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        } else {
            location = new Location("");
            location.setLatitude(0.0d);//your coords of course
            location.setLongitude(0.0d);
        }

        if (location != null) {
            onLocationChanged(location);
        }

        // Setting onclick event listener for the map
        mGoogleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {

                // Already map contain destination location
                if (mMarkerPoints.size() > 1) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    mMarkerPoints.clear();
                    mGoogleMap.clear();
                    LatLng startPoint = new LatLng(mLatitude, mLongitude);
                    drawMarker(startPoint);
                }

                drawMarker(point);

                // Checks, whether start and end locations are captured
                if (mMarkerPoints.size() >= 2) {
                    LatLng origin = mMarkerPoints.get(0);
                    LatLng dest = mMarkerPoints.get(1);

                    // Getting URL to the Google Directions API
                    String url = getDirectionsUrl(origin, dest);

                    DownloadTask downloadTask = new DownloadTask();

                    // Start downloading json data from Google Directions API
                    downloadTask.execute(url);
                }
            }
        });
        fixedCentreoption = new MarkerOptions();

        mGoogleMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition position) {
                // TODO Auto-generated method stub
                // Get the center of the Map.

                mGoogleMap.clear();

                LatLng centerOfMap = mGoogleMap.getCameraPosition().target;

                // Update your Marker's position to the center of the Map.
                fixedCentreoption.position(centerOfMap);
                //                   mGoogleMap.addMarker(fixedCentreoption);
                //                   drawMarker(centerOfMap);
                LatLng origin = new LatLng(0.0d, 0.0d);
                ;
                if (mMarkerPoints.size() > 0) {
                    origin = mMarkerPoints.get(0);
                }
                //                  LatLng dest = mMarkerPoints.get(1);
                LatLng dest = centerOfMap;
                // Getting URL to the Google Directions API
                String url = getDirectionsUrl(origin, dest);

                DownloadTask downloadTask = new DownloadTask();

                // Start downloading json data from Google Directions API
                downloadTask.execute(url);

                GPSTracker gpsTracker = new GPSTracker(getActivity().getApplicationContext());
                //               String Addrs = gpsTracker.location();
                Addrs = gpsTracker.locationBasedOnLatlng(centerOfMap);
                //               Toast.makeText(getApplicationContext(), Addrs, Toast.LENGTH_LONG).show();

            }
        });
    }

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

    return v;
}

From source file:com.prod.intelligent7.engineautostart.ConnectDaemonService.java

private void registerAccelerometerListener() {
    final SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_FASTEST);
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

private void configureDeviceForCall() {
    needPlayEndSound = true;//from ww  w  . j a v a  2s .c om
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    am.setMode(AudioManager.MODE_IN_COMMUNICATION);
    am.setSpeakerphoneOn(false);
    am.requestAudioFocus(this, AudioManager.STREAM_VOICE_CALL, AudioManager.AUDIOFOCUS_GAIN);

    SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    try {
        if (proximity != null) {
            proximityWakelock = ((PowerManager) getSystemService(Context.POWER_SERVICE))
                    .newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, "telegram-voip-prx");
            sm.registerListener(this, proximity, SensorManager.SENSOR_DELAY_NORMAL);
        }
    } catch (Exception x) {
        FileLog.e("Error initializing proximity sensor", x);
    }
}

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

public void onSWatchStart() {
    if (isButtonStartPressed) {
        onSWatchStop();/*w  w w. java  2s . c o  m*/
        //            startStopService();

        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.unregisterListener(this);
        } catch (Exception e) {
            e.printStackTrace();
        }

    } else {

        //            startStopService();
        getActivity().startService(new Intent(getActivity(), SensorListener.class));

        try {
            SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
            sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER),
                    SensorManager.SENSOR_DELAY_UI, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        isButtonStartPressed = true;

        startButton.setBackgroundResource(R.drawable.btn_stop_states);
        startButton.setText(R.string.btn_stop);

        getActivity().startService(new Intent(getActivity(), BroadcastService.class));

        /*lapButton.setBackgroundResource(R.drawable.btn_lap_states);
        lapButton.setText(R.string.btn_lap);
        lapButton.setEnabled(true);*/

        //            setUpNotification();

        /*timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    currentTime += 1;
        //                            lapTime += 1;
                
                   *//*manager = (NotificationManager)
                             getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                              
                      // update notification text
                      builder.setContentText(TimeFormatUtil.toDisplayString(currentTime));
                      manager.notify(mId, builder.build());*//*
                                                                      
                                                              // update ui
                                                              tv_duration.setText(TimeFormatUtil.toDisplayString(currentTime));
                                                              }
                                                              });
                                                              }
                                                              }, 0, 100);*/
    }
}

From source file:com.ferdi2005.secondgram.voip.VoIPService.java

@Override
public void onDestroy() {
    FileLog.d("=============== VoIPService STOPPING ===============");
    stopForeground(true);//from   w  ww  . ja  v a  2 s  . c  o  m
    stopRinging();
    NotificationCenter.getInstance().removeObserver(this, NotificationCenter.appDidLogout);
    SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    Sensor proximity = sm.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    if (proximity != null) {
        sm.unregisterListener(this);
    }
    if (proximityWakelock != null && proximityWakelock.isHeld()) {
        proximityWakelock.release();
    }
    unregisterReceiver(receiver);
    if (timeoutRunnable != null) {
        AndroidUtilities.cancelRunOnUIThread(timeoutRunnable);
        timeoutRunnable = null;
    }
    super.onDestroy();
    sharedInstance = null;
    AndroidUtilities.runOnUIThread(new Runnable() {
        @Override
        public void run() {
            NotificationCenter.getInstance().postNotificationName(NotificationCenter.didEndedCall);
        }
    });
    if (controller != null && controllerStarted) {
        lastKnownDuration = controller.getCallDuration();
        updateStats();
        StatsController.getInstance().incrementTotalCallsTime(getStatsNetworkType(),
                (int) (lastKnownDuration / 1000) % 5);
        if (needSendDebugLog) {
            String debugLog = controller.getDebugLog();
            TLRPC.TL_phone_saveCallDebug req = new TLRPC.TL_phone_saveCallDebug();
            req.debug = new TLRPC.TL_dataJSON();
            req.debug.data = debugLog;
            req.peer = new TLRPC.TL_inputPhoneCall();
            req.peer.access_hash = call.access_hash;
            req.peer.id = call.id;
            ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
                @Override
                public void run(TLObject response, TLRPC.TL_error error) {
                    FileLog.d("Sent debug logs, response=" + response);
                }
            });
        }
        controller.release();
        controller = null;
    }
    cpuWakelock.release();
    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE);
    if (isBtHeadsetConnected && !playingSound)
        am.stopBluetoothSco();
    am.setMode(AudioManager.MODE_NORMAL);
    am.unregisterMediaButtonEventReceiver(new ComponentName(this, VoIPMediaButtonReceiver.class));
    if (haveAudioFocus)
        am.abandonAudioFocus(this);

    if (!playingSound)
        soundPool.release();

    ConnectionsManager.getInstance().setAppPaused(true, false);
}

From source file:com.thomasokken.free42.Free42Activity.java

public int shell_get_acceleration(DoubleHolder x, DoubleHolder y, DoubleHolder z) {
    if (!accel_inited) {
        accel_inited = true;/*w w  w. ja  v a  2s.  c  o  m*/
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor s = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (s == null)
            return 0;
        boolean success = sm.registerListener(new SensorEventListener() {
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // Don't care
            }

            public void onSensorChanged(SensorEvent event) {
                // Transform the measurements to conform to the iPhone
                // conventions. The conversion factor used here is the
                // 'standard gravity'.
                accel_x = event.values[0] / -9.80665;
                accel_y = event.values[1] / -9.80665;
                accel_z = event.values[2] / -9.80665;
            }
        }, s, SensorManager.SENSOR_DELAY_NORMAL);
        if (!success)
            return 0;
        accel_exists = true;
    }

    if (accel_exists) {
        x.value = accel_x;
        y.value = accel_y;
        z.value = accel_z;
        return 1;
    } else {
        return 0;
    }
}

From source file:com.thomasokken.free42.Free42Activity.java

public int shell_get_heading(DoubleHolder mag_heading, DoubleHolder true_heading, DoubleHolder acc_heading,
        DoubleHolder x, DoubleHolder y, DoubleHolder z) {
    if (!heading_inited) {
        heading_inited = true;//from w w  w  . j ava2 s. c  om
        SensorManager sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor s1 = sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
        Sensor s2 = sm.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
        if (s1 == null)
            return 0;
        SensorEventListener listener = new SensorEventListener() {
            public void onAccuracyChanged(Sensor sensor, int accuracy) {
                // Don't care
            }

            public void onSensorChanged(SensorEvent event) {
                // TODO: Verify this on a real phone, and
                // check if the orientation matches the iPhone.
                // There doesn't seem to be an API to obtain true
                // heading, so I should set true_heading to 0
                // and heading_acc to -1; the current code just
                // exists to let me investigate the components
                // returned by Orientation events.
                if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
                    heading_mag = event.values[0];
                    heading_true = event.values[1];
                    heading_acc = event.values[2];
                } else {
                    heading_x = event.values[0];
                    heading_y = event.values[1];
                    heading_z = event.values[2];
                }
            }
        };
        boolean success = sm.registerListener(listener, s1, SensorManager.SENSOR_DELAY_UI);
        if (!success)
            return 0;
        sm.registerListener(listener, s2, SensorManager.SENSOR_DELAY_UI);
        heading_exists = true;
    }

    if (heading_exists) {
        mag_heading.value = heading_mag;
        true_heading.value = heading_true;
        acc_heading.value = heading_acc;
        x.value = heading_x;
        y.value = heading_y;
        z.value = heading_z;
        return 1;
    } else {
        return 0;
    }
}

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

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

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);/*from w w  w. ja  v  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();
    }
}