当用户更改android系统时间时,我想在Preferences中存储一个布尔值 . 因此,我将广播操作ACTION_TIME_CHANGED添加到清单:
<receiver android:name="test.TimeChangedReceiver">
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
<action android:name="android.intent.action.TIMEZONE_CHANGED" />
</intent-filter>
</receiver>
TimeChangedReceiver扩展了BroadcastReceiver并覆盖onReceive() . 在这个类中,将存储布尔值并显示通知 .
public class TimeChangedReceiver extends BroadcastReceiver {
private static final String TAG = "TimeChangedReceiver";
public TimeChangedReceiver() {
super();
}
@Override
public void onReceive(Context context, Intent intent) {
// store boolean to SharedPreferences
PreferenceUtils.getInstance().storeBoolean(true, PreferenceUtils.CHECK_LICENSE);
// build notification
int icon = android.R.drawable.ic_dialog_alert;
String title = "changed time";
String text = "user changed time";
long when = System.currentTimeMillis();
String timezone = intent.getStringExtra("time-zone");
Notification notification = new Notification(icon, title, when);
NotificationManager mgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notification_id = (int) System.currentTimeMillis();
Intent notificationIntent = new Intent(context, MainView.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notificationIntent.putExtra("time-zone", timezone);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT );
notification.setLatestEventInfo(context, title, text, contentIntent);
mgr.notify(notification_id, notification);
}
}
一切正常,直到应用程序关闭 - 不再在后台运行 .
这里说:
How can I receive the broadcast anyway and store the boolean?
我不需要看通知 .
2 回答
您的观察是正确的,并被认为是正常行为 . 通过系统设置完成"force stop"后,即使您在AndroidManifest.xml中声明了消息,
BroadcastReceiver
也将不再收到消息 . 通过执行"force stop",您基本上可以指示系统:"stop this app now and don't let it run again" . 这是一个管理操作,因此只能从系统设置访问 . 这有道理不是吗?新安装的应用程序也是如此 . 在它至少启动一次之前,它不会收到任何广播意图 .这就是Android系统的设计方式 . 你无法对付它 .
在"force stop"之后,您的应用程序(或其中一个组件)必须至少再次由用户手动(重新)启动 . 在这种情况下,即使在完全重新启动系统之后,AndroidManifest.xml中声明的接收器也会按预期接收广播意图 .
你不应该混淆“强制停止”与系统破坏你的应用程序的情况(例如,由于缺乏记忆) . 这些不一样,因为“强制停止”会为您的应用设置一个永久性标志,以防止它再次运行 .
来自docs:
然后
所以我猜你需要实现一个注册接收器的服务,以确保接收者的进程具有高优先级,从而保持运行 .