Example usage for android.hardware Sensor TYPE_ACCELEROMETER

List of usage examples for android.hardware Sensor TYPE_ACCELEROMETER

Introduction

In this page you can find the example usage for android.hardware Sensor TYPE_ACCELEROMETER.

Prototype

int TYPE_ACCELEROMETER

To view the source code for android.hardware Sensor TYPE_ACCELEROMETER.

Click Source Link

Document

A constant describing an accelerometer sensor type.

Usage

From source file:com.aware.Aware_Preferences.java

/**
 * Accelerometer module settings UI//from   www  .  ja  va2 s  .co  m
 */
private void accelerometer() {

    final PreferenceScreen accel_pref = (PreferenceScreen) findPreference("accelerometer");
    Sensor temp = mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    if (temp != null) {
        accel_pref.setSummary(
                accel_pref.getSummary().toString().replace("*", " - Power: " + temp.getPower() + " mA"));
    } else {
        accel_pref.setSummary(accel_pref.getSummary().toString().replace("*", ""));
    }

    final CheckBoxPreference accelerometer = (CheckBoxPreference) findPreference(
            Aware_Preferences.STATUS_ACCELEROMETER);
    accelerometer.setChecked(
            Aware.getSetting(getApplicationContext(), Aware_Preferences.STATUS_ACCELEROMETER).equals("true"));
    accelerometer.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            if (mSensorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) == null) {
                showDialog(DIALOG_ERROR_MISSING_SENSOR);
                accelerometer.setChecked(false);
                Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_ACCELEROMETER, false);
                return false;
            }

            Aware.setSetting(getApplicationContext(), Aware_Preferences.STATUS_ACCELEROMETER,
                    accelerometer.isChecked());
            if (accelerometer.isChecked()) {
                framework.startAccelerometer();
            } else {
                framework.stopAccelerometer();
            }
            return true;
        }
    });

    final EditTextPreference frequency_accelerometer = (EditTextPreference) findPreference(
            Aware_Preferences.FREQUENCY_ACCELEROMETER);
    if (Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_ACCELEROMETER).length() > 0) {
        frequency_accelerometer
                .setSummary(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_ACCELEROMETER)
                        + " microseconds");
    }
    frequency_accelerometer
            .setText(Aware.getSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_ACCELEROMETER));
    frequency_accelerometer.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            Aware.setSetting(getApplicationContext(), Aware_Preferences.FREQUENCY_ACCELEROMETER,
                    (String) newValue);
            frequency_accelerometer.setSummary((String) newValue + " microseconds");
            framework.startAccelerometer();
            return true;
        }
    });

}

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

@Override
public void onSensorChanged(SensorEvent event) {
    synchronized (this) {
        // Checking which type of sensor called this listener
        // In this case it is the Accelerometer (the next is the Magnetomer)
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            accelerometerCurrentTime = System.currentTimeMillis();

            if (accelerometerCurrentTime
                    - lastAccelerometerReadTime > (1000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER
                            - 1000 / (Constants.PARAM_SAMPLERATE_ACCELEROMETER
                                    * Constants.PARAM_UPSAMPLERATE_ACCELEROMETER))) {
                lastAccelerometerReadTime = accelerometerCurrentTime;
                float xRaw = event.values[0];
                float yRaw = event.values[1];
                float zRaw = event.values[2];

                // Extracts unwanted gravity component from the
                // accelerometer signal.
                float alpha = Constants.PARAM_GRAVITY_FILTER_COEFFICIENT;
                runningGravityComponents[0] = runningGravityComponents[0] * alpha + (1 - alpha) * xRaw;
                runningGravityComponents[1] = runningGravityComponents[1] * alpha + (1 - alpha) * yRaw;
                runningGravityComponents[2] = runningGravityComponents[2] * alpha + (1 - alpha) * zRaw;

                float xAccel = xRaw - runningGravityComponents[0];
                float yAccel = yRaw - runningGravityComponents[1];
                float zAccel = zRaw - runningGravityComponents[2];

                double magnitudeSquare = xAccel * xAccel + yAccel * yAccel + zAccel * zAccel;
                double magnitude = Math.sqrt(magnitudeSquare);

                actigraphyQueue.add(magnitude);
                int secsToDisplay = Integer.parseInt(sharedPreferences.getString(Constants.PREF_GRAPH_SECONDS,
                        Constants.DEFAULT_GRAPH_RANGE));
                int numberExtraSamples = actigraphyQueue.size()
                        - (secsToDisplay * Constants.PARAM_SAMPLERATE_ACCELEROMETER);
                if (numberExtraSamples > 0) {
                    for (int i = 0; i < numberExtraSamples; i++) {
                        actigraphyQueue.remove();
                    }//  w  w  w  . j  ava2s . c o m
                }

                // Saves accelerometer data, necessary for the orientation
                // computation
                System.arraycopy(event.values, 0, latestAccelerometerEventValues, 0, 3);
                pushBackAccelerometerValues(xRaw, yRaw, zRaw);

                if (accelerometerCurrentTime
                        - lastAccelerometerRecordedTime > Constants.PARAM_ACCELEROMETER_RECORDING_PERIOD
                                + 1000 / Constants.PARAM_SAMPLERATE_ACCELEROMETER) {
                    if (startRecordingFlag) {
                        writeActigraphyLogVariance();
                    }
                    gravitySum = gravitySquaredSum = 0;
                    varianceCounter = 0;
                    lastAccelerometerRecordedTime = accelerometerCurrentTime;
                }
                if (startRecordingFlag) {
                    writeRawActigraphy();
                }
            }
        }

        // Checking if the Magnetomer called this listener
        if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {

            // Copying magnetometer measures.
            System.arraycopy(event.values, 0, mGeoMags, 0, 3);

            if (SensorManager.getRotationMatrix(mRotationM, null, latestAccelerometerEventValues, mGeoMags)) {
                SensorManager.getOrientation(mRotationM, mOrientation);

                // Finding current orientation requires both Accelerometer
                // (using the previous measure) and Magnetometer data.
                // Converting radians to degrees (yaw, pitch, roll)
                mOrientation[0] = mOrientation[0] * Constants.CONST_DEGREES_PER_RADIAN;
                mOrientation[1] = mOrientation[1] * Constants.CONST_DEGREES_PER_RADIAN;
                mOrientation[2] = mOrientation[2] * Constants.CONST_DEGREES_PER_RADIAN;

                // The values (1,2,3,4) attributed for
                // supine/prone/left/right match the
                // ones attributed in VISI text files.
                int positionValue = 0;
                // Supine (4).
                if (-45 < mOrientation[1] && mOrientation[1] < 45 && -45 < mOrientation[2]
                        && mOrientation[2] < 45) {
                    positionValue = Constants.CODE_POSITION_SUPINE;
                    position = Position.Supine;
                }

                // Prone (1).
                if ((((-180 < mOrientation[2] && mOrientation[2] < -135)
                        || (135 < mOrientation[2] && mOrientation[2] < 180)) && -45 < mOrientation[1]
                        && mOrientation[1] < 45)) {
                    positionValue = Constants.CODE_POSITION_PRONE;
                    position = Position.Prone;
                }

                // Right (2).
                if (-90 < mOrientation[2] && mOrientation[2] < -45) {
                    positionValue = Constants.CODE_POSITION_RIGHT;
                    position = Position.Right;
                }

                // Left (3).
                if (45 < mOrientation[2] && mOrientation[2] < 90) {
                    positionValue = Constants.CODE_POSITION_LEFT;
                    position = Position.Left;
                }

                // Sitting up (5).
                if ((((-135 < mOrientation[1] && mOrientation[1] < -45)
                        || (45 < mOrientation[1] && mOrientation[1] < 135)) && -45 < mOrientation[2]
                        && mOrientation[2] < 45)) {
                    positionValue = Constants.CODE_POSITION_SITTING;
                    position = Position.Sitting;
                }

                if ((oldPositionValue != positionValue) && (positionValue != 0) && startRecordingFlag) {
                    updatePositionChangeTime(oldPositionValue);
                    oldPositionValue = positionValue;
                    try {
                        // Write raw body position data
                        BufferedWriter orientationBufferedWriter = new BufferedWriter(
                                new FileWriter(orientationFile, true));
                        orientationBufferedWriter.append(String.valueOf(System.currentTimeMillis()) + ",");
                        orientationBufferedWriter.append(String.valueOf(positionValue) + "\n");
                        orientationBufferedWriter.flush();
                        orientationBufferedWriter.close();
                    } catch (IOException e) {
                        Log.e(Constants.CODE_APP_TAG, "Error writing orientation data to file", e);
                    }
                }
            }
        }
    }
}

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

/**
 * Continue the paused game./*from  w w w  . j a v  a 2  s  . c  om*/
 * 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.vonglasow.michael.satstat.MainActivity.java

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

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            Context c = getApplicationContext();
            File dumpDir = c.getExternalFilesDir(null);
            File dumpFile = new File(dumpDir, "satstat-" + System.currentTimeMillis() + ".log");
            PrintStream s;/*  www  . j  a v a  2  s  .c o m*/
            try {
                InputStream buildInStream = getResources().openRawResource(R.raw.build);
                s = new PrintStream(dumpFile);
                s.append("SatStat build: ");

                int i;
                try {
                    i = buildInStream.read();
                    while (i != -1) {
                        s.write(i);
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);

    final ActionBar actionBar = getActionBar();

    setContentView(R.layout.activity_main);

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Find out default screen orientation
    Configuration config = getResources().getConfiguration();
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    int rot = wm.getDefaultDisplay().getRotation();
    isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE
            && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180)
            || config.orientation == Configuration.ORIENTATION_PORTRAIT
                    && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270));
    Log.d("MainActivity", "isWideScreen=" + Boolean.toString(isWideScreen));

    // compact action bar
    int dpX = (int) (this.getResources().getDisplayMetrics().widthPixels
            / this.getResources().getDisplayMetrics().density);
    /*
     * This is a crude way to ensure a one-line action bar with tabs
     * (not a drop-down list) and home (incon) and title only if there
     * is space, depending on screen width:
     * divide screen in units of 64 dp
     * each tab requires 1 unit, home and menu require slightly less,
     * title takes up approx. 2.5 units in portrait,
     * home and title are about 2 units wide in landscape
     */
    if (dpX < 192) {
        // just enough space for drop-down list and menu
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if (dpX < 320) {
        // not enough space for four tabs, but home will fit next to list
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if (dpX < 384) {
        // just enough space for four tabs
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
    } else if ((dpX < 448) || ((config.orientation == Configuration.ORIENTATION_PORTRAIT) && (dpX < 544))) {
        // space for four tabs and home, but not title
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(false);
    } else {
        // ample space for home, title and all four tabs
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
    }
    setEmbeddedTabs(actionBar, true);

    providerLocations = new HashMap<String, Location>();

    mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(LOCATION_PROVIDER_STYLES));

    providerStyles = new HashMap<String, String>();
    providerAppliedStyles = new HashMap<String, String>();

    providerInvalidationHandler = new Handler();
    providerInvalidators = new HashMap<String, Runnable>();

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(this);

    // Add tabs, specifying the tab's text and TabListener
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                //.setText(mSectionsPagerAdapter.getPageTitle(i))
                .setIcon(mSectionsPagerAdapter.getPageIcon(i)).setTabListener(this));
    }

    // This is needed by the mapsforge library.
    AndroidGraphicFactory.createInstance(this.getApplication());

    // Get system services for event delivery
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mAccSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGyroSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mMagSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mProximitySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mPressureSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mHumiditySensor = mSensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    mTempSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);

    mAccSensorRes = getSensorDecimals(mAccSensor, mAccSensorRes);
    mGyroSensorRes = getSensorDecimals(mGyroSensor, mGyroSensorRes);
    mMagSensorRes = getSensorDecimals(mMagSensor, mMagSensorRes);
    mLightSensorRes = getSensorDecimals(mLightSensor, mLightSensorRes);
    mProximitySensorRes = getSensorDecimals(mProximitySensor, mProximitySensorRes);
    mPressureSensorRes = getSensorDecimals(mPressureSensor, mPressureSensorRes);
    mHumiditySensorRes = getSensorDecimals(mHumiditySensor, mHumiditySensorRes);
    mTempSensorRes = getSensorDecimals(mTempSensor, mTempSensorRes);

    networkTimehandler = new Handler();
    networkTimeRunnable = new Runnable() {
        @Override
        public void run() {
            int newNetworkType = mTelephonyManager.getNetworkType();
            if (getNetworkGeneration(newNetworkType) != mLastNetworkGen)
                onNetworkTypeChanged(newNetworkType);
            else
                networkTimehandler.postDelayed(this, NETWORK_REFRESH_DELAY);
        }
    };

    wifiTimehandler = new Handler();
    wifiTimeRunnable = new Runnable() {

        @Override
        public void run() {
            mWifiManager.startScan();
            wifiTimehandler.postDelayed(this, WIFI_REFRESH_DELAY);
        }
    };

    updateLocationProviderStyles();
}

From source file:github.popeen.dsub.activity.SubsonicActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    checkShake = true;//from  w ww. j av  a  2s .  c om
    if (checkShake) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {

            boolean reset = false;
            double sensitivity = 3.0;
            if (event.values[0] > x + sensitivity || event.values[0] < x - sensitivity) {
                reset = true;
            }
            if (event.values[1] > y + sensitivity || event.values[1] < y - sensitivity) {
                reset = true;
            }
            if (event.values[2] > z + sensitivity || event.values[2] < z - sensitivity) {
                reset = true;
            }

            if (reset) {
                DownloadService downloadService = getDownloadService();
                if (downloadService != null && downloadService.getSleepTimer()) {
                    downloadService.stopSleepTimer();
                    downloadService.startSleepTimer();
                }
            }

            x = event.values[0];
            y = event.values[1];
            z = event.values[2];

        }
    }
}

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

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

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

    setContentView(R.layout.activity_main);
    setTitle(R.string.app_name);/* ww w  .ja va 2  s .co  m*/

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

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

    sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Update layout
    updateLayout();

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

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

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

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

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

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

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

            popup.show();
        }
    });

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                updateLayout();

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

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

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

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

From source file:jmri.enginedriver.throttle.java

private void setupSensor() {
    if (!prefAccelerometerShake.equals(ACCELERATOROMETER_SHAKE_NONE)) {
        // ShakeDetector initialization
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        if (accelerometer != null) {
            shakeDetector = new shakeDetector(getApplicationContext());
            shakeDetector.setOnShakeListener(new shakeDetector.OnShakeListener() {

                @Override//from  w w  w .j av a  2 s.  c  o  m
                public void onShake(int count) {

                    switch (prefAccelerometerShake) {
                    case ACCELERATOROMETER_SHAKE_WEB_VIEW:
                        if ((webViewLocation.equals(WEB_VIEW_LOCATION_NONE))
                                && (keepWebViewLocation.equals(WEB_VIEW_LOCATION_NONE))) {
                            GamepadFeedbackSound(true);
                            Toast.makeText(getApplicationContext(), getApplicationContext().getResources()
                                    .getString(R.string.toastShakeWebViewUnavailable), Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            GamepadFeedbackSound(false);
                            showHideWebView(getApplicationContext().getResources()
                                    .getString(R.string.toastShakeWebViewHidden));
                        }
                        break;
                    case ACCELERATOROMETER_SHAKE_NEXT_V:
                        GamepadFeedbackSound(false);
                        setNextActiveThrottle();
                        speakWords(TTS_MSG_VOLUME_THROTTLE, whichVolume);
                        break;
                    case ACCELERATOROMETER_SHAKE_LOCK_DIM_SCREEN:
                        GamepadFeedbackSound(false);
                        setRestoreScreenLockDim(getApplicationContext().getResources()
                                .getString(R.string.toastShakeScreenLocked));
                        break;
                    case ACCELERATOROMETER_SHAKE_DIM_SCREEN:
                        GamepadFeedbackSound(false);
                        setRestoreScreenDim(getApplicationContext().getResources()
                                .getString(R.string.toastShakeScreenDimmed));
                        break;
                    case ACCELERATOROMETER_SHAKE_ALL_STOP:
                        GamepadFeedbackSound(false);
                        speedUpdateAndNotify(0); // update all three throttles
                    }
                }
            });
            accelerometerCurrent = true;
        } else {
            Toast.makeText(getApplicationContext(),
                    getApplicationContext().getResources().getString(R.string.toastAccelerometerNotFound),
                    Toast.LENGTH_LONG).show();
        }

    }
}

From source file:com.davidmascharka.lips.TrackerActivity.java

@Override
public void onSensorChanged(SensorEvent event) {
    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        accelerometerX = event.values[0];
        accelerometerY = event.values[1];
        accelerometerZ = event.values[2];
        break;/*  www.j  av a2 s.c om*/
    case Sensor.TYPE_MAGNETIC_FIELD:
        magneticX = event.values[0];
        magneticY = event.values[1];
        magneticZ = event.values[2];
        break;
    case Sensor.TYPE_LIGHT:
        light = event.values[0];
        break;
    case Sensor.TYPE_ROTATION_VECTOR:
        rotationX = event.values[0];
        rotationY = event.values[1];
        rotationZ = event.values[2];
        break;
    default:
        break;
    }

    SensorManager.getRotationMatrix(rotation, inclination,
            new float[] { accelerometerX, accelerometerY, accelerometerZ },
            new float[] { magneticX, magneticY, magneticZ });
    orientation = SensorManager.getOrientation(rotation, orientation);
}

From source file:com.vonglasow.michael.satstat.MainActivity.java

/**
 * Called when a sensor's reading changes. Updates sensor display.
 */// ww  w. j a v  a  2 s.c  o m
public void onSensorChanged(SensorEvent event) {
    //to enforce sensor rate
    boolean isRateElapsed = false;

    switch (event.sensor.getType()) {
    case Sensor.TYPE_ACCELEROMETER:
        isRateElapsed = (event.timestamp / 1000) - mAccLast >= iSensorRate;
        // if Z acceleration is greater than X/Y combined, lock rotation, else unlock
        if (Math.pow(event.values[2], 2) > Math.pow(event.values[0], 2) + Math.pow(event.values[1], 2)) {
            // workaround (SCREEN_ORIENTATION_LOCK is unsupported on API < 18)
            if (isWideScreen)
                setRequestedOrientation(
                        OR_FROM_ROT_WIDE[this.getWindowManager().getDefaultDisplay().getRotation()]);
            else
                setRequestedOrientation(
                        OR_FROM_ROT_TALL[this.getWindowManager().getDefaultDisplay().getRotation()]);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        }
        break;
    case Sensor.TYPE_ORIENTATION:
        isRateElapsed = (event.timestamp / 1000) - mOrLast >= iSensorRate;
        break;
    case Sensor.TYPE_GYROSCOPE:
        isRateElapsed = (event.timestamp / 1000) - mGyroLast >= iSensorRate;
        break;
    case Sensor.TYPE_MAGNETIC_FIELD:
        isRateElapsed = (event.timestamp / 1000) - mMagLast >= iSensorRate;
        break;
    case Sensor.TYPE_LIGHT:
        isRateElapsed = (event.timestamp / 1000) - mLightLast >= iSensorRate;
        break;
    case Sensor.TYPE_PROXIMITY:
        isRateElapsed = (event.timestamp / 1000) - mProximityLast >= iSensorRate;
        break;
    case Sensor.TYPE_PRESSURE:
        isRateElapsed = (event.timestamp / 1000) - mPressureLast >= iSensorRate;
        break;
    case Sensor.TYPE_RELATIVE_HUMIDITY:
        isRateElapsed = (event.timestamp / 1000) - mHumidityLast >= iSensorRate;
        break;
    case Sensor.TYPE_AMBIENT_TEMPERATURE:
        isRateElapsed = (event.timestamp / 1000) - mTempLast >= iSensorRate;
        break;
    }

    if (isSensorViewReady && isRateElapsed) {
        switch (event.sensor.getType()) {
        case Sensor.TYPE_ACCELEROMETER:
            mAccLast = event.timestamp / 1000;
            accX.setText(String.format("%." + mAccSensorRes + "f", event.values[0]));
            accY.setText(String.format("%." + mAccSensorRes + "f", event.values[1]));
            accZ.setText(String.format("%." + mAccSensorRes + "f", event.values[2]));
            accTotal.setText(String.format("%." + mAccSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2)
                    + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
            accStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_ORIENTATION:
            mOrLast = event.timestamp / 1000;
            orAzimuth.setText(String.format("%.0f%s", event.values[0], getString(R.string.unit_degree)));
            orAziText.setText(formatOrientation(event.values[0]));
            orPitch.setText(String.format("%.0f%s", event.values[1], getString(R.string.unit_degree)));
            orRoll.setText(String.format("%.0f%s", event.values[2], getString(R.string.unit_degree)));
            orStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_GYROSCOPE:
            mGyroLast = event.timestamp / 1000;
            rotX.setText(String.format("%." + mGyroSensorRes + "f", event.values[0]));
            rotY.setText(String.format("%." + mGyroSensorRes + "f", event.values[1]));
            rotZ.setText(String.format("%." + mGyroSensorRes + "f", event.values[2]));
            rotTotal.setText(String.format("%." + mGyroSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2)
                    + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
            rotStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_MAGNETIC_FIELD:
            mMagLast = event.timestamp / 1000;
            magX.setText(String.format("%." + mMagSensorRes + "f", event.values[0]));
            magY.setText(String.format("%." + mMagSensorRes + "f", event.values[1]));
            magZ.setText(String.format("%." + mMagSensorRes + "f", event.values[2]));
            magTotal.setText(String.format("%." + mMagSensorRes + "f", Math.sqrt(Math.pow(event.values[0], 2)
                    + Math.pow(event.values[1], 2) + Math.pow(event.values[2], 2))));
            magStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_LIGHT:
            mLightLast = event.timestamp / 1000;
            light.setText(String.format("%." + mLightSensorRes + "f", event.values[0]));
            lightStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_PROXIMITY:
            mProximityLast = event.timestamp / 1000;
            proximity.setText(String.format("%." + mProximitySensorRes + "f", event.values[0]));
            proximityStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_PRESSURE:
            mPressureLast = event.timestamp / 1000;
            metPressure.setText(String.format("%." + mPressureSensorRes + "f", event.values[0]));
            pressureStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_RELATIVE_HUMIDITY:
            mHumidityLast = event.timestamp / 1000;
            metHumid.setText(String.format("%." + mHumiditySensorRes + "f", event.values[0]));
            humidStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        case Sensor.TYPE_AMBIENT_TEMPERATURE:
            mTempLast = event.timestamp / 1000;
            metTemp.setText(String.format("%." + mTempSensorRes + "f", event.values[0]));
            tempStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy)));
            break;
        }
    }
    if (isGpsViewReady && isRateElapsed) {
        switch (event.sensor.getType()) {
        case Sensor.TYPE_ORIENTATION:
            gpsStatusView.setYaw(event.values[0]);
            break;
        }
    }
}

From source file:com.ichi2.anki2.Reviewer.java

private void initLayout(Integer layout) {
    setContentView(layout);//from   w ww .  j a va 2s .  c o  m

    mMainLayout = findViewById(R.id.main_layout);
    Themes.setContentStyle(mMainLayout, Themes.CALLER_REVIEWER);

    mCardContainer = (FrameLayout) findViewById(R.id.flashcard_frame);
    setInAnimation(false);

    findViewById(R.id.top_bar).setOnClickListener(mCardStatisticsListener);

    mCardFrame = (FrameLayout) findViewById(R.id.flashcard);
    mTouchLayer = (FrameLayout) findViewById(R.id.touch_layer);
    mTouchLayer.setOnTouchListener(mGestureListener);
    if (mPrefTextSelection && mLongClickWorkaround) {
        mTouchLayer.setOnLongClickListener(mLongClickListener);
    }
    if (mPrefTextSelection) {
        mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    }
    mCardFrame.removeAllViews();
    if (!mChangeBorderStyle) {
        ((View) findViewById(R.id.flashcard_border)).setVisibility(View.VISIBLE);
    }
    // hunt for input issue 720, like android issue 3341
    if (AnkiDroidApp.SDK_VERSION <= 7 && (mCard != null)) {
        mCard.setFocusableInTouchMode(true);
    }

    // Initialize swipe
    gestureDetector = new GestureDetector(new MyGestureDetector());

    mProgressBar = (ProgressBar) findViewById(R.id.flashcard_progressbar);

    // initialise shake detection
    if (mShakeEnabled) {
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mSensorManager.registerListener(mSensorListener,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;
    }

    Resources res = getResources();

    mEase1 = (Button) findViewById(R.id.ease1);
    mEase1.setTextColor(res.getColor(R.color.next_time_failed_color));
    mEase1Layout = (LinearLayout) findViewById(R.id.flashcard_layout_ease1);
    mEase1Layout.setOnClickListener(mSelectEaseHandler);

    mEase2 = (Button) findViewById(R.id.ease2);
    mEase2.setTextColor(res.getColor(R.color.next_time_usual_color));
    mEase2Layout = (LinearLayout) findViewById(R.id.flashcard_layout_ease2);
    mEase2Layout.setOnClickListener(mSelectEaseHandler);

    mEase3 = (Button) findViewById(R.id.ease3);
    mEase3Layout = (LinearLayout) findViewById(R.id.flashcard_layout_ease3);
    mEase3Layout.setOnClickListener(mSelectEaseHandler);

    mEase4 = (Button) findViewById(R.id.ease4);
    mEase4Layout = (LinearLayout) findViewById(R.id.flashcard_layout_ease4);
    mEase4Layout.setOnClickListener(mSelectEaseHandler);

    mNext1 = (TextView) findViewById(R.id.nextTime1);
    mNext2 = (TextView) findViewById(R.id.nextTime2);
    mNext3 = (TextView) findViewById(R.id.nextTime3);
    mNext4 = (TextView) findViewById(R.id.nextTime4);

    mNext1.setTextColor(res.getColor(R.color.next_time_failed_color));
    mNext2.setTextColor(res.getColor(R.color.next_time_usual_color));

    if (!mshowNextReviewTime) {
        ((TextView) findViewById(R.id.nextTimeflip)).setVisibility(View.GONE);
        mNext1.setVisibility(View.GONE);
        mNext2.setVisibility(View.GONE);
        mNext3.setVisibility(View.GONE);
        mNext4.setVisibility(View.GONE);
    }

    mFlipCard = (Button) findViewById(R.id.flip_card);
    mFlipCardLayout = (LinearLayout) findViewById(R.id.flashcard_layout_flip);
    mFlipCardLayout.setOnClickListener(mFlipCardListener);

    mTextBarRed = (TextView) findViewById(R.id.red_number);
    mTextBarBlack = (TextView) findViewById(R.id.black_number);
    mTextBarBlue = (TextView) findViewById(R.id.blue_number);

    if (mShowProgressBars) {
        mSessionProgressTotalBar = (View) findViewById(R.id.daily_bar);
        mSessionProgressBar = (View) findViewById(R.id.session_progress);
        mProgressBars = (LinearLayout) findViewById(R.id.progress_bars);
    }

    mCardTimer = (Chronometer) findViewById(R.id.card_time);
    if (mShowProgressBars && mProgressBars.getVisibility() != View.VISIBLE) {
        switchVisibility(mProgressBars, View.VISIBLE);
    }

    mChosenAnswer = (TextView) findViewById(R.id.choosen_answer);

    if (mPrefWhiteboard) {
        mWhiteboard = new Whiteboard(this, mInvertedColors, mBlackWhiteboard);
        FrameLayout.LayoutParams lp2 = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT);
        mWhiteboard.setLayoutParams(lp2);
        FrameLayout fl = (FrameLayout) findViewById(R.id.whiteboard);
        fl.addView(mWhiteboard);

        mWhiteboard.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (mShowWhiteboard) {
                    return false;
                }
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        });
    }
    mAnswerField = (EditText) findViewById(R.id.answer_field);

    mNextTimeTextColor = getResources().getColor(R.color.next_time_usual_color);
    mNextTimeTextRecomColor = getResources().getColor(R.color.next_time_recommended_color);
    mForegroundColor = getResources().getColor(R.color.next_time_usual_color);
    if (mInvertedColors) {
        invertColors(true);
    }

    mLookUpIcon = findViewById(R.id.lookup_button);
    mLookUpIcon.setVisibility(View.GONE);
    mLookUpIcon.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (clipboardHasText()) {
                lookUp();
            }
        }

    });
    initControls();
}