Showing posts with label Light sensor. Show all posts
Showing posts with label Light sensor. Show all posts

May 11, 2011

How to use the Light sensor on Android

If your android device has a Light Sensor you can use it in your applications. It provide the value in lux units as described here. More about lux find here.

main.xml





main.java
package com.blog.lightsensor;

import java.util.Date;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;

public class main extends Activity implements SensorEventListener {
 private  SensorManager sensorManager = null;
 private  Sensor currentSensor = null; 
 
 @Override
 public void onResume(){
  super.onResume();
  if(currentSensor != null)sensorManager.registerListener(this, currentSensor, SensorManager.SENSOR_DELAY_FASTEST);
 }
 
 @Override
 public void onPause(){
  super.onPause();
  sensorManager.unregisterListener(this);
 } 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     sensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
  currentSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT );
  if(currentSensor != null){
   sensorManager.registerListener(this, currentSensor, SensorManager.SENSOR_DELAY_FASTEST);
  }else{
   ((TextView) findViewById(R.id.textView1)).setText("Can't initialize the LIGHT sensor.");   
  } 
    }

 @Override
 public void onAccuracyChanged(Sensor sensor, int accuracy) {
  // TODO Auto-generated method stub
 }

 @Override
 public void onSensorChanged(SensorEvent event) {
  // TODO Auto-generated method stub
  
  if (event.sensor.getType() == Sensor.TYPE_LIGHT){   
   TextView tv = (TextView) findViewById(R.id.textView1);
   tv.setText( tv.getText()+ "value: " +event.values[0] + " lux , time: " + new Date() + "\n");   
  }
 }
}