我的AlarmManager代码能否正常发送广播?onReceive未触发是什么原因
问题修复方案
1. 修正AlertReceiver语法错误
你的广播接收器里嵌套重写了两次onReceive方法,属于语法错误,直接删掉一层重复的重写逻辑即可:
class AlertReceiver: BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { Toast.makeText(context, "Alarm", Toast.LENGTH_LONG).show() println("Alarm") Log.e("Alarm","Alarm Triggered") } }
2. 补充PendingIntent可变性声明
Android 12(API 31)及以上系统要求PendingIntent必须显式声明可变性,仅用FLAG_UPDATE_CURRENT会触发异常,修改初始化代码:
pendingIntent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) } else { PendingIntent.getBroadcast(this, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT) }
3. 修复Manifest标签闭合问题
你的注册代码中<intent-filter标签缺少结尾的>,修正后配置:
<receiver android:name=".AlertReceiver" android:enabled="true" android:exported="true"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /> <action android:name="MyBroadcastReceiverAction"/> </intent-filter> </receiver>
如果仅通过Alarm触发广播、不需要监听开机事件,也可以直接去掉intent-filter配置,显式Intent触发的广播不需要额外配置action过滤。
4. 替换不精准的setRepeating API
Android 6.0(API 23)之后引入低电耗、应用待机模式,setRepeating设置的闹钟会被系统延迟甚至拦截,建议使用精准闹钟API,每次触发后重新注册下一次闹钟实现24小时重复效果:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent ) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent ) } else { alarmManager.set( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent ) }
附加调试优化建议
- 测试时先把触发时间改成当前时间往后1-2分钟,不需要等到固定21点,快速验证功能是否正常
- 国产ROM需要手动开启应用自启动权限、关闭电池优化,避免应用被后台杀死后闹钟失效
- 如需重启设备后闹钟仍生效,需要在Manifest中添加权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> - Android 13及以上系统如果后续需要弹出通知,需要提前申请
POST_NOTIFICATIONS动态权限
内容的提问来源于stack exchange,提问作者Zupermar
相关产品推荐
相关产品推荐

