即使使用 FLAG_UPDATE_CURRENT

问题描述

尝试定期收到通知

使用如下所示的 AlarmManager 创建一个重复的挂起 Intent 并添加可序列化的额外内容(newHabit 是我自己的类的一个实例)。 newHabit.getNotificationID() 基于实例创建时的时间戳返回一个 int 值,因此不太可能这是在其他地方使用的意图

Intent notifyIntent = new Intent(this,ReminderReceiver.class);
                    // tried this
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("habit",newHabit);

                    notifyIntent.putExtras(bundle);
                    //then this
                    notifyIntent.putExtra("habit",newHabit);

                    PendingIntent pendingIntent = PendingIntent.getbroadcast( this,newHabit.getNotificationID(),notifyIntent,PendingIntent.FLAG_UPDATE_CURRENT);

                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR_OF_DAY,reminderTime.getHour());
                    calendar.set(Calendar.MINUTE,reminderTime.getMinute());
                    calendar.set(Calendar.SECOND,0);

                    AlarmManager alarmManager =
                            (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
                    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

然后在接收 broadcastReciever 时使用以下代码获取额外内容

        Habit habit = null;

        Bundle extras = intent.getExtras();
        if (extras != null) {
            habit = (Habit) extras.get("habit");

        }

这在 API 24 之前都可以正常工作,之后接收器中的习惯始终为空。

解决方法

基于此答案:Pass Serializable Object to Pending Intent,使用 AlarmManager 和传递可序列化对象存在问题

与上述问题的第二个答案一样,将 Serializable 对象转换为 byte[] 有效