Android中,申请WakeLock可以让你的进程持续执行即使手机进入睡眠模式,比较实用的是比如后台有网络功能,可以保证操作持续进行.
需要权限
<uses-permission android:name="android.permission.WAKE_LOCK"/>
API
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 |
PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
//打开
wakeLock.acquire();
//关闭
if (wakeLock != null) {
wakeLock.release();
wakeLock = null;
}
另一种方法是
@Override
protected void onCreate(Bundle bundle) {
super .onCreate(bundel);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//or
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}