Intent extras not removed/replaced

2019-05-16 08:23发布

问题:

I am setting an alarm on a button click.

The alarm is triggered with an intent.

This intent get an extra "int" to pass to the Broadcast Receiver.

The problem is that the intent's extra gets set once on the first click of the button and never changes on the other clicks:

Intent intent = new Intent(A.this, B.class);
intent.putExtra(WAKEUP_DURATION, wakeUpDuration);
PendingIntent sender = PendingIntent.getBroadcast(A.this, 0, intent, 0);

I tried removing it in the Broadcast Receiver, but no luck:

intent.removeExtra(A.WAKEUP_DURATION);

回答1:

Use FLAG_UPDATE_CURRENT when creating your PendingIntent to update the extras from a new Intent.



回答2:

Thanks! That did the trick. For those of you who would like to know the exact answer. The "FLAG_UPDATE_CURRENT" goes as the fourth argument in the method 'getBroadcast'. It should look like this:

PendingIntent sender = PendingIntent.getBroadcast(A.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);