80锁屏清理进程(重点)
锁屏清理进程是一个比较有用的功能,可以为用户节省很多的电量,锁屏清理进程也比定时清理进程优点多。说下思路:
判断用户是否锁屏需要注册一个广播接收者去监听,当然这个广播接收者放在服务里面比较好,试想如果放在Activity里面,当Activity执行onDestory()的时候,广播接收者就没了。而且这个广播接受者必须是代码注册。
package com.ustc.mobilemanager.service; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.util.Log; public class AutoCleanService extends Service { public static final String TAG = "AutoCleanService"; private ScreenOffReceiver receiver; private ActivityManager am; @Override public void onCreate() { am = (ActivityManager) getSystemService(ACTIVITY_SERVICE); receiver = new ScreenOffReceiver(); IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF); registerReceiver(receiver, filter); super.onCreate(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { unregisterReceiver(receiver); receiver = null; super.onDestroy(); } private class ScreenOffReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.i(TAG, "屏幕锁屏啦!"); List<RunningAppProcessInfo> infos = am.getRunningAppProcesses(); for (RunningAppProcessInfo info : infos) { am.killBackgroundProcesses(info.processName); } } } }
CheckBox的点击事件:
cb_auto_clean.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // 锁屏的广播事件是一个特殊的广播事件,在清单文件配置广播接受者是不会生效的 // 锁屏的广播接受者必须在代码中注册(写在服务里) Intent intent = new Intent(TaskSettingActivity.this, AutoCleanService.class); if (isChecked) { startService(intent); } else { stopService(intent); } } });
CheckBox的状态与服务的生存期有关:
@Override protected void onStart() { boolean running = ServiceUtils.isServiceRunning(this, "com.ustc.mobilemanager.service.AutoCleanService"); cb_auto_clean.setChecked(running); super.onStart(); }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。