Saturday, 12 October 2013

Android Sensors example

Sensor

A sensor is a device, which responds to an input quantity by generating a functionally related output usually in the form of an electrical or optical signal.

In android several type of Sensor present like
  1. Proximity sensor
  2. Accelerator sensor
  3. Gyroscope sensor
  4. Location sensor
To create Sensor Based Application: We have to follow three step.

  1. Create instance of SensorManager
  2. Create instance of Sensor
  3. implement Sensor Event listener

SensorManager

Sensor Manager is use to get device sensor accessibility.

SensorManager mysensormanager = (SensorManager)getSystemService(SENSOR_SERVICE)


Sensor: 

it is a class that hold a particular sensor object.

Sensor mysensor = mysensormanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

implement SensorEventListener: 

Now we have to override onAccuracyChanged(Sensor sensor, int accurracy) and onSensorChanged(SensorEvent event) method. what ever we want using sensor we have to write within onSensorChanged() method.


public void onAccuracyChanged(Sensor sensor, int accuracy) {
     }

     public void onSensorChanged(SensorEvent event) {

     }

Note : Since Sensor is highly responsive so to make power efficient application we have to register and unregister SensorListerner smartly.
               we are normally register sensor event listener in on Resume() menthod  by calling registerListener().
protected void onResume() {
         super.onResume();
         mysensormanager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
     }
 and unregister in onPause method by calling unregisterListener(this);

     protected void onPause() {
         super.onPause();
         mSensorManager.unregisterListener(this);
     } 
Android-Sensor-Manager
Android Senor manager work flow


No comments:

Today's Pageviews