13

我正在按照示例代码每 10 秒发送一次更新通知。代码如下,它位于一个UpdateServicefor 中AppWidgetProvider。如果我放了一个,Thread.sleep(10*1000);我可以看到我的服务循环的预期行为。我显然有一些根本性的错误会立即触发。它应该是PendingIntent一个警报,它将向我的听众广播更新。

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 device awake for this update
AlarmManager alarmManager = (AlarmManager)getBaseContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 
    nextUpdate, pendingIntent);
4

3 回答 3

22

AlarmManager.setRepeating 被定义为public void setRepeating (int type, long triggerAtTime, long interval, PendingIntent operation)第二个参数是它应该第一次被调用的时间。你告诉它从SystemClock.elapsedRealtime()现在开始。

于 2010-07-29T02:10:34.560 回答
16

您是在告诉setRepeating()您希望第一个警报立即响起 ( SystemClock.elapsedRealtime())。如果您希望第一个警报在其他时间响起,请添加偏移量 ( SystemClock.elapsedRealtime()+nextUpdate)。

于 2010-07-29T02:10:52.097 回答
6

如果您正在为过去时间创建 PendingIntent 警报,它将立即被触发。示例 - 为今天上午 8 点安排警报,但在上午 11 点左右执行代码将立即触发。

解决方案:

cal.add(Calendar.DATE, 1);

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

这将在第二天的指定时间(即早上 8 点)触发事件;

于 2014-07-04T12:39:54.427 回答