即使使用正确的参数,Android AlarmManager也会立即触发?
问题描述:
我从我主要Activity的onCreate设置AlamManager。即使使用正确的参数,Android AlarmManager也会立即触发?
这里是方法
public void scheduleAdsUpdateAlarm() {
long THEE_HOURS = 3 * 60 * 60 * 1000;
long THREE_MINUTES= 3*60*1000;
long UNTIL_FIRST_TRIGGER = THREE_MINUTES;
// Construct an intent that will execute the AlarmReceiver
Intent intent = new Intent(getApplicationContext(), AdsUpdateAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(this, AdsUpdateAlarmReceiver.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
if(alarm != null){
alarm.cancel(pIntent);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, UNTIL_FIRST_TRIGGER,
THREE_MINUTES, pIntent);
}
}
正如你可以看到报警设置三分钟与初始启动每三小时运行。
问题是当onCreate和下面的警报设置被调用时警报立即熄灭。我不明白我在做什么错了?
答
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, UNTIL_FIRST_TRIGGER,
THREE_MINUTES, pIntent);
应改为:
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + UNTIL_FIRST_TRIGGER, THREE_MINUTES, pIntent);
由于alarm.setInexactRepeating的第二个参数是不从现在值的毫秒但实际时间值。