Hello,
Today we are going to learn how to access sensor and retrieve data from it.
First, to access device’s sensors we have to use Class SensorManager(android.hardware.SensorManager). that lets you access the device’s sensors
http://developer.android.com/reference/android/hardware/SensorManager.html
To get SensorManager we have to use getSystemService(ServiceName)
It returns handle to a system level service.Hence we get handle to SensorManager as below
Today we are going to learn how to access sensor and retrieve data from it.
First, to access device’s sensors we have to use Class SensorManager(android.hardware.SensorManager). that lets you access the device’s sensors
http://developer.android.com/reference/android/hardware/SensorManager.html
To get SensorManager we have to use getSystemService(ServiceName)
It returns handle to a system level service.Hence we get handle to SensorManager as below
//Declare Sensor Manager class object private SensorManager mSensorManager; //Next get the handle to the Sensor service mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);Next declare a listener for receiving notifications from the SensorManager when sensor values have changed as.
private final SensorListener sensorListener = new SensorListener(){ public void onSensorChanged(int sensor, float[] values) { //Retrieve the values from the float array values which contains sensor data Float dataX = values[SensorManager.DATA_X]; Float dataY = values[SensorManager.DATA_Y]; Float dataZ = values[SensorManager.DATA_Z]; //Now we got the values and we can use it as we want Log.i("X - Value",""+dataX); Log.i("Y - Value",""+dataY); Log.i("Z - Value",""+dataZ); } public void onAccuracyChanged(int sensor, int accuracy) {} };For above listener to be notified of changed value we have to register it . We can register it in onResume as
protected void onResume() { super.onResume(); mSensorManager.registerListener(sensorListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); }The syntax of register listener is as
SensorManager.registerListener(SensorListener listener, int sensors, int rate)We can unregister the sensorlistener in onStop as
protected void onStop() { super.onStop(); mSensorManager.unregisterListener(sensorListener); }
No comments:
Post a Comment