May 23, 2011

Android Light Sensor

Hello Guys,

Here I am explaining you how to use Light Sensor of Android.
1. Implement SensorEventListener
2. Create variable for SensorManager and Sensor
3. Get Object of SensorManager using system service
4. Get Object of Light Sensor from SensorManager
5. Implement onAccuracyChanged and onSensorChanged method

package com.test;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;

public class Test extends Activity implements SensorEventListener{

 private SensorManager mSensorManager;
 private Sensor mLight;

 public void onCreate(Bundle savedInstanceState) {

   mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
         mLight = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);

 protected void onResume() {
   mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
 protected void onPause() {
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
   if(sensor.getType() == Sensor.TYPE_LIGHT){
    Log.i("Sensor Changed", "Accuracy :" + accuracy);

 public void onSensorChanged(SensorEvent event) {
  if( event.sensor.getType() == Sensor.TYPE_LIGHT){
   Log.i("Sensor Changed", "onSensor Change :" + event.values[0]);

Screen Shot of Change Values