Android sensors
Most of the android devices have built-in sensors that measure motion, orientation, and various environmental condition. 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. For this android provides us with some classes.
Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, 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);
The next thing you need to do is to instantiate the object of Sensor class by calling the getDefaultSensor() method of the SensorManager class. Its syntax is given below −
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
You can get a list of sensors supported by your device by calling the getSensorList method, which will return a list of sensors containing their name and version number and much more information. You can then iterate the list to get the information. Its syntax is given below −
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL); for(Sensor sensor: list){ }
Apart from the these methods, there are other methods provided by the SensorManager class for managing sensors framework. These methods are listed below −
Sr.No | Method & description |
---|---|
1 |
getDefaultSensor(int type)
This method get the default sensor for a given type.
|
2 |
getOrientation(float[] R, float[] values)
This method returns a description of the current primary clip on the clipboard but not a copy of its data.
|
3 |
getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from the inclination matrix.
|
4 |
registerListener(SensorListener listener, int sensors, int rate)
This method registers a listener for the sensor
|
5 |
unregisterListener(SensorEventListener listener, Sensor sensor)
This method unregisters a listener for the sensors with which it is registered.
|
6 |
getOrientation(float[] R, float[] values)
This method computes the device's orientation based on the rotation matrix.
|
7 |
getAltitude(float p0, float p)
This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.
|
Comments
Post a Comment