Sam
Sam

Reputation: 1337

Use one alarm manager to cancel another

I am doing a reminder application. It will reminder for a duration at the interval of time. For example, remind every five minutes for an hour. In this case, I am trying to set two alarm. One is used to do the reminder for every five minutes, the other one is used to cancel the reminder alarm after one hour. Here is my codes.

private void createIntervalNotification(int reminder, int dhour, int dminute){ //reminder in min
    int interval = (reminder)*60*1000;
    AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+interval, interval, getPendingIntent(this,REMINDER_ID));

    int duration = (dhour*60 + dminute)*60*1000;
    am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+duration,getPendingIntent(this,CANCEL_REMINDER_ID));
}

private static PendingIntent getPendingIntent(Context ctxt, int id) {
    Intent intent1 = new Intent(ctxt, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(ctxt, id,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    return pendingIntent;
}

I have some questions to do this(Set reminder of 5 mins for duration of 1 hour).

1) Can I do this with my method? Use one alarm to cancel another?

2) Can both alarm share a broadcastReceiver? If yes, how to differentiate it is invoked by which alarm?

3) Is it any other method can do this?

Upvotes: 0

Views: 63

Answers (1)

Kuffs
Kuffs

Reputation: 35661

Cancelling an alarm is pretty much exactly the same as setting an alarm. You just call a different method to cancel on the AlarmManager than you do to create. Just make sure that the pending intent in the AlarmManager and the broadcast ID is identical.

Differentiate alarms by setting Extras on the Intent.

Upvotes: 0

Related Questions