耗电量的优化
耗电量:CPU后台运行,屏幕常亮,最耗电量 |
优化:在ScreenOff时,停止看门狗服务,ScreenOn时,开启看门狗服务 |
1)服务开启 // 服务开启时
@Override
public void onCreate() {
super.onCreate(); tempNoProtectAppPackageName = new ArrayList<String>(); // 4)注册屏幕解锁时的广播接收者
screenOnReceiver = new ScreenOnReceiver();
IntentFilter screenOnFilter = new IntentFilter();
screenOnFilter.addAction(Intent.ACTION_SCREEN_ON);// 屏幕解锁广播
registerReceiver(screenOnReceiver, screenOnFilter);
// 3)注册屏幕锁屏时的广播接收者
screenOffReceiver = new ScreenOffReceiver();
IntentFilter screenOffFilter = new IntentFilter();
screenOffFilter.addAction(Intent.ACTION_SCREEN_OFF);// 屏幕锁屏广播
registerReceiver(screenOffReceiver, screenOffFilter); // 2)注册接收自定义的广播事件
noProtectReceiver = new CancelProtectApplicationReceiver();
IntentFilter cancelProtectFilter = new IntentFilter();
cancelProtectFilter.addAction("cn.zengfansheng.cancel");
registerReceiver(noProtectReceiver, cancelProtectFilter); // 1)获取ActivityManager管理者,进行开启看门狗服务
activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
appLockDao = new AppLockDao(getApplicationContext());
intent = new Intent(getApplicationContext(),EnterPasswordActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 外部开启Activity,一定要加上
// 看门狗需要不停的监视后台正在运行的应用程序.
startWatchDogInThread();
}
// 服务停止时
@Override
public void onDestroy() {
super.onDestroy(); // 1、销毁时,服务不在运行
flag = false; // 2、服务销毁时,取消自定义广播的事件-取消应用保护的注册
unregisterReceiver(noProtectReceiver);
noProtectReceiver = null; // 3、服务销毁时,取消屏幕锁屏广播事件的注册
unregisterReceiver(screenOffReceiver);
screenOffReceiver = null; // 3、服务销毁时,取消屏幕解锁广播事件的注册
unregisterReceiver(screenOnReceiver);
screenOnReceiver = null;
}3)屏幕解锁和锁屏广播接收者 /**
* 3、屏幕解锁时的广播接收者,解锁时,开启保护
* @author hacket
*/
private class ScreenOnReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (!flag) {// 如果看门狗没有启动,开启看门服务
startWatchDogInThread();
Log.i(TAG, "屏幕解锁,开启看门狗服务~~~");
}
}
}
/**
* 2、屏幕锁屏时的广播接收者,锁屏时,取消临时保护,停止保护
* @author hacket
*/
private class ScreenOffReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// 屏幕锁屏时,将临时不受保护的List集合给清空
if (tempNoProtectAppPackageName != null) {
tempNoProtectAppPackageName.clear();
}
if (flag) {// 如果看门狗运行时,flag为true时,停止看门狗服务
flag = false;
Log.i(TAG, "锁屏,停止看门狗服务~~~");
}
}
}
|
|