简体   繁体   中英

Android Alarm manager to run a task on a specific time

I have read many articles, but non seems to work for me!

I have to schedule a repeating task with AlarmManager for everyday at 7:15. The following method is set in an activity and registered a broadcast receiver for it!

private void setTask(Context context) {

    Calendar updateTime = Calendar.getInstance();
    updateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
    updateTime.set(Calendar.HOUR_OF_DAY, 7);
    updateTime.set(Calendar.MINUTE, 15);

    Intent intent = new Intent(context, NotifyUpdate.class);
    PendingIntent fireAlarm = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarms.setRepeating(alarms.RTC_WAKEUP, updateTime.getTimeInMillis(), alarms.INTERVAL_DAY, fireAlarm);
}

The problem is when I run the app the method gets executed immediately regardless of the time set, but not executing at (7:15).

Any Idea?

Try this before setting alarm

Calendar now = Calendar.getInstance();
if (updateTime.before(now)) {
            updateTime.add(Calendar.DAY_OF_MONTH, 1);  // if its in the past increment
}

alarms.setRepeating(alarms.RTC_WAKEUP, updateTime.getTimeInMillis(), alarms.INTERVAL_DAY, fireAlarm);

You said that you have immediate triggering not depending on time. It's happening because updateTime-object references at time in the past, so the goal is to set an alarm to 7:15 in the future. This will help to avoid immediate triggering.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM