我在PowerManager.WakeLock
中使用Sensor.TYPE_LIGHT
Activity
。
它运作良好,但当我关闭/转到其他Activity
SensorEventListener
时,如果传感器更改,请保持打开/关闭屏幕。
代码示例
SensorManager mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
SensorEventListener
界面方法
@Override
public void onSensorChanged(SensorEvent event) {
float[] lux = event.values;
if (lux[0] <= 200) {
mWakeLock.acquire();
} else {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
}
}
SensorManager
听众
@Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mLightSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
@Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this, mLightSensor);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
}
那么如何正确释放和禁用WakeLock
。提前谢谢。
答案 0 :(得分:1)
我的错是使用SensorEventListener
。可能它是dublicate WakeLock.acquire()
并且每次都这样称呼它。关键是要在onCreate()
中获取并在onDestroy()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
mWakeLock.acquire();
}
@Override
protected void onDestroy() {
if (mWakeLock.isHeld()) {
mWakeLock.release();
}
super.onDestroy();
}