今天在看一个项目的源代码时,发现了这个电源管理和屏幕锁:PowerManager、wakelock。

其中在onStart()方法中获取wakelock,并且在onstop()中将这个lock释放掉。

protected void onStart() {

....

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "MediaCenterApplication");
wl.acquire();
wl.setReferenceCounted(false);

....

}

protected void onStop() {

....

wl.release();

....

}

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

关于int flags

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

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

SCREEN_DIM_WAKE_LOCK:保持CPU 运转,允许保持屏幕显示但有可能是灰的,允许关闭键盘灯

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

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

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.

权限获取

要进行电源的操作需要在AndroidManifest.xml中声明该应用有设置电源管理的权限。
                                    <                    uses-permission                     android:name                    ="android.permission.WAKE_LOCK"                                         />                     你可能还需要                     <                    uses-permission                     android:name                    ="android.permission.DEVICE_POWER"                                         />                

另外WakeLock的设置是 Activiy 级别的,不是针对整个Application应用的。


更多相关文章

  1. Android标题栏上添加多个Menu按钮的实例
  2. Android(安卓)的Activity.getWindowManager().getDefaultDisplay
  3. Android内容提供器-读取通讯录
  4. Android(安卓)dialog——点击「屏幕」或者「返回键」不消失
  5. [Android实例] android中进行https连接的方式的详解 (转发)
  6. 屏幕适配问题
  7. Android桌面小组件:最简例子
  8. 时间和日期选择器DatePicker和TimePicker的使用
  9. Android解锁屏幕失效问题

随机推荐

  1. Sql查询性能限制行数之间的差异
  2. PHP分页算法详解
  3. mysql忘记帐号密码 解决办法。
  4. window 下 mysql 启动 二进制日志文件
  5. 获取项目列表的更好方法:缓存序列化数据与
  6. mysql 在当前表中对某一列数据进行计算后
  7. MySQL5.6基于GTID的主从复制
  8. [MySQL高级](七) MySQL主从复制实战
  9. 一分钟完成MySQL5.7安装部署
  10. 在时间戳和相应的值中选择每天的最后一个