2 * Copyright (C) 2012 ZXing authors
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package cz.cvut.fel.dce.barcodescanner;
19 import android.content.Context;
20 import android.content.SharedPreferences;
21 import android.hardware.Sensor;
22 import android.hardware.SensorEvent;
23 import android.hardware.SensorEventListener;
24 import android.hardware.SensorManager;
25 import android.preference.PreferenceManager;
27 import cz.cvut.fel.dce.barcodescanner.camera.CameraManager;
28 import cz.cvut.fel.dce.barcodescanner.camera.FrontLightMode;
31 * Detects ambient light and switches on the front light when very dark, and off again when sufficiently light.
34 * @author Nikolaus Huber
36 final class AmbientLightManager implements SensorEventListener {
38 private static final float TOO_DARK_LUX = 45.0f;
39 private static final float BRIGHT_ENOUGH_LUX = 450.0f;
41 private final Context context;
42 private CameraManager cameraManager;
43 private Sensor lightSensor;
45 AmbientLightManager(Context context) {
46 this.context = context;
49 void start(CameraManager cameraManager) {
50 this.cameraManager = cameraManager;
51 SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
52 if (FrontLightMode.readPref(sharedPrefs) == FrontLightMode.AUTO) {
53 SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
54 lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
55 if (lightSensor != null) {
56 sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL);
62 if (lightSensor != null) {
63 SensorManager sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
64 sensorManager.unregisterListener(this);
71 public void onSensorChanged(SensorEvent sensorEvent) {
72 float ambientLightLux = sensorEvent.values[0];
73 if (cameraManager != null) {
74 if (ambientLightLux <= TOO_DARK_LUX) {
75 cameraManager.setTorch(true);
76 } else if (ambientLightLux >= BRIGHT_ENOUGH_LUX) {
77 cameraManager.setTorch(false);
83 public void onAccuracyChanged(Sensor sensor, int accuracy) {