Search code examples
javaandroidcamerabrightness

Android: detect brightness (amount of light) in phone's surroundings using the camera?


The following applies to the Android operating system.

I am trying to estimate how dark (or light) it is in the room where the phone is located using the camera.

The idea is that the camera can return a certain brightness level, which I can use to determine the amount of light in the surroundings of the phone.

My question is simple: how do I use the camera (either the front of back camera) to get this amount of brightness (the "amount of light")?

Thanks in advance.


Solution

  • Here is how you register a listener on the light sensor:

    private final SensorManager mSensorManager;
    private final Sensor mLightSensor;
    private float mLightQuantity;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        // Obtain references to the SensorManager and the Light Sensor
        mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    
        // Implement a listener to receive updates
        SensorEventListener listener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent event) {
                mLightQuantity = event.values[0];
            }
        }
    
        // Register the listener with the light sensor -- choosing
        // one of the SensorManager.SENSOR_DELAY_* constants.
        mSensorManager.registerListener(
                listener, lightSensor, SensorManager.SENSOR_DELAY_UI);
    }
    

    EDIT: Thanks to @AntiMatter for the suggested updates.

    Docs: SensorEventListener SensorManager SensorEvent Sensor