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.