【问题标题】:After ACTION_BOOT_COMPLETED, why is AlarmManager running right away?在 ACTION_BOOT_COMPLETED 之后,为什么 AlarmManager 会立即运行?
【发布时间】:2020-11-02 02:55:43
【问题描述】:

引导接收器

override fun onReceive(context: Context, intent: Intent) {
    if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
        val array = MyDatabase(context).getAllAlarm()

        val receiver = Intent(context, BootReceiver::class.java)
        receiver.action = "ALARM_SETTING"

        val trigger = Calendar.getInstance()
        for (i in array) {
            trigger.time = SimpleDateFormat("yyyy/MM/dd hh:mm", Locale.getDefault()).parse(i.time)!!
            receiver.putExtra("trigger", trigger.timeInMillis)
            AlarmUtil.setAlarm(context, receiver, i.id, trigger.timeInMillis)
        }
    } else (intent.action == "ALARM_SETTING") {
        val trigger = intent.getLongExtra("trigger", 0)
        NotificationUtil.sendNotification(context, name, id, trigger)
    }
}

AlarmUtil

class AlarmUtil {
    companion object {
        fun setAlarm(context: Context, intent: Intent, id: Int, calendar: Long) {
            val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
            val pendingIntent = PendingIntent.getBroadcast(context.applicationContext, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar, pendingIntent)
            } else {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar, pendingIntent)
            }
        }
    }
}

如你所见,当手机重启时,这段代码会带上SQLiteDatabase中存储的报警数组,并发出报警声。如果你看一下 AlarmUtil 中的 setAlarm(),我写了一段代码,让它在 AlarmManager 中指定的时间哭泣。问题是存储在数组中的所有警报将被立即清除,无论警报数组中指定的时间如何(我将其实现为通知)。在calendar 输入setExactAndAllowWhileIdlesetExact 的第二个参数时哭泣不是很正常吗?为什么手机一开机就所有闹钟都响?

[编辑]

下图是设置闹钟在02:22响铃后手机关机再开机的情况。系统时间是2020/11/02 02:21,但是我设置的触发时间是2020/11/02 02:22。换句话说,一旦时间用完,警报就会响起。我想记录日志并显示出来,但是我一关掉手机,应用就死机了,所以我看不到日志。

【问题讨论】:

    标签: android broadcastreceiver alarmmanager android-reboot


    【解决方案1】:

    您好,您正在通过更早的时间作为触发时间。 你应该在未来消磨时间。 检查 db 时间是否小于 now() 而不是增加一天

    【讨论】:

    • 感谢您的回复。从BootReceiver 代码中可以看出,trigger 暂时调用Calendar.getInstance(),并且 trigger 时间在 for 语句中被重置。由于将 trigger 值作为通知传递,您所说的未来时间将被标记。它从来没有更早的时间
    • 你能记录下你传递给 AlarmManager 的时间吗?
    • 我上传了你的日志图片。
    • 你能同时记录触发时间和设备时间吗?
    • 也许您在记录时忽略了时区,将时间记录在 miillis 而不是日期演示文稿中
    猜你喜欢
    • 2014-03-23
    • 2014-11-29
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2019-06-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    相关资源
    最近更新 更多