首页 文章

应用程序关闭时接收TIME_SET广播

提问于
浏览
3

当用户更改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 回答

  • 2

    一切正常,直到应用程序关闭 - 不再在后台运行 . 当我“强制停止”应用程序并在之后更改日期时,没有日志 .

    您的观察是正确的,并被认为是正常行为 . 通过系统设置完成"force stop"后,即使您在AndroidManifest.xml中声明了消息, BroadcastReceiver 也将不再收到消息 . 通过执行"force stop",您基本上可以指示系统:"stop this app now and don't let it run again" . 这是一个管理操作,因此只能从系统设置访问 . 这有道理不是吗?新安装的应用程序也是如此 . 在它至少启动一次之前,它不会收到任何广播意图 .

    这就是Android系统的设计方式 . 你无法对付它 .

    我怎么能接收广播并存储布尔值?

    在"force stop"之后,您的应用程序(或其中一个组件)必须至少再次由用户手动(重新)启动 . 在这种情况下,即使在完全重新启动系统之后,AndroidManifest.xml中声明的接收器也会按预期接收广播意图 .

    你不应该混淆“强制停止”与系统破坏你的应用程序的情况(例如,由于缺乏记忆) . 这些不一样,因为“强制停止”会为您的应用设置一个永久性标志,以防止它再次运行 .

  • 0

    来自docs

    当前正在执行BroadcastReceiver的进程(即,当前在其onReceive(Context,Intent)方法中运行代码)被认为是前台进程,除非在极端内存压力的情况下,系统将继续运行 .

    然后

    这意味着对于运行时间较长的操作,您通常会将一个Service与BroadcastReceiver结合使用,以便在整个操作期间保持包含进程处于活动状态 .

    所以我猜你需要实现一个注册接收器的服务,以确保接收者的进程具有高优先级,从而保持运行 .

相关问题