Android: PowerManager.WakeLock

Android中通过各种Lock锁对电源进行控制:

PARTIAL_WAKE_LOCK SCREEN_DIM_WAKE_LOCK SCREEN_BRIGHT_WAKE_LOCK FULL_WAKE_LOCK Flag Value CPU Screen Keyboard
On* Off Off
On Dim Off
On Bright Off
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();

你可能感兴趣的:(android)