锁屏清理进程是一个比较有用的功能,可以为用户节省很多的电量,锁屏清理进程也比定时清理进程优点多。说下思路:
判断用户是否锁屏需要注册一个广播接收者去监听,当然这个广播接收者放在服务里面比较好,试想如果放在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(); }
时间: 2024-12-02 20:59:45