Skip to content Skip to sidebar Skip to footer

Getting Light Sensor Value

So I'm looking for a way to get the current value of the Light Sensor (in Lux obviously) on a button press. Here is the code I'm using to implement control of the light sensor publ

Solution 1:

As noted here, it isn't possible to directly get the current sensor value and, while some more recent versions of Android will generate an onSensorChanged event as soon as the listener is registered (allowing you to get a baseline), earlier versions don't. So the only thing you can really do is hope that the user is either running a more recent version of Android or that the value changes and then retrieve the current lux value from event.values[0] inside onSensorChanged (e.g.) :

publicvoidonSensorChanged(SensorEvent event) 
 {
     if( event.sensor.getType() == Sensor.TYPE_LIGHT)
     {
        currentLux = event.values[0];
        if (currentLux > maxLux)
          maxLux = currentLux;
     }
 }

(After changing maxLux and currentLux to floats). This then leaves the issue of retrieving the current value based on a button press, which can be done by looking at the value of currentLux at the time the button is pressed.

Post a Comment for "Getting Light Sensor Value"