android的PowerManager和PowerManager.WakeLock

PowerManager.WakeLock

  PowerManager.WakerLock是我分析Standup Timer源代码时发现的一个小知识点,Standup Timer 用WakeLock保证程序运行时保持手机屏幕的恒亮(程序虽小但也作得至关的细心,考虑的很周到)。PowerManager 和PowerManager.WakerLock7用于对Android设备的电源进行管理。
   PowerManager:This class gives you control of the power state of the device.
   PowerManager.WakeLock: lets you say that you need to have the device on.
  Android中经过各类Lock锁对电源进行控制,须要注意的是加锁和解锁必须成对出现。先上一段Standup Timer里的代码而后进行说明。
复制代码
代码
private void acquireWakeLock() {
if (wakeLock == null ) {
    Logger.d(
" Acquiring wake lock " );
    PowerManager pm
= (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock
= pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this .getClass().getCanonicalName());
    wakeLock.acquire();
    }
}


private void releaseWakeLock() {
if (wakeLock != null && wakeLock.isHeld()) {
    wakeLock.release();
    wakeLock
= null ;
    }
}
 

 

acquireWakeLock()方法中获取了 SCREEN_DIM_WAKE_LOCK锁,该锁使 CPU 保持运转,屏幕保持亮度(能够变灰)。这个函数在Activity的 onResume中被调用。releaseWakeLock()方法则是释放该锁。它在Activity的 onPause中被调用。利用Activiy的生命周期,巧妙的让 acquire()和release()成对出现。
 
@Override
protected void onResume()
{
super .onResume();
// 获取锁,保持屏幕亮度
acquireWakeLock();
startTimer();
}
 
代码
protected void onPause()
{
super .onPause();
synchronized ( this ) {
cancelTimer();
releaseWakeLock();

if (finished) {
clearState();
}
else {
saveState();
}
}
}

 

PowerManager和WakeLock的操做步骤
  1.   PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);经过 Context.getSystemService().方法获取PowerManager实例。
  2.   而后经过PowerManager的newWakeLock((int flags, String tag)来生成WakeLock实例。int Flags指示要获取哪一种WakeLock,不一样的Lock对cpu 、屏幕、键盘灯有不一样影响。
  3.   获取WakeLock实例后经过acquire()获取相应的锁,而后进行其余业务逻辑的操做,最后使用release()释放(释放是必须的)。

关于int flags

  各类锁的类型对CPU 、屏幕、键盘的影响:

PARTIAL_WAKE_LOCK:保持CPU 运转,屏幕和键盘灯有多是关闭的。 html

SCREEN_DIM_WAKE_LOCK:保持CPU 运转,容许保持屏幕显示但有多是灰的,容许关闭键盘灯 java

SCREEN_BRIGHT_WAKE_LOCK:保持CPU 运转,容许保持屏幕高亮显示,容许关闭键盘灯 android

FULL_WAKE_LOCK:保持CPU 运转,保持屏幕高亮显示,键盘灯也保持亮度 ide

ACQUIRE_CAUSES_WAKEUP:Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately, when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately. 函数

ON_AFTER_RELEASE:f this flag is set, the user activity timer will be reset when the WakeLock is released, causing the illumination to remain on a bit longer. This can be used to reduce flicker if you are cycling between wake lock conditions. ui

权限获取

要进行电源的操做须要在AndroidManifest.xml中声明该应用有设置电源管理的权限。
< uses-permission android:name ="android.permission.WAKE_LOCK" />
你可能还须要
< uses-permission android:name ="android.permission.DEVICE_POWER" />
另外WakeLock的设置是 Activiy 级别的,不是针对整个Application应用的。
相关文章
相关标签/搜索