Search code examples
androidalarmmanagerandroid-pendingintentandroid-alarms

Android Alarm Manager Start time


I have this code, but the Alarm won't start from the beginning of time. I want myReceiver to start from the start of minutes and also repeat it from start of times . How can I achieve that?

PendingIntent pendingIntent3;
AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);


Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, 0);


manager.setRepeating(AlarmManager.ELAPSED_REALTIME  _WAKEUP,
                SystemClock.currentThreadTimeMillis(),
                1*60*1000, pendingIntent3);

Solution

  • Use below code to set repeating alarm:

    Intent alarmIntent3 = new Intent(getBaseContext(), myReceiver.class);
    PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getBaseContext(), 0, alarmIntent3, PendingIntent.FLAG_UPDATE_CURRENT);
    
    // Current time
    Calendar calendarNotifiedTime = Calendar.getInstance();
    calendarNotifiedTime.setTimeInMillis(System.currentTimeMillis());
    calendarNotifiedTime.set(Calendar.SECOND, 0);
    
    // Set alarm
    AlarmManager manager =(AlarmManager) getSystemService(Context.ALARM_SERVICE);
    manager.setRepeating(AlarmManager.RTC_WAKEUP, calendarNotifiedTime.getTimeInMillis(), 1*60*1000, pendingIntent3);
    

    Make sure you have declared myReceiver BroadcastReceiver in your AndroidManifest.xml.