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

后端 未结 5 996
小蘑菇
小蘑菇 2020-12-01 08:38

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.

5条回答
  •  忘掉有多难
    2020-12-01 09:20

    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

提交回复
热议问题