Search code examples
androidalarmmanager

Alarm Manager Android


private void startAlarm() {

    AlarmManager alarmMgr;
    PendingIntent alarmIntent;

    alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
    alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);


    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 52);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
            1000 * 60 * 20, alarmIntent);

}

startAlarm() method is in the MainActivity class.

The following code should display a toast (declared in onReceive() method of the AlarmReceiver class) at 23:52 and every 20 minutes thereafter

AlarmReceiver extends BroadcastReceiver.

The code compiles without errors but for some reason it is not displaying the toast.

NOTE : The code worked fine with ELAPSED_REALTIME_WAKEUP. I am having problem with RTC_WAKEUP only. So everything else has to be correct. There is something wrong inside the startAlarm() method only.


Solution

  • I have tried your code with some modification as below .

        private void startAlarm() {
    
            AlarmManager alarmMgr;
            PendingIntent alarmIntent;
    
            alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
            alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
    
    
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 2);
    
            alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                    1000 * 20, alarmIntent);
        }
    

    This code works fine with AlarmManager.RTC_WAKEUP. If it does not work for you, please reboot your device after installing it. After reboot completed, start your app. Then it should fire the alarm and every 20 sec interval the alarm fires repeatedly.

    You can also check the difference between RTC_WAKEUP and ELAPSED_REALTIME_WAKEUP. From android docs, elapsedRealtime means, Returns milliseconds since boot, including time spent in sleep and RTC means, time in System.currentTimeMillis() (wall clock time in UTC).