Search code examples
androidbroadcastreceiveralarmmanagerandroid-pendingintent

Is it possible to get the time of a specific alarm?


I'm working on an event planner for Android (learning purposes), and want each event to have it's own reminder. I've got the alarms working and they successfully trigger and know how to check if the alarms exist, but I'm unable to find out how to get the time for each alarm.

I've managed to identify if the alarm exists using:

    Intent i = new Intent(getApplicationContext(), NotificationReceiver.class);
    pIntent = PendingIntent.getBroadcast(getApplicationContext(), (int) id, i, PendingIntent.FLAG_NO_CREATE);

And I've tried using

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Calendar test = Calendar.getInstance();
    test.setTimeInMillis(am.getNextAlarmClock().getTriggerTime());
    Log.d(TAG, "getReminder: TRIGGER: " + test.getTime());

But the time displayed there doesn't even match any of my alarms when testing. Also this doesn't allow me to identify which event the alarm belongs to anyway.

This is where I create the reminders.

public void makeReminder(String event, long reminder){
    Log.d(TAG, "makeReminder: Started");

    Intent i = new Intent (getApplicationContext(), NotificationReceiver.class);
    i.putExtra("id", event); // eventID
    i.putExtra("reminder", reminder); // reminderKey
    i.putExtra("reminderTime", reminderCal.getTimeInMillis()); // actual time for the reminder
    i.putExtra("message", "You have an upcoming event on " + dateTimeFormat.format(startCal.getTime()));
    i.putExtra("name", eventName);
    i.putExtra("channel", "event");

    PendingIntent nIntent = (PendingIntent) PendingIntent.getBroadcast(
            getApplicationContext(),
            (int)reminder, i,
            PendingIntent.FLAG_CANCEL_CURRENT
    );

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, reminderCal.getTimeInMillis(), nIntent);

    Log.d(TAG, "makeReminder: reminder set for " + reminderCal.getTime());
    Log.d(TAG, "makeReminder: reminderID: " + reminder);

}

I'm not sure how to proceed to get the time, but I'm hoping that it would be possible to get the triggertime with the reminderKey or alternatively fetching the reminderTime from the intent before the event actually gets triggered. The point is for users to see if there's an alarm set, when it is and then I know how to cancel or change the alarm. Just can't find a good way of displaying it.

Hopefully something that's simple to achieve, that I've overlooked :/ but can't seem to solve this.


Solution

  • You can't get this information from AlarmManager. If you need this information, you will need to save it in some persistent storage (SQLite database, SharedPreferences, File, etc.) and manage it yourself.