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");   
  }
 }
}

6 comentarii:

deep vats said...

nice , it is the basic step of this
nice blog and information ,
android application development please keep it up

Anonymous said...

Hi,

What need I put into the manifest file?

Is this will be correct?


is permission needed?

Anonymous said...

lost this line:
uses-feature android:name="android.hardware.sensor.light"

From.Ae said...

Well, I have got the best information from here the site is fully stuffed with the knowledgeable information.

Android App Developer in Pakistan

Alex said...

Been reading this site for awhile now, always has really good posts and topics please keep it up! loads of blogs are going under lately from lack of new posts etc
android apps developer

Unknown said...

Nice info you posted here! Keep up the excellent work!
Mobile app developers India

Post a Comment