Search code examples
androidandroid-intentandroid-broadcast

Intent extras don't seem to refresh


When I press the button it calls a method which gets user input and sets it to a variable, then that variable is put to an intent extra and sent to BroadcastReceiver which decides what to do depending on that value. It only works the first time, on all the next presses intent extra value isn't changed no matter if that variable value changes. It forever holds the value which is set at the first press. How to rewrite intent extra with a new value?

How I set the extra:

Intent intentForReceiver = new Intent(this, AlarmReceiver.class);
intentForReceiver.putExtra("checkBox1", checkBox1.isChecked());
        PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
intentForReceiver, 0);

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
    AlarmManager.INTERVAL_DAY, alarmIntent);

How I receive the extra on BroadcastReceiver and put it to the intent for service:

Intent intentForService = new Intent(context, CMService.class);
intent.putExtra("checkBox1", intentForReceiver.getExtras().getBoolean("checkBox1"));
context.startService(intentForService);

How I receive the extra on Service:

if(intentForService.getExtras().getBoolean("checkBox1")) {
...
} else {
...
}

So this is my code. If I uncheck the checkBox1 and press the button, it still does the job which should be done only if checkBox1.isChecked() is true, so it means this value stays true forever after the first press and doesn't update when I uncheck the checkBox1.


Solution

  • Before recreating your alarm, cancel the first one. To do this, you recreate your Intent and call cancel on the AlarmManager. For instance, I have a method in an Alarm class that cancels it for me before starting a new one

    // cancel existing logout alarm
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 
         REQUEST_CODE, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);     
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);
    

    Then recreate the PendingIntent and set the new AlarmManager

    This answer explains a little more