【问题标题】:Set alarms after rebooting Phone重启手机后设置闹钟
【发布时间】:2014-10-18 13:44:48
【问题描述】:

我有一个小问题。我使用 AlarmManager 在特定时间设置通知。我设置通知的时间存储在 SQLLite 数据库中。除了我重新启动手机的那一刻,它们都工作得很好。 alarmManager 当然会丢失它们的重复。

我想问在这种情况下最好的解决方案是什么?我在 MainActivity 中设置了 alarmManager,并在 BroadcastReceiver 中设置了通知,如下面的代码所示:

这是我从 MainActivity 中调用它的方式:

        Intent intent = new Intent(context, MyReceiver.class);
        intent.putExtra(EXTRA_TITLE, title);
        intent.putExtra(EXTRA_COUNT, count);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, count, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), WEEK_LENGTH_MS, pendingIntent);

这里是广播接收器的onReceive方法

  public void onReceive(Context context, Intent intent)
    {
        nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        CharSequence from = context.getString(R.string.app_name);
        CharSequence message = intent.getStringExtra(DayActivity.EXTRA_TITLE);
        Intent intentNotification = new Intent(context,DayActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(context, intent.getIntExtra(DayActivity.EXTRA_COUNT,0), intentNotification, 0);
        Notification notif = new Notification(R.drawable.notification_logo,context.getString(R.string.app_name), System.currentTimeMillis());
        notif.setLatestEventInfo(context, from, message, contentIntent);
        notif.defaults |= Notification.DEFAULT_LIGHTS;
        notif.flags |= Notification.FLAG_AUTO_CANCEL | Notification.FLAG_SHOW_LIGHTS;
        nm.notify(intent.getIntExtra(DayActivity.EXTRA_COUNT,0), notif);

    }

我正在为 BOOT_COMPLETED 事件声明 BroadcastReceiver,但它总是在我启动手机时只调用空通知,不再调用。

【问题讨论】:

    标签: android broadcastreceiver alarmmanager notificationmanager android-reboot


    【解决方案1】:

    我想问一下这种情况下最好的解决方案是什么?

    注册BOOT_COMPLETEDBroadcastReceiver 以在AlarmManager 上致电setRepeating() 以重新制定您的日程安排。

    我正在为 BOOT_COMPLETED 事件声明 BroadcastReceiver,但它总是在我启动手机时只调用空通知,不再调用。

    BOOT_COMPLETEDBroadcastReceiver 的目标应该是重新安排您的警报。您可能希望考虑使用单独的BroadcastReceiver,而不是用于警报事件本身的BroadcastReceiver

    【讨论】:

    • 所以你是说使用类似 OnBootReceiver 的东西我会得到时间并使用 alarmManager 调用第一个 BroadcastReceiver?
    • @JanOmacka:是的。欢迎您让一个BroadcastReceiver 处理这两个角色,但您需要区分启动事件和警报事件,例如通过检查传入Intent 的操作字符串。例如,this sample app 使用该方法,因为BOOT_COMPLETED 广播将有一个非null 操作字符串,而我在PendingIntentAlarmManager 中使用的显式Intent 将有一个null动作字符串。
    • 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 2014-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多