2017-07-07 70 views
2

有它应该在指定的精确时间使用AlarmManager(次日7:00)触发一个动作代码:AlarmManager不会醒来电话

val manager = getSystemService(Context.ALARM_SERVICE) as AlarmManager 
val intent = Intent(this, FooIntentService::class.java) 
val pendingIntent = PendingIntent.getService(this, 0, intent, 0) 

// Set alarm 
val calendar = Calendar.getInstance() 
calendar.timeInMillis = System.currentTimeMillis() 
calendar.set(Calendar.HOUR_OF_DAY, 7) 
calendar.set(Calendar.MINUTE, 0) 

// Set tomorrow 
calendar.add(Calendar.DATE, 1) 

manager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent) 

我已经测试这代码从现在起最多5分钟触发事件,关闭应用程序(关闭所有应用程序)并将其置于睡眠状态(按住“保持”按钮) - 并且它可以正常工作。然而,当我在明天早上7点设置时间(距离现在5分钟以上)时,它将永远不会触发,直到我解除阻止(手动唤醒)为止。此刻我醒了过来 - 马上触发了这个动作。


问题:是我在我的情况设置计划事件提供正确的示例代码?

+2

也许打瞌睡:https://stackoverflow.com/questions/35629268/alarm-manager-issue-in-android-6-0-doze-mode – Alex

+0

@Alex谢谢你的分享,这可能是回答。我将调查并在此主题中提供结果。 – Oleg

+1

看看下面的答案的第二部分:https://stackoverflow.com/a/39739886/3363481 – earthw0rmjim

回答

2

注意:从API 19(KITKAT)开始,报警传送并不准确:操作系统将切换报警以最大限度地减少唤醒和电池使用。有新的API支持需要严格交付保证的应用程序;请参阅setWindow(int,long,long,PendingIntent)和setExact(int,long,PendingIntent)。 targetSdkVersion早于API 19的应用程序将继续看到之前的行为,即所有报警在请求时都准确传送。

documentation

基本上,报警旨在不准确,以尽量减少唤醒和电池使用。您可以用setExact替换set,那么它应该按照您的要求工作。

manager.setExact(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent);