警报未在 Android 上执行

Alarm isn't executed on Android

我有一个 android 应用程序,我试图在其中设置闹钟。我的代码在 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")
}

我设置了这个闹钟,调用了setAlarm方法。这是我的 NotificationReceiver class:

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Timber.i("onReceive called");
    }
}

为什么我在 logcat 中只有“setAlarm executed”,而不是“onReceive called”?我将警报设置为 1 毫秒,它应该立即触发。为什么什么都没发生?

您使用 RTC_WAKEUP 设置了 AlarmManager,因此您应该提供准确的日期和时间。相反,您将时间设置为 1 毫秒,这被解释为 1-1-1970 之后的 1 毫秒,00h00m00s。 如果您想使用设置 alarmManager 的相对时间,您应该获取当前的 RTC 时间,添加几秒钟并使用该时间设置 alarmManager。由于此方法不精确,请留出几秒钟的余地。 See here for description RTC_WAKEUP

你的第二个参数有误。这不是您希望警报发生的时间,而是您希望警报发生的时间的 Unix 时间戳。所以 1 会发生在 1970 年。你至少需要 System.currentTimeMillis()+1。尽管这很可能会导致竞争条件,但我不会指望在未来的工作中将警报设置为不到一秒。