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

Android Alarm Manager未触发,无法推送Notification问题排查

问题分析与解决方案

我仔细看了你的代码,发现几个关键问题导致BroadcastReceiver没被调用,咱们逐个解决:

1. AlarmManager的时间类型完全不匹配

你使用了AlarmManager.ELAPSED_REALTIME_WAKEUP作为闹钟类型,但传入的触发时间是notificationdate.getTime()——这两个根本不是一套时间体系:

  • ELAPSED_REALTIME_WAKEUP要求的是设备开机至今的毫秒数(可以通过SystemClock.elapsedRealtime()获取当前值);
  • Date.getTime()返回的是1970年1月1日UTC至今的时间戳,和开机时间毫无关系。

这直接导致闹钟计算的触发时间完全错误,自然不会在你预期的1分钟后触发。

修复方案:

根据你的需求二选一:

  • 如果要设置“从现在起1分钟后触发”,用ELAPSED_REALTIME_WAKEUP的话,触发时间应该是:
    long notificationTimeInMillis = SystemClock.elapsedRealtime() + 60 * 1000;
    
  • 如果要基于具体的Date对象触发,把闹钟类型换成AlarmManager.RTC_WAKEUP,它支持Date.getTime()这种时间戳:
    alarmManager.set(AlarmManager.RTC_WAKEUP, notificationTimeInMillis, pendingAlarmIntent);
    

2. PendingIntent的Flag适配问题

在Android 12(API 31)及以上版本,创建PendingIntent必须指定IMMUTABLE或MUTABLE flag,否则会抛出异常或者导致PendingIntent无法正常传递。你当前只用了FLAG_UPDATE_CURRENT,这在高版本系统上可能出问题。

修复方案:

如果你的通知内容不需要后续修改,建议组合使用:

PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(mActivity, 0, notificationIntent, 
    PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

如果需要后续修改Intent里的内容,就把FLAG_IMMUTABLE换成FLAG_MUTABLE。

3. 额外提醒:通知渠道未创建(影响通知显示)

虽然这不是导致BroadcastReceiver不触发的原因,但你构建Notification时指定了channelid,却没有创建对应的通知渠道。Android 8.0(API 26)及以上必须创建渠道才能显示通知,所以即使闹钟触发了,用户也看不到通知。建议添加创建渠道的代码:

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence channelName = "测试通知渠道";
        String channelDesc = "用于测试一次性闹钟的通知渠道";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        
        NotificationChannel channel = new NotificationChannel("Channel Id", channelName, importance);
        channel.setDescription(channelDesc);
        
        NotificationManager notificationManager = mActivity.getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
}

记得在调度闹钟前调用这个方法。


内容的提问来源于stack exchange,提问作者Kenny Wyland

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:48:41