无法正确释放PowerManager.WakeLock

时间:2015-08-04 11:23:31

标签: android android-sensors

我在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。提前谢谢。

1 个答案:

答案 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();
}