Android中通过各种Lock锁对电源进行控制:
Flag Value |
CPU |
Screen |
Keyboard |
PARTIAL_WAKE_LOCK |
On*
Off
Off
SCREEN_DIM_WAKE_LOCK |
On
Dim
Off
SCREEN_BRIGHT_WAKE_LOCK |
On
Bright
Off
FULL_WAKE_LOCK |
On
Bright
Bright
private static PowerManager.WakeLock mWakeLock;
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
加锁:
mWakeLock.acquire();
解锁:
mWakeLock.release();
需要注意:
0. WakeLock是activity级的
1. 加锁/解锁必须成对出现
2. 可以多次加锁,同时解锁次数等于加锁次数才能完成解锁
3. 未加锁时进行解锁操作会抛出异常,程序挂掉
可以用下面的方法保证不多次加锁及未加锁时进行解锁:
if (!mWakeLock.isHeld())
mWakeLock.acquire();
if (mWakeLock.isHeld())
mWakeLock.release();