Android 上未执行警报
我有一个 Android 应用程序,我尝试在其中设置闹钟。我在活动中的代码:
fun setAlarm() {
alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, NotificationReceiver::class.java)
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager!!.set(AlarmManager.RTC_WAKEUP, /*calculateAlarmTime()*/1, pendingIntent)
Timber.i("setAlarm executed")
}
我设置了这个闹钟,调用 setAlarm 方法。这是我的NotificationReceiver类:
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Timber.i("onReceive called");
}
}
为什么我在logcat中只有“setAlarm执行”,而不是“onReceive调用”?我将闹钟设置为 1 毫秒,它应该立即触发。为什么什么也没有发生?
I have an android app where I try to set an alarm. My code inside activity:
fun setAlarm() {
alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, NotificationReceiver::class.java)
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)
alarmManager!!.set(AlarmManager.RTC_WAKEUP, /*calculateAlarmTime()*/1, pendingIntent)
Timber.i("setAlarm executed")
}
I set this alarm, calling setAlarm method. This is my NotificationReceiver class:
public class NotificationReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Timber.i("onReceive called");
}
}
Why I have only "setAlarm executed" in logcat, and not "onReceive called"? I set alarm to 1 millisecond and it should trigger immeditately. Why nothing happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的第二个参数是错误的。这不是您希望警报从现在开始多长时间发生,而是您希望警报发生的 Unix 时间戳。因此,1 会在 1970 年发生。您至少需要执行 System.currentTimeMillis()+1。尽管这很可能会导致竞争条件,但我不会指望在未来的工作中设置少于一秒钟的警报。
Your second parameter is wrong. It isn't how long from now you want the alarm to occur, it's the Unix timestamp of when you want it to occur. So 1 would have happened back in 1970. You would need to, at minimum, go System.currentTimeMillis()+1. Although that may well cause race conditions, I wouldn't count on an alarm being set for less than a second in the future working.
您使用 RTC_WAKEUP 设置 AlarmManager,因此您应该提供准确的日期和时间。相反,您将时间设置为 1 毫秒,这被解释为 1-1-1970, 00h00m00s 之后的 1 毫秒。
如果您想使用设置alarmManager的相对时间,您应该获取当前的RTC时间,添加几秒并使用该时间设置alarmManager。由于此方法不精确,请留出几秒钟的余地。
请参阅此处了解 RTC_WAKEUP 说明
You set the AlarmManager with RTC_WAKEUP, so you should supply the exact date and time. Instead you set the time to 1 ms, which is interpreted as 1ms after 1-1-1970, 00h00m00s.
If you want to use an relative time from setting the alarmManager you should get the current RTC time, add a few seconds and set the alarmManager with that time. As this method is inexact, allow a few seconds leeway.
See here for description RTC_WAKEUP