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

使用AlarmManager与PendingIntent时Android应用崩溃问题求助

问题解决

崩溃原因

你的应用目标API版本为31(Android 12)及以上,系统要求创建PendingIntent时必须指定FLAG_IMMUTABLE或FLAG_MUTABLE标记,而你当前仅使用了FLAG_UPDATE_CURRENT,缺少强制要求的标记,因此抛出IllegalArgumentException。

修复步骤

1. 修改PendingIntent创建逻辑

在获取PendingIntent时,添加FLAG_IMMUTABLE(推荐,AlarmManager场景无需修改PendingIntent内容,该标记更安全),与原有的FLAG_UPDATE_CURRENT做按位或操作:

private void scheduleNotification (Notification notification, int delay)
{
    Intent notificationIntent = new Intent(this, MyNotificationPublisher.class);
    // 注意:原代码两次使用同一个key传值,第二个会覆盖第一个,建议修正key名称
    notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, 1);
    notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_CONTENT, notification);
    
    int flags;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
        flags = PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE;
    } else {
        flags = PendingIntent.FLAG_UPDATE_CURRENT;
    }
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, flags);
    
    long futureMillis = SystemClock.elapsedRealtime() + delay;
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    assert alarmManager != null;
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureMillis, pendingIntent);
}

2. 修正重复Key问题

原代码中两次调用notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATIONID, ...),同一个key会导致第一个值被覆盖,建议定义两个不同的常量key,分别传递ID和Notification对象。

标记说明

  • FLAG_IMMUTABLE:创建不可修改的PendingIntent,适用于绝大多数AlarmManager场景,安全性更高。
  • FLAG_MUTABLE:仅当需要后续修改PendingIntent内数据时使用,比如涉及内联回复、气泡功能等场景。

内容的提问来源于stack exchange,提问作者Binyamin Pekar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:15:04