In this chapter, we will learn how to write our first sensor program. We will also understand the various callbacks, and how to use these callbacks in the foreground activity and background service. This chapter will also walk you through a basic algorithm developed using sensor values.
We will cover the following topics in this chapter:
The two most important callbacks of the sensor framework are the onSensorChanged()
and onAccuracyChanged()
methods. In order to write efficient sensor code, it's important to understand when these methods are called, and what processing we can do in them. These callbacks are methods of the SensorEventListnener
interface, which needs to be implemented in the class where the callbacks are to be received:
onSensorChanged()
is the first callback and has the following syntax:
@Override public void onSensorChanged(SensorEvent event) { }
Depending on the type of reporting mode of the sensor, this method will be called, either at regular frequency (Continuous mode) or whenever there is a change in the value of the sensors from the previously reported value (On the change mode). The onSensorChanged()
method provides the sensor values inside the float value[]
array of the SensorEvent
object. These sensor values are different from the previously reported values. There may be instances where the OS can choose to report sensor values at a different frequency than specified at the time of the registration of the listener. Generally, this happens because the OS is heavily loaded and busy with performing some other, more important, processing tasks:
onAccuracyChanged()
is the second callback and has the following syntax:
@Override public void onAccuracyChanged(Sensor sensor, int accuracy) { }
Whenever the OS chooses to change (increase or decrease) the accuracy of the sensor values, it informs your listener using this callback. In this method call, it sends the new accuracy value (Integer) and the sensor object for which the accuracy has changed. Generally, this change in accuracy happens rarely; only when the OS goes into battery-saver mode or gets involved with important heavy-processing tasks. When the OS gets busy, it reduces the accuracy, and when the OS becomes free, it increases the accuracy.
The following sequence diagram explains the logical steps required by your application to get the values from the sensors:
SensorManager
class from the system sensor service.Sensor
class object from SensorManager
.SensorEventListener
interface for your application. We can implement the SensorEventListener
interface in activity, service, or any other class, and the chosen one will receive the sensor callbacks.SensorEventListener
with the SensorManager
class.SensorEvent
objects in the onSensorChanged()
method callback of SensorEventListener
.SensorEventListener
interface with the SensorManager
class when it doesn't require the sensor data any more.