Most of the android devices have built-in sensors that measure motion, orientation, and various environmental conditions. The android platform supports three broad categories of sensors.
- Motion Sensors
- Environmental sensors
- Position sensors
Some of the sensors are hardware based and some are software based sensors. Whatever the sensor is, android allows us to get the raw data from these sensors and use it in our application.
Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, the first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
Sensor light;
light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
Once that sensor is declared , you need to register its listener and override two methods which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −
sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
}
Getting list of sensors supported
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){
}
Apart from these methods, there are other methods provided by the SensorManager class for managing sensors framework.
Sr.No | Method & description |
1 | getDefaultSensor(int type)This method gets the default sensor for a given type. |
2 | getInclination(float[] I)This method computes the geomagnetic inclination angle in radians from the inclination matrix. |
3 | registerListener(SensorListener listener, int sensors, int rate)This method registers a listener for the sensor |
4 | unregisterListener(SensorEventListener listener, Sensor sensor)This method unregisters a listener for the sensors with which it is registered. |
5 | getOrientation(float[] R, float[] values)This method computes the device’s orientation based on the rotation matrix. |
6 | getAltitude(float p0, float p)This method computes the Altitude in metres from the atmospheric pressure and the pressure at sea level. |