List of usage examples for android.hardware Sensor TYPE_LIGHT
int TYPE_LIGHT
To view the source code for android.hardware Sensor TYPE_LIGHT.
Click Source Link
From source file:it.unime.mobility4ckan.MySensor.java
void registerLightSensor() { lightSensorListener = new SensorEventListener() { @Override/* w w w .j a v a 2 s. co m*/ public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { currentLight = event.values[0]; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }; sensorManager.registerListener(lightSensorListener, lightSensor, SensorManager.SENSOR_DELAY_FASTEST); }
From source file:ch.bfh.sensordataprocessor.sensor.SensorDisplayFragment.java
/** * @see android.hardware.SensorEventListener#onSensorChanged(android.hardware.SensorEvent) *//*w w w . ja v a 2s . c om*/ @Override public void onSensorChanged(SensorEvent event) { onAccuracyChanged(event.sensor, event.accuracy); timestampLabel.setVisibility(View.VISIBLE); timestamp.setVisibility(View.VISIBLE); timestamp.setText(String.valueOf(event.timestamp)); timestampUnits.setVisibility(View.VISIBLE); switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: showEventData("Acceleration - gravity on axis", ACCELERATION_UNITS, event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_MAGNETIC_FIELD: showEventData("Abient Magnetic Field", "uT", event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_GYROSCOPE: showEventData("Angular speed around axis", "radians/sec", event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_LIGHT: showEventData("Ambient light", "lux", event.values[0]); break; case Sensor.TYPE_PRESSURE: showEventData("Atmospheric pressure", "hPa", event.values[0]); break; case Sensor.TYPE_PROXIMITY: showEventData("Distance", "cm", event.values[0]); break; case Sensor.TYPE_GRAVITY: showEventData("Gravity", ACCELERATION_UNITS, event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_LINEAR_ACCELERATION: showEventData("Acceleration (not including gravity)", ACCELERATION_UNITS, event.values[0], event.values[1], event.values[2]); break; case Sensor.TYPE_ROTATION_VECTOR: showEventData("Rotation Vector", null, event.values[0], event.values[1], event.values[2]); xAxisLabel.setText("x*sin(" + THETA + "/2)"); yAxisLabel.setText("y*sin(" + THETA + "/2)"); zAxisLabel.setText("z*sin(" + THETA + "/2)"); if (event.values.length == 4) { cosLabel.setVisibility(View.VISIBLE); cos.setVisibility(View.VISIBLE); cos.setText(String.valueOf(event.values[3])); } break; case Sensor.TYPE_ORIENTATION: showEventData("Angle", "Degrees", event.values[0], event.values[1], event.values[2]); xAxisLabel.setText(R.string.azimuthLabel); yAxisLabel.setText(R.string.pitchLabel); zAxisLabel.setText(R.string.rollLabel); break; case Sensor.TYPE_RELATIVE_HUMIDITY: showEventData("Relatice ambient air humidity", "%", event.values[0]); break; case Sensor.TYPE_AMBIENT_TEMPERATURE: showEventData("Ambien temperature", "degree Celcius", event.values[0]); break; } }
From source file:devbox.com.br.minercompanion.ProfileActivity.java
@Override public void onSensorChanged(SensorEvent event) { synchronized (this) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: float[] sensor1 = event.values; sensors.acelerometer = sensor1; //acelerText.setText("x: " + sensor1[0] + " y: " + sensor1[1] + " z: " + sensor1[2]); break; case Sensor.TYPE_ORIENTATION: float[] sensor2 = event.values; sensors.orientation = sensor2; //gyroText.setText("x: " + sensor2[0] + " y: " + sensor2[1] + " z: " + sensor2[2]); break; case Sensor.TYPE_GYROSCOPE: float[] sensor3 = event.values; sensors.gyroscope = sensor3; //orienText.setText("x: " + sensor3[0] + " y: " + sensor3[1] + " z: " + sensor3[2]); break; case Sensor.TYPE_LIGHT: sensors.luminosity = event.values[0]; //ligthText.setText("Luminosidade: " + event.values[0]); break; }/*w w w .j a va 2s . com*/ } }
From source file:de.tudarmstadt.dvs.myhealthassistant.myhealthhub.services.InternalSensorService.java
@Override public void onSensorChanged(SensorEvent event) { if (pref == null) pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); int mSensorType = event.sensor.getType(); if (mSensorType == Sensor.TYPE_ACCELEROMETER) { int x = Math.round(event.values[0]); int y = Math.round(event.values[1]); int z = Math.round(event.values[2]); // using ACCELEROMETER_KNEE only as a demonstration, // in practice new event can be created AccDeviceSensorEvent accEvt = new AccDeviceSensorEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.ACCELEROMETER_ON_DEVICE, getTimestamp(), x, y, z, x, y, z); sendToChannel(accEvt, AbstractChannel.RECEIVER); // for external // apps//from www.j a va2 s . com // subscription gotAccEvent(getTimestamp(), Sensor.TYPE_ACCELEROMETER, x, y, z); // for // on device // graphViews // using } else if (mSensorType == Sensor.TYPE_LIGHT) { float x = event.values[0]; // using ambientLightEvent only as a demonstration, // in practice new event can be created AmbientLightEvent lightEvnt = new AmbientLightEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.AMBIENT_LIGHT, getTimestamp(), "location", "object", x, AmbientLightEvent.UNIT_LUX); sendToChannel(lightEvnt, AbstractChannel.RECEIVER); gotLightEvent(getTimestamp(), Sensor.TYPE_LIGHT, x); } else if (mSensorType == Sensor.TYPE_PRESSURE) { float x = event.values[0]; AmbientPressureEvent temEvnt = new AmbientPressureEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.AMBIENT_PRESSURE, getTimestamp(), "location", "object", x, AmbientPressureEvent.UNIT_HPA); sendToChannel(temEvnt, AbstractChannel.RECEIVER); gotLightEvent(getTimestamp(), Sensor.TYPE_PRESSURE, x); } else if (mSensorType == Sensor.TYPE_PROXIMITY) { float x = event.values[0]; ProximityEvent evnt = new ProximityEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.PROXIMITY, getTimestamp(), "location", "object", x, ""); sendToChannel(evnt, AbstractChannel.RECEIVER); gotLightEvent(getTimestamp(), Sensor.TYPE_PROXIMITY, x); } else if (mSensorType == Sensor.TYPE_AMBIENT_TEMPERATURE) { float x = event.values[0]; TemperatureEvent evnt = new TemperatureEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.ROOM_TEMPERATURE, getTimestamp(), "location", "object", x, TemperatureEvent.UNIT_CELSIUS); sendToChannel(evnt, AbstractChannel.RECEIVER); gotLightEvent(getTimestamp(), Sensor.TYPE_AMBIENT_TEMPERATURE, x); } else if (mSensorType == Sensor.TYPE_RELATIVE_HUMIDITY) { float x = event.values[0]; HumidityEvent evnt = new HumidityEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.HUMIDITY, getTimestamp(), "location", "object", x); sendToChannel(evnt, AbstractChannel.RECEIVER); gotLightEvent(getTimestamp(), Sensor.TYPE_RELATIVE_HUMIDITY, x); } else if (mSensorType == Sensor.TYPE_GYROSCOPE) { int x = Math.round(event.values[0]); int y = Math.round(event.values[1]); int z = Math.round(event.values[2]); GyroscopeSensorEvent gSEvnt = new GyroscopeSensorEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.GYROSCOPE, getTimestamp(), x, y, z, x, y, z); sendToChannel(gSEvnt, AbstractChannel.RECEIVER); gotAccEvent(getTimestamp(), Sensor.TYPE_GYROSCOPE, x, y, z); } else if (mSensorType == Sensor.TYPE_MAGNETIC_FIELD) { int x = Math.round(event.values[0]); int y = Math.round(event.values[1]); int z = Math.round(event.values[2]); MagneticSensorEvent gSEvnt = new MagneticSensorEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.MAGNETIC_FIELD, getTimestamp(), x, y, z, x, y, z); sendToChannel(gSEvnt, AbstractChannel.RECEIVER); gotAccEvent(getTimestamp(), Sensor.TYPE_MAGNETIC_FIELD, x, y, z); } else if (mSensorType == Sensor.TYPE_LINEAR_ACCELERATION) { int x = Math.round(event.values[0]); int y = Math.round(event.values[1]); int z = Math.round(event.values[2]); // using ACCELEROMETER_KNEE only as a demonstration, // in practice new event can be created AccDeviceSensorEvent accEvt = new AccDeviceSensorEvent("eventID", getTimestamp(), "producerID", SensorReadingEvent.ACCELEROMETER_ON_DEVICE, getTimestamp(), x, y, z, x, y, z); sendToChannel(accEvt, AbstractChannel.RECEIVER); gotAccEvent(getTimestamp(), Sensor.TYPE_LINEAR_ACCELERATION, x, y, z); } }
From source file:com.vonglasow.michael.satstat.SensorSectionFragment.java
/** * Called by {@link MainActivity} when a sensor's reading changes. Updates sensor display. *//*from ww w . j av a2 s. co m*/ public void onSensorChanged(SensorEvent event) { switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: 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: orAzimuth.setText(String.format("%.0f%s", event.values[0], getString(R.string.unit_degree))); orAziText.setText(MainActivity.formatOrientation(this.getContext(), 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: 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: 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: light.setText(String.format("%." + mLightSensorRes + "f", event.values[0])); lightStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_PROXIMITY: proximity.setText(String.format("%." + mProximitySensorRes + "f", event.values[0])); proximityStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_PRESSURE: metPressure.setText(String.format("%." + mPressureSensorRes + "f", event.values[0])); pressureStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_RELATIVE_HUMIDITY: metHumid.setText(String.format("%." + mHumiditySensorRes + "f", event.values[0])); humidStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; case Sensor.TYPE_AMBIENT_TEMPERATURE: metTemp.setText(String.format("%." + mTempSensorRes + "f", event.values[0])); tempStatus.setTextColor(getResources().getColor(accuracyToColor(event.accuracy))); break; } }
From source file:edu.uwp.alga.calculator.CalculatorFragment.java
@Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_LIGHT) { lux = event.values[0];// w w w . j a v a 2 s.com LuxText.setHint(String.valueOf(lux) + " lux"); } }
From source file:it.unime.mobility4ckan.MainActivity.java
void sendTask(final boolean shouldUpdateCountdown) { if (!isDeviceCurrentSensorsRegistered && !isRegistering) { new RegisterDevice(this).execute(datasetName); isRegistering = true;/* w ww. j a v a2s . c o m*/ return; } if (!isDeviceCurrentSensorsRegistered || !isGPSReady) { return; } String currentSpeedValue = "" + mySensor.getCurrentSpeed(); getSensorDataToSend("speedDatastoreUUID", "Speed", currentSpeedValue); lastSpeedValue = currentSpeedValue; for (int k = 0; k < sensorList.size(); k++) { switch (sensorList.get(k).getType()) { case Sensor.TYPE_AMBIENT_TEMPERATURE: // Gradi Celsius (C) String currentTempValue = "" + mySensor.getCurrentTemp(); getSensorDataToSend("temperatureDatastoreUUID", "Temperature", currentTempValue); lastTempValue = currentTempValue; break; case Sensor.TYPE_PRESSURE: String currentPressureValue = "" + mySensor.getCurrentPressure(); getSensorDataToSend("pressureDatastoreUUID", "Pressure", currentPressureValue); lastPressureValue = currentPressureValue; break; case Sensor.TYPE_LIGHT: // lx String currentLightValue = "" + mySensor.getCurrentLight(); getSensorDataToSend("lightDatastoreUUID", "Light", currentLightValue); lastLightValue = currentLightValue; break; case Sensor.TYPE_ACCELEROMETER: // m/s2 String currentAccelerationValue = mySensor.getCurrentAcceleration(); getSensorDataToSend("accelerometerDatastoreUUID", "Accelerometer", currentAccelerationValue); lastAccelerationValue = currentAccelerationValue; break; case Sensor.TYPE_GYROSCOPE: // rad/s String currentGyroscopeValue = mySensor.getCurrentGyroscope(); getSensorDataToSend("gyroscopeDatastoreUUID", "Gyroscope", currentGyroscopeValue); lastGyroscopeValue = currentGyroscopeValue; break; case Sensor.TYPE_MAGNETIC_FIELD: // T String currentMagneticValue = mySensor.getCurrentMagnetic(); getSensorDataToSend("magneticFieldDatastoreUUID", "MagneticField", currentMagneticValue); lastMagneticValue = currentMagneticValue; break; case Sensor.TYPE_PROXIMITY: // cm String currentProximityValue = "" + mySensor.getCurrentProximity(); getSensorDataToSend("proximityDatastoreUUID", "Proximity", currentProximityValue); lastProximityValue = currentProximityValue; break; case Sensor.TYPE_ROTATION_VECTOR: // unita di misura sconosciuta String currentRotationValue = mySensor.getCurrentRotation(); getSensorDataToSend("rotationVector", "RotationVector", currentRotationValue); lastRotationValue = currentRotationValue; break; case Sensor.TYPE_GRAVITY: // m/s2 String currentGravityValue = mySensor.getCurrentGravity(); getSensorDataToSend("gravity", "Gravity", currentGravityValue); lastGravityValue = currentGravityValue; break; case Sensor.TYPE_LINEAR_ACCELERATION: // m/s2 String currentLinearAccelerationValue = mySensor.getCurrentLinearAcceleration(); getSensorDataToSend("linearAcceleration", "LinearAcceleration", currentLinearAccelerationValue); lastLinearAccelerationValue = currentLinearAccelerationValue; break; case Sensor.TYPE_RELATIVE_HUMIDITY: // % String currentRelativeHumidity = "" + mySensor.getCurrentHumidity(); getSensorDataToSend("relativeHumidity", "RelativeHumidity", currentRelativeHumidity); lastRelativeHumidity = currentRelativeHumidity; break; default: break; } } runOnUiThread(new Runnable() { @Override public void run() { if (shouldUpdateCountdown) { new CountDownTimer(countdown, 1000) { public void onTick(long millisUntilFinished) { countdownText.setText("" + millisUntilFinished / 1000); } public void onFinish() { } }.start(); } } }); }
From source file:com.vonglasow.michael.satstat.ui.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); DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT); fmt.setTimeZone(TimeZone.getTimeZone("UTC")); String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis()))); File dumpFile = new File(dumpDir, fileName); PrintStream s;/*from ww w . j a v a 2 s .c om*/ 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(); Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); Uri contentUri = Uri.fromFile(dumpFile); mediaScanIntent.setData(contentUri); c.sendBroadcast(mediaScanIntent); } catch (FileNotFoundException e2) { e2.printStackTrace(); } defaultUEH.uncaughtException(t, e); } }); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType); prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots); prefCoord = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord))); prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc); prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid); prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2); prefWifiSort = Integer .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort))); prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline); prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath); ActionBar actionBar = getSupportActionBar(); setContentView(R.layout.activity_main); // 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(TAG, "isWideScreen=" + Boolean.toString(isWideScreen)); // Create the adapter that will return a fragment for each of the // 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); Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme); mTabLayout = new TabLayout(ctx); LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); mTabLayout.setLayoutParams(mTabLayoutParams); for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) { TabLayout.Tab newTab = mTabLayout.newTab(); newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i)); mTabLayout.addTab(newTab); } actionBar.setDisplayShowCustomEnabled(true); actionBar.setCustomView(mTabLayout); mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager)); mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout)); // This is needed by the mapsforge library. AndroidGraphicFactory.createInstance(this.getApplication()); // Get system services for event delivery locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE); mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY); mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE); mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY); mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); }
From source file:org.thecongers.mtpms.MainActivity.java
@SuppressLint("HandlerLeak") @Override//w w w . j ava 2s .c o m public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setTitle(R.string.app_name); layoutFront = (LinearLayout) findViewById(R.id.layoutFront); layoutRear = (LinearLayout) findViewById(R.id.layoutRear); txtFrontPressure = (TextView) findViewById(R.id.txtFrontPressure); txtFrontTemperature = (TextView) findViewById(R.id.txtFrontTemperature); txtFrontVoltage = (TextView) findViewById(R.id.txtFrontVoltage); txtRearPressure = (TextView) findViewById(R.id.txtRearPressure); txtRearTemperature = (TextView) findViewById(R.id.txtRearTemperature); txtRearVoltage = (TextView) findViewById(R.id.txtRearVoltage); txtOutput = (TextView) findViewById(R.id.txtOutput); View myView = findViewById(R.id.appLayout); root = myView.getRootView(); sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); // Keep screen on getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Watch for Bluetooth Changes IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); this.registerReceiver(btReceiver, filter1); this.registerReceiver(btReceiver, filter2); this.registerReceiver(btReceiver, filter3); sensorDB = new SensorIdDatabase(this); // Backgrounds background = this.getResources().getDrawable(R.drawable.rectangle_bordered); redBackground = this.getResources().getDrawable(R.drawable.rectangle_bordered_red); backgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_dark); redBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_bordered_red_dark); txtOutBackground = this.getResources().getDrawable(R.drawable.rectangle); txtOutBackgroundDark = this.getResources().getDrawable(R.drawable.rectangle_dark); // Update textViews with select units String pressureFormat = sharedPrefs.getString("prefpressuref", "0"); String pressureUnit = "psi"; if (pressureFormat.contains("1")) { // KPa pressureUnit = "KPa"; } else if (pressureFormat.contains("2")) { // Kg-f pressureUnit = "Kg-f"; } else if (pressureFormat.contains("3")) { // Bar pressureUnit = "Bar"; } String temperatureUnit = "C"; if (sharedPrefs.getString("preftempf", "0").contains("0")) { // F temperatureUnit = "F"; } txtFrontPressure.setText("--- " + pressureUnit); txtFrontTemperature.setText("--- " + temperatureUnit); txtFrontVoltage.setText("--- V"); txtRearPressure.setText("--- " + pressureUnit); txtRearTemperature.setText("--- " + temperatureUnit); txtRearVoltage.setText("--- V"); // Set initial color scheme if (!sharedPrefs.getBoolean("prefNightMode", false)) { root.setBackgroundColor(getResources().getColor(android.R.color.white)); layoutFront.setBackground(background); layoutRear.setBackground(background); txtFrontPressure.setTextColor(getResources().getColor(android.R.color.black)); txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.black)); txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.black)); txtRearPressure.setTextColor(getResources().getColor(android.R.color.black)); txtRearTemperature.setTextColor(getResources().getColor(android.R.color.black)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black)); txtOutput.setBackground(txtOutBackground); txtOutput.setTextColor(getResources().getColor(android.R.color.black)); } else { root.setBackgroundColor(getResources().getColor(android.R.color.black)); layoutFront.setBackground(backgroundDark); layoutRear.setBackground(backgroundDark); txtFrontPressure.setTextColor(getResources().getColor(android.R.color.white)); txtFrontTemperature.setTextColor(getResources().getColor(android.R.color.white)); txtFrontVoltage.setTextColor(getResources().getColor(android.R.color.white)); txtRearPressure.setTextColor(getResources().getColor(android.R.color.white)); txtRearTemperature.setTextColor(getResources().getColor(android.R.color.white)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white)); txtOutput.setBackground(txtOutBackgroundDark); txtOutput.setTextColor(getResources().getColor(android.R.color.white)); } // Check if there are sensor to wheel mappings if (sharedPrefs.getString("prefFrontID", "").equals("") && sharedPrefs.getString("prefRearID", "").equals("")) { new AlertDialog.Builder(this).setTitle(R.string.alert_setup_title) .setMessage(R.string.alert_setup_message).setNeutralButton(R.string.alert_setup_button, null) .show(); } sensorMessages = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case RECEIVE_MESSAGE: // Message received Log.d(TAG, "Serial Message Received, Length: " + msg.arg1); // Check to see if message is the correct size if (msg.arg1 == 13) { byte[] readBuf = (byte[]) msg.obj; // Validate against checksum int calculatedCheckSum = readBuf[4] + readBuf[5] + readBuf[6] + readBuf[7] + readBuf[8] + readBuf[9] + readBuf[10]; if (calculatedCheckSum == readBuf[11]) { // Convert to hex String[] hexData = new String[13]; StringBuilder sbhex = new StringBuilder(); for (int i = 0; i < msg.arg1; i++) { hexData[i] = String.format("%02X", readBuf[i]); sbhex.append(hexData[i]); } // Get sensor position String position = hexData[3]; // Get sensor ID StringBuilder sensorID = new StringBuilder(); sensorID.append(hexData[4]); sensorID.append(hexData[5]); sensorID.append(hexData[6]); sensorID.append(hexData[7]); // Check if sensor ID is new boolean checkID = sensorDB.sensorIdExists(sensorID.toString()); if (!checkID) { // Add sensor ID to db sensorDB.addID(sensorID.toString()); Toast.makeText(MainActivity.this, getResources().getString(R.string.toast_newSensor) + " " + sensorID.toString(), Toast.LENGTH_LONG).show(); } // Only parse message if there is one or more sensor mappings String prefFrontID = sharedPrefs.getString("prefFrontID", ""); String prefRearID = sharedPrefs.getString("prefRearID", ""); if (!prefFrontID.equals("") || !prefRearID.equals("")) { try { // Get temperature int tempC = Integer.parseInt(hexData[8], 16) - 50; double temp = tempC; String temperatureUnit = "C"; // Get tire pressure int psi = Integer.parseInt(hexData[9], 16); double pressure = psi; String pressureUnit = "psi"; // Get battery voltage double voltage = Integer.parseInt(hexData[10], 16) / 50; // Get pressure thresholds int fLowPressure = Integer .parseInt(sharedPrefs.getString("prefFrontLowPressure", "30")); int fHighPressure = Integer .parseInt(sharedPrefs.getString("prefFrontHighPressure", "46")); int rLowPressure = Integer .parseInt(sharedPrefs.getString("prefRearLowPressure", "30")); int rHighPressure = Integer .parseInt(sharedPrefs.getString("prefRearHighPressure", "46")); if (sharedPrefs.getString("preftempf", "0").contains("0")) { // F temp = (9.0 / 5.0) * tempC + 32.0; temperatureUnit = "F"; } int formattedTemperature = (int) (temp + 0.5d); String pressureFormat = sharedPrefs.getString("prefpressuref", "0"); if (pressureFormat.contains("1")) { // KPa pressure = psi * 6.894757293168361; pressureUnit = "KPa"; } else if (pressureFormat.contains("2")) { // Kg-f pressure = psi * 0.070306957965539; pressureUnit = "Kg-f"; } else if (pressureFormat.contains("3")) { // Bar pressure = psi * 0.0689475729; pressureUnit = "Bar"; } int formattedPressure = (int) (pressure + 0.5d); // Get checksum String checksum = hexData[11]; Log.d(TAG, "Sensor ID: " + sensorID.toString() + ", Sensor Position: " + position + ", Temperature(" + temperatureUnit + "): " + String.valueOf(temp) + ", Pressure(" + pressureUnit + "): " + String.valueOf(pressure) + ", Voltage: " + String.valueOf(voltage) + ", Checksum: " + checksum + ", Data: " + sbhex.toString() + ", Bytes:" + msg.arg1); if (sensorID.toString().equals(prefFrontID)) { Log.d(TAG, "Front ID matched"); // Check for data logging enabled if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } logger.write("front", String.valueOf(psi), String.valueOf(tempC), String.valueOf(voltage)); } // Set front tire status if (psi <= fLowPressure) { frontStatus = 1; } else if (psi >= fHighPressure) { frontStatus = 2; } else { frontStatus = 0; } txtFrontPressure .setText(String.valueOf(formattedPressure) + " " + pressureUnit); txtFrontTemperature.setText( String.valueOf(formattedTemperature) + " " + temperatureUnit); txtFrontVoltage.setText(String.format("%.2f", voltage) + " V"); } else if (sensorID.toString().equals(prefRearID)) { Log.d(TAG, "Rear ID matched"); // Check for data logging enabled if (sharedPrefs.getBoolean("prefDataLogging", false)) { // Log data if (logger == null) { logger = new LogData(); } logger.write("rear", String.valueOf(psi), String.valueOf(tempC), String.valueOf(voltage)); } // Set rear tire status if (psi <= rLowPressure) { rearStatus = 1; } else if (psi >= rHighPressure) { rearStatus = 2; } else { rearStatus = 0; } txtRearPressure .setText(String.valueOf(formattedPressure) + " " + pressureUnit); txtRearTemperature.setText( String.valueOf(formattedTemperature) + " " + temperatureUnit); txtRearVoltage.setText(String.format("%.2f", voltage) + " V"); } // Update txtOutput box and send notification if ((frontStatus == 0) && (rearStatus == 0)) { txtOutput.setText(""); if (notificationManager != null) { notificationManager.cancel(0); } } else if ((frontStatus == 1) && (rearStatus == 0)) { txtOutput .setText(getResources().getString(R.string.alert_lowFrontPressure)); Notify(getResources().getString(R.string.alert_lowFrontPressure)); } else if ((frontStatus == 2) && (rearStatus == 0)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontPressure)); Notify(getResources().getString(R.string.alert_highFrontPressure)); } else if ((rearStatus == 1) && (frontStatus == 0)) { txtOutput.setText(getResources().getString(R.string.alert_lowRearPressure)); Notify(getResources().getString(R.string.alert_lowRearPressure)); } else if ((rearStatus == 2) && (frontStatus == 0)) { txtOutput .setText(getResources().getString(R.string.alert_highRearPressure)); Notify(getResources().getString(R.string.alert_highRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 1)) { txtOutput.setText( getResources().getString(R.string.alert_lowFrontLowRearPressure)); Notify(getResources().getString(R.string.alert_lowFrontLowRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 2)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontHighRearPressure)); Notify(getResources().getString(R.string.alert_highFrontHighRearPressure)); } else if ((frontStatus == 1) && (rearStatus == 2)) { txtOutput.setText( getResources().getString(R.string.alert_lowFrontHighRearPressure)); Notify(getResources().getString(R.string.alert_lowFrontHighRearPressure)); } else if ((frontStatus == 2) && (rearStatus == 1)) { txtOutput.setText( getResources().getString(R.string.alert_highFrontLowRearPressure)); Notify(getResources().getString(R.string.alert_highFrontLowRearPressure)); } // Update color scheme if ((!itsDark) && (!sharedPrefs.getBoolean("prefNightMode", false))) { if (frontStatus == 0) { layoutFront.setBackground(background); } else { layoutFront.setBackground(redBackground); } if (rearStatus == 0) { layoutRear.setBackground(background); } else { layoutRear.setBackground(redBackground); } root.setBackgroundColor(getResources().getColor(android.R.color.white)); txtOutput.setBackground(txtOutBackground); txtOutput.setTextColor(getResources().getColor(android.R.color.black)); txtFrontPressure .setTextColor(getResources().getColor(android.R.color.black)); txtFrontTemperature .setTextColor(getResources().getColor(android.R.color.black)); txtFrontVoltage .setTextColor(getResources().getColor(android.R.color.black)); txtRearPressure .setTextColor(getResources().getColor(android.R.color.black)); txtRearTemperature .setTextColor(getResources().getColor(android.R.color.black)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.black)); } else { if (frontStatus == 0) { layoutFront.setBackground(backgroundDark); } else { layoutFront.setBackground(redBackgroundDark); } if (rearStatus == 0) { layoutRear.setBackground(backgroundDark); } else { layoutRear.setBackground(redBackgroundDark); } root.setBackgroundColor(getResources().getColor(android.R.color.black)); txtOutput.setBackground(txtOutBackgroundDark); txtOutput.setTextColor(getResources().getColor(android.R.color.white)); txtFrontPressure .setTextColor(getResources().getColor(android.R.color.white)); txtFrontTemperature .setTextColor(getResources().getColor(android.R.color.white)); txtFrontVoltage .setTextColor(getResources().getColor(android.R.color.white)); txtRearPressure .setTextColor(getResources().getColor(android.R.color.white)); txtRearTemperature .setTextColor(getResources().getColor(android.R.color.white)); txtRearVoltage.setTextColor(getResources().getColor(android.R.color.white)); } } catch (NumberFormatException e) { Log.d(TAG, "Malformed message, unexpected value"); } } } } else { Log.d(TAG, "Malformed message, message length: " + msg.arg1); } break; } } }; // Light Sensor Stuff SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); Sensor lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); if (lightSensor == null) { Log.d(TAG, "Light sensor not found"); } else { float max = lightSensor.getMaximumRange(); sensorManager.registerListener(lightSensorEventListener, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); hasSensor = true; Log.d(TAG, "Light Sensor Max Value: " + max); } // Try to connect to iTPMSystem btConnect(); }
From source file:com.davidmascharka.lips.MainActivity.java
@Override public void onSensorChanged(SensorEvent event) { /*//ww w.ja v a2 s.co m * Because Android doesn't let us query a sensor reading whenever we want so * we have to keep track of the readings at all times. Here we just update * the class members with the values associated with each reading we're * interested in. */ switch (event.sensor.getType()) { case Sensor.TYPE_ACCELEROMETER: accelerometerX = event.values[0]; accelerometerY = event.values[1]; accelerometerZ = event.values[2]; break; 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); }