I'm working on the alarm app, and have trouble removing an existing alarm. I have to create the same pending intent to remove the alarm in the activity which lists all alarms in my app, but It doesn't work as I expected. I want to get the "Context" from the activity which I used to add an alarm.
Here is the code to add an alarm from ListAddActivity.
private void addAlarm()
{
final int ALARM_CODE = this.getAlarmCode(1);
final int HOUR_OF_DAY = vo.getHour1();
final int MINUTE = vo.getMinute1();
AlarmManager alarmManager = (AlarmManager) getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = CalendarCreator.getCalendar(HOUR_OF_DAY, MINUTE);
Intent intent = new Intent(ListAddActivity.this, PushMainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
ListAddActivity.this, ALARM_CODE, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
pendingIntent);
}
Here is the code to remove an scheduled alarm from ListMainActivity.
private void removeAlarm(int number)
{
final int alarmCode = AlarmCodeCreator.CreateNum(1, clickedPosition, 0);
System.out.println(alarmCode);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(),
PushMainActivity.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), alarmCode, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
As you can see, I made my own algorithm to create an alarmCode, so I can retrieve it, and had the same flag, too. However, getting the same "Context" is the one that I'm struggling with.
This has nothing to do with contexts. The intent you schedule was created with getActivity. That is a different kind of intent than the one created with getBroadcast. You cannot use the latter to cancel the former.
(Edited to add code)