Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Sensors provide data to our application once we register a listener to receive the data. When our listener is not listening, the sensor can be turned off, conserving battery life, so make sure you only listen when you really need to. Setting up a sensor listener is easy to do. Let’s say that we want to measure the light levels from the light sensor. Listing 29–2 shows the Java code for a sample app that does this.
Listing 29–2. Java Code for a Light Sensor Monitor App
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager mgr;
private Sensor light;
private TextView text;
private StringBuilder msg = new StringBuilder(2048);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
light = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
text = (TextView) findViewById(R.id.text);
}
@Override
protected void onResume() {
mgr.registerListener(this, light,
SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
@Override
protected void onPause() {
mgr.unregisterListener(this, light);
super.onPause();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
msg.insert(0, sensor.getName() + " accuracy changed: " +
accuracy + (accuracy==1?" (LOW)":(accuracy==2?" (MED)":
" (HIGH)")) + "\n");
text.setText(msg);
text.invalidate();
}
public void onSensorChanged(SensorEvent event) {
msg.insert(0, "Got a sensor event: " + event.values[0] +
" SI lux units\n");
text.setText(msg);
text.invalidate();
}
}