Created
April 8, 2015 17:58
-
-
Save forceLain/52b8dce0f524884600b1 to your computer and use it in GitHub Desktop.
one threshold light sensor manager
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LightSensorManager implements SensorEventListener { | |
private enum Environment {DAY, NIGHT} | |
public interface EnvironmentChangedListener { | |
void onDayDetected(); | |
void onNightDetected(); | |
} | |
private static final int THRESHOLD_LUX = 50; | |
private static final String TAG = "LightSensorManager"; | |
private final SensorManager sensorManager; | |
private final Sensor lightSensor; | |
private EnvironmentChangedListener environmentChangedListener; | |
private Environment currentEnvironment; | |
public LightSensorManager(Context context) { | |
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); | |
lightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); // Сенсор освещённости | |
} | |
public void enable() { | |
if (lightSensor != null){ | |
sensorManager.registerListener(this, lightSensor, SensorManager.SENSOR_DELAY_NORMAL); | |
} else { | |
Log.w(TAG, "Light sensor in not supported"); | |
} | |
} | |
public void disable() { | |
sensorManager.unregisterListener(this); | |
} | |
public EnvironmentChangedListener getEnvironmentChangedListener() { | |
return environmentChangedListener; | |
} | |
public void setEnvironmentChangedListener(EnvironmentChangedListener environmentChangedListener) { | |
this.environmentChangedListener = environmentChangedListener; | |
} | |
@Override | |
public void onSensorChanged(SensorEvent event) { | |
float luxLevel = event.values[0]; | |
Environment oldEnvironment = currentEnvironment; | |
currentEnvironment = luxLevel < THRESHOLD_LUX ? Environment.NIGHT : Environment.DAY; | |
if (hasChanged(oldEnvironment, currentEnvironment)){ | |
callListener(currentEnvironment); | |
} | |
} | |
@Override | |
public void onAccuracyChanged(Sensor sensor, int accuracy) {} | |
private boolean hasChanged(Environment oldEnvironment, Environment newEnvironment) { | |
return oldEnvironment != newEnvironment; | |
} | |
private void callListener(Environment environment) { | |
if (environmentChangedListener == null || environment == null){ | |
return; | |
} | |
switch (environment) { | |
case DAY: | |
environmentChangedListener.onDayDetected(); | |
break; | |
case NIGHT: | |
environmentChangedListener.onNightDetected(); | |
break; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment