android(五)----使用WakeLock使Android应用程序保持后台唤醒

   在使用一些产品列如微信、QQ之类的,如果有新消息来时,手机屏幕即使在锁屏状态下也会亮起并提示声音,这时用户就知道有新消息来临了。

但是,一般情况下手机锁屏后,Android系统为了省电以及减少CPU消耗,在一段时间后会使系统进入休眠状态,这时,Android系统中CPU会保持在

一个相对较低的功耗状态。针对前面的例子,收到新消息必定有网络请求,而网络请求是消耗CPU的操作,那么如何在锁屏状态乃至系统进入休眠后,

仍然保持系统的网络状态以及通过程序唤醒手机呢?答案就是Android中的WakeLock机制。

1.WakeLock--------------A wake lock is a mechanism to indicate that your application needs to have the device stay on.

PowerManager pm = (PowerManager)mContext.getSystemService(
                                          Context.POWER_SERVICE);
 PowerManager.WakeLock wl = pm.newWakeLock(
                                      PowerManager.SCREEN_DIM_WAKE_LOCK
                                      | PowerManager.ON_AFTER_RELEASE,
                                      TAG);
 wl.acquire();
 // ... do work...
 wl.release();

2.定制wakeLock行为

public PowerManager.WakeLock newWakeLock (int levelAndFlags, String tag)

evelAndFlags Combination of wake lock level and flag values defining the requested behavior of the WakeLock.
tag Your class name (or other tag) for debugging purposes.
Flag ValueCPUScreenKeyboard
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

*If you hold a partial wake lock, the CPU will continue to run, regardless of any display timeouts or the state of the screen and even after the user presses the power button. In all other wake locks, the CPU will run, but the user can still put the device to sleep using the power button.

原文地址:https://www.cnblogs.com/yuyutianxia/p/3294608.html