Android devices have a lot of devices to play with. In this tutorial, we are going to play with the ambient luminosity sensor to create a Luminosity Detector Application for Android devices.

You can enjoy this tutorial in video on YouTube :

To start, we are going to create an ultra simple User Interface for our application. We just need a RelativeLayout in our main layout :

Now, it’s time to write the Java code of the Main Activity of our Luminosity Detector Application. First, we need to get the SensorManager instance by calling getSystemService method with the SENSOR_SERVICE constant in parameter.

Then, we get the default sensor for the Ambient Luminosity sensor by calling the getDefaultSensor method of the SensorManager instance got previously with Sensor.TYPE_LIGHT method in parameter.

We check if the Sensor instance returned is null or no. If it is null, the device doesn’t have an Ambient Luminosity sensor. So, we display a message to alert the user and we quit the application by calling the finish method.

If the device has an Ambient Luminosity sensor, we get the maximum range of the sensor. Then, we create a SensorEventListener implementation to manage the values’ changes of the Ambient Luminosity sensor.

In the onSensorChanged method of our implementation, we get the new value for luminosity in lx. We put this value in the [0, 255] range to be able to change the background color of our main activity according the ambient luminosity. Thus, the background color will become lighter when the ambient luminosity will increase.

The last step is to register our SensorEventListener implementation and the light sensor instance got previously on the SensorManager instance by calling its registerListener. In the onPause method of our activity, we mustn’t forget to unregister this listener by calling the unregisterListener method.

This gives us the following code for the Main Activity of our application :

Now, we can try our Luminosity Detector Application on a real Android device and enjoy the result by approaching a light source of the device :

That’s all for that tutorial. To discover more tutorials on Android development, don’t hesitate to visit the SSaurel’s Channel on YouTube : https://www.youtube.com/user/sylsau