Wednesday, August 29, 2012

Using Android device build-in light sensor in Android

It's a simple light meter Using Android device build-in light sensor. A ProgressBar is defined in main.xml as a indicator of the light sensor. The default value of 100 defined in android:max is a dummy value, it will be updated after lightSensor.getMaximumRange(). The updated reading will be be read in lightSensorEventListener, and update the ProgressBar accordingly.

Using Android device build-in light sensor

package com.AndroidLightSensor;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidLightSensorActivity extends Activity {
 ProgressBar lightMeter;
 TextView textMax, textReading;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        lightMeter = (ProgressBar)findViewById(;
        textMax = (TextView)findViewById(;
        textReading = (TextView)findViewById(;
        SensorManager sensorManager
        = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        Sensor lightSensor
        = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
        if (lightSensor == null){
           "No Light Sensor! quit-",
         float max =  lightSensor.getMaximumRange();
         textMax.setText("Max Reading: " + String.valueOf(max));
    SensorEventListener lightSensorEventListener
    = new SensorEventListener(){
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
   // TODO Auto-generated method stub
  public void onSensorChanged(SensorEvent event) {
   // TODO Auto-generated method stub
    float currentReading = event.values[0];
    textReading.setText("Current Reading: " + String.valueOf(currentReading));