Getting Sensor Events

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 ...

Get Pro Android 4 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.