Android AlarmManager 闹钟相关

如何设置闹钟

具体参考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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值