Aleksey Timoshchenko Aleksey Timoshchenko - 4 months ago 12
Android Question

How to check amount of light?

I work with

Camera2API
and I need to disable the ability to take a photo if the outside is not enough light ...

I've thought about that, when user use standard camera he have setting to flash (auto mode).

If I understand correctly, the camera works with some sort of sensor that detects the amount of light, and if it is not enough that the flash works.

How to connect this sensor?

Answer

You could use something similar to the code listed here:

https://developer.android.com/guide/topics/sensors/sensors_environment.html

Modify it like this to work with the light sensor:

public class SensorActivity extends Activity implements SensorEventListener {
  private SensorManager mSensorManager;
  private Sensor mLight;

  @Override
  public final void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Get an instance of the sensor service, and use that to get an instance of
    // a particular sensor.
    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mLight= mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
  }

  @Override
  public final void onAccuracyChanged(Sensor sensor, int accuracy) {
    // Do something here if sensor accuracy changes.
  }

  @Override
  public final void onSensorChanged(SensorEvent event) {
    float luminosity = event.values[0];
    // Do something with this sensor data.
  }

  @Override
  protected void onResume() {
    // Register a listener for the sensor.
    super.onResume();
    mSensorManager.registerListener(this, mLight, SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // Be sure to unregister the sensor when the activity pauses.
    super.onPause();
    mSensorManager.unregisterListener(this);
  }
}