开发者

Why is my android alarm manager firing instantly?

I am following sample code for sending an update notification every 10'seconds. The code follows and it is in an UpdateService for an AppWidgetProvider. If I put a Thread.sleep(10*1000); I can see the expected behavior of my servicing loop. I obviously have something fundamentally wrong that is triggering immediately. It is supposed to be a PendingIntent of an alarm that will broadcast update to my listener.

long nextUpdate = 10*1000;
Log.d(TAG, "Requesting next update in " + nextUpdate + " msec." );

Intent updateIntent = new Intent(ACTION_UPDATE_ALL);
updateIntent.setClass(this, UpdateService.class);

PendingIntent pendingIntent = PendingIntent.getService(this, 0, updateIntent, 0);

// Schedule alarm, and force the devi开发者_JAVA技巧ce awake for this update
AlarmManager alarmManager = (AlarmManager)getBaseContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 
    nextUpdate, pendingIntent);


AlarmManager.setRepeating is defined as public void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation) The 2nd argument is when it should be first called. You're telling it to start at SystemClock.elapsedRealtime(), which is now.


You are telling setRepeating() that you want the first alarm to go off immediately (SystemClock.elapsedRealtime()). If you want the first alarm to go off some other time, add an offset (SystemClock.elapsedRealtime()+nextUpdate).


If you are creating PendingIntent of an alarm for past time it will be fired immediately. Example - Schedule alarm for today 8AM but executing code around 11AM will fire immediately.

Solution:

cal.add(Calendar.DATE, 1);

long delay = 24 * 60 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), delay,pendingIntent);` 

This will fire the event on next day at specified time (i.e 8AM);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜