我正在使用此代码来检测屏幕何时被锁定并调用烤面包,每次屏幕锁定时它都能正常工作.但是,每当我退出应用程序时,它就会停止工作.它只适用于应用程序打开的情况.
public class BatterySaverLiteReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { Log.i("Check", "Screen went OFF"); Toast.makeText(context, "screen OFF", Toast.LENGTH_LONG).show(); task(context); } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { Log.i("Check", "Screen went ON"); Toast.makeText(context, "screen ON", Toast.LENGTH_LONG).show(); } } private void task(Context context) { // Process Killer and display all package names in toast ActivityManager actvityManager = (ActivityManager) context .getApplicationContext().getSystemService( context.getApplicationContext().ACTIVITY_SERVICE); ListprocInfos = actvityManager .getRunningAppProcesses(); for (int pnum = 0; pnum < procInfos.size(); pnum++) { actvityManager .killBackgroundProcesses(procInfos.get(pnum).processName); } } }
多数民众赞成如何注册我的接收器
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); mReceiver = new BatterySaverLiteReceiver(); registerReceiver(mReceiver, filter);
表现
我从这里得到了这个代码