Intent extras don't seem to refresh

醉酒当歌 提交于 2020-01-06 08:14:30

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/19867051/intent-extras-dont-seem-to-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!