simone_s1994 simone_s1994 - 5 months ago 43
Android Question

Android | setAlartm every day at the same hour | not working

In my Android app, I would to launch a command each day at 3 a.m. and I use

AlarmManager
and
setRepeating
. When the app start, I do this:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 3);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
Intent intent = new Intent(context, MyBroadcast.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);


And this is MyBroadcast:

public class MyBroadcast extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("ALARM","Alarm worked.");
}
}


Buy, instead run the command at 3, the app run the command immediately. Why?

Answer

When an alarm is set to a passed date it will trigger immediately, if you don't want that you can create some logic to only start it today if the current time is before 3AM, something like this would work:

    Calendar now = Calendar.getInstance();
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.HOUR_OF_DAY, 3);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    Intent intent = new Intent(context, MyBroadcast.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (now.before(cal)) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    } 
    else {
        cal.set(Calendar.DAY_OF_YEAR, now.get(Calendar.DAY_OF_YEAR) +1);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);   
    }

We created another calendar to use as a reference to the current time, and check if we are before 3AM, if not then only call the alarm a day after.

Comments