You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中如何设置仅触发一次的非重复闹钟?

安卓单次闹钟实现方案

问题原因

你当前调用的setInexactRepeating是Android系统专门提供的重复闹钟API,方法的第三个参数就是重复间隔,你传入了AlarmManager.INTERVAL_DAY也就是24小时的间隔,所以闹钟会每天重复触发。

解决方法

直接使用set方法即可,该方法本身就是为一次性闹钟设计的,不会重复执行。修改后的代码如下:

alarmManager= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent=new Intent(this,AlarmReceiver.class);
// 注意:如果你的应用目标SDK版本>=31,需要给PendingIntent指定FLAG_IMMUTABLE或FLAG_MUTABLE,不能传0
pendingIntent=PendingIntent.getBroadcast(this,0,intent, PendingIntent.FLAG_IMMUTABLE);
// 替换原有的setInexactRepeating调用为set方法即可实现单次闹钟
alarmManager.set(AlarmManager.RTC_WAKEUP,calender.getTimeInMillis(), pendingIntent);

适配注意事项

  • 若应用目标SDK >= 23(Android 6.0),低电耗模式下set方法可能被系统延迟触发,需要在低电耗模式下也准时触发的场景可以替换为setAndAllowWhileIdle方法
  • 若应用目标SDK >= 19(Android 4.4),set方法的触发时间允许系统偏移对齐以降低功耗,要求绝对准时的场景可以使用setExact方法
  • 闹钟触发后,建议在AlarmReceiver的业务逻辑执行完成后调用alarmManager.cancel(pendingIntent)清理对应的PendingIntent,避免后续出现意外触发的情况

内容的提问来源于stack exchange,提问作者Avni Krtigya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 00:54:00