【发布时间】:2015-12-31 15:16:29
【问题描述】:
我正在使用此代码来检测屏幕何时被锁定并调用 toast,每次屏幕被锁定时它都会起作用。但是,每当我退出应用程序时,它就会停止工作。仅当应用打开时才有效。
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);
List<RunningAppProcessInfo> procInfos = 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);
清单
<receiver android:name=".BatterySaverUltraReceiver" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
我从here得到这个代码
【问题讨论】:
-
是因为 unregisterReceiver 你的广播接收器在 onPause、onStop 或 onDestory 方法中?
标签: android