Search code examples
androidalarmmanagerandroid-alarmsandroid-workmanager

android - set Alarm just once - AlarmManager vs WorkManager?


on button clicked, I want to set an alarm that sounds and shows a custom dialog after one hour. If this dialog is not closed, I need to show the same dialog after 15 minutes. I have checked AlarmManager and WorkManager but I do not know which one to use. I have read AlarmManager is better in this cases when needed to trigger alarms at specific time, but haven't seen anything about scheduling alarms just once (what I am interested in and I do not know how to do it), I have only read about scheduling repeating alarms.

Any advice?


Solution

  • You can set an alarm just once as shown here. This will schedule an alarm for 15 minutes. In case of one hour you can adjust accordingly.

    private PendingIntent alarmIntent;
    
    alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() +
            15 * 60 * 1000, alarmIntent);