Android AlarmManager problem with setting & resett

2019-01-11 12:12发布

问题:

I use an Alarm to fetch data from server. I like to give user the option to start and stop the alarm. This means I have to check and see if alarm is already set. I found some code that tells me if the alarm is already set:

Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_NO_CREATE);
found = (P!=null);

if the Alarm is already set I cancel it but if it is not set then I set it (like a toggle)

Problem is this works only once. The first time the above code to check existing alarms will return null indicating no alarm but after I cancel the alarm once it returns a pointer to something but alarm is not running.

here is the code to set alarm

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, P); 

and here is the code to cancel an alarm:

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(P);

Am I to reset something after canceling an alarm to make it's PendingIntent go away.

回答1:

When canceling the AlarmManager do not use a PendingIntent with a flag of FLAG_CANCEL_CURRENT. Instead, cancel the PendingIntent explicitly after canceling the alarm:

am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent p = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
am.cancel(p);
p.cancel();