Android AlarmManager 闹钟相关

亢奇
2023-12-01

如何设置闹钟

具体参考Android官网。
在上午 8:30 准时唤醒设备并触发闹钟,此后每 20 分钟触发一次:

private var alarmMgr: AlarmManager? = null
    private lateinit var alarmIntent: PendingIntent
    ...
    alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    alarmIntent = Intent(context, AlarmReceiver::class.java).let { intent ->
        PendingIntent.getBroadcast(context, 0, intent, 0)
    }

    // Set the alarm to start at 8:30 a.m.
    val calendar: Calendar = Calendar.getInstance().apply {
        timeInMillis = System.currentTimeMillis()
        set(Calendar.HOUR_OF_DAY, 8)
        set(Calendar.MINUTE, 30)
    }

    // setRepeating() lets you specify a precise custom interval--in this case,
    // 20 minutes.
    alarmMgr?.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1000 * 60 * 20,
            alarmIntent
    )

注意如果闹钟开始时间早于当前时间,则系统会根据过去的时间和重复的间隔选择一个时间去触发闹钟。

If the stated trigger time is in the past, the alarm will be triggered immediately,with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.

所以会出现前几次闹钟的间隔不太一致的情况:
设置的闹钟间隔为10分钟,闹钟开始时间早于当前时间,唤醒结果如下

        alarmMgr.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            CommandBean.DEF_INVENTORY_DURATION * 60 * 1000,
            alarmIntent
        )
2019-12-06 14:13:46.696 
2019-12-06 14:16:26.634 
2019-12-06 14:24:26.765 
2019-12-06 14:34:26.579 
2019-12-06 14:43:46.785 

使用ELAPSED_REALTIME_WAKEUP则会好些

        alarmMgr.setRepeating(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime(),
            tenMinutes,
            alarmIntent
        )

取消闹钟

取消闹钟时需要传入上文中的PendingIntent 。注意requestCode等要完全一致,要满足Intent#filterEquals()的条件。

alarmManager.cancel(alarmIntent)

查看已经设置的闹钟

adb shell dumpsys alarm

ADB发送广播

adb shell am broadcast -a com.to.package --ei seq 1619684 --es "data" '''{这里可以放JSON数据}'''

参考链接

安排重复闹钟 Android Developer

 类似资料: