In Android, Ambient Light Sensing is pretty much straight forward. Below is the code to achieve this. Also including some of the experiences in testing this out with the real hardware , my Android One phone.
android.hardware.SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if(sensorManager != null) {
Sensor lightSensor
= sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor == null){
Log.v(LOG_TAG,"light sensor is null!");
}else{
float max = lightSensor.getMaximumRange();
Log.v(LOG_TAG,"Max light range is :"+max);
sensorManager.registerListener(lightSensorEventListener,
lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
else
{
Log.v(LOG_TAG,"Sensor manager is null during create");
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
@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){
final float currentReading = event.values[0];
Log.v(LOG_TAG,"Current reading from light sensor is :"+currentReading);
}
}
};
Based on experience, few points below
- During day light, the onSensorChanged call back get called frequently with values > 70
- When there is no light, the value becomes < 10
References:
No comments:
Post a Comment