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

Solution 1:

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

Solution 2:

If you wanted to use the camera, for instance if the other sensors were not available then I would

  1. Set the camera's auto exposure to off, and set exposure compensation to 0
  2. Set capture to lowest quality / size (why bother with more)
  3. Make the preview window as small as possible (maybe you could even set it to invisible and still get a frame to analyze, not sure)
  4. Get an image preview frame, but those are in yuv format so 2.1 and earlier would need an a translator.

Then I would compute the histogram for the images luminosity and work right (brightest) to left (dimmest) until you found the first significant value higher than N, which would determine your scene brightness.

Having said all of that I would not do it since you would need to test for a lot of outlier situations.

Course not sure what you use case is, if it's a situation where you are using it to adjust "brightness" in a car, then forward facing camera would be effected by headlights etc.

Anyway interesting problem but seems like a lot of work for such little gain, especially with most decent pieces of hardware having those sensors