繁体   English   中英

为什么我的Android警报管理器立即触发?

[英]Why is my android alarm manager firing instantly?

我正在按照示例代码每10秒发送一次更新通知。 代码如下,该代码位于AppWidgetProviderUpdateService中。 如果我放一个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);

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

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

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

解:

cal.add(Calendar.DATE, 1);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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