重复警报 BroadcastReceiver Intent 字符串附加信息未更新

Recurring alarm BroadcastReceiver Intent string extras not getting updated

我有以下 class 来检查我的警报是否在我安排的确切时间触发或是否不同。

我将从 MainActivity 调用 BroadCast Reciever 中的 SetAlarm 方法。连续的警报将由接收器自己通过将当前时间设置为其新的字符串额外来设置。

除了 Intent 字符串额外的问题没有得到更新之外,警报工作正常。无论我在 setAlarm 方法中设置了什么,ScheduledTime 将始终保持初始值。

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Date currentTime = new Date(); 
        String ScheduledTime = ""; 
        if (null != intent) { //Null Checking
            ScheduledTime =   intent.getStringExtra("ScheduledTime");
            //intent.removeExtra("ScheduledTime");
        }
        String message  = "Current Time" + currentTime + ",  Scheduled Time was: " + ScheduledTime ; 
        //Show Notification 

        long alarmMillis =(10*60*1000) ; //Set Alarm after 10 minutes
        Long newTimeInMillis = System.currentTimeMillis() +  alarmMillis;
        currentTime.setTime(newTimeInMillis );
        setAlarm(context, newTimeInMillis , currentTime.toString());
    }

     public void setAlarm(Context context, Long timeMillis, String ScheduledTime)
    {
        AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(context, AlarmReceiver.class);
        i.putExtra("ScheduledTime", ScheduledTime);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
        am.setExact(AlarmManager.RTC_WAKEUP, timeMillis, pi);
    }
}

来自Android official site

public static final int FLAG_UPDATE_CURRENT

Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent. For use with getActivity(Context, int, Intent, int), getBroadcast(Context, int, Intent, int), and getService(Context, int, Intent, int).

This can be used if you are creating intents where only the extras change, and don't care that any entities that received your previous PendingIntent will be able to launch it with your new extras even if they are not explicitly given to it.

所以更改您的代码

PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);