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

Android 12设置PendingIntent FLAG_IMMUTABLE后仍报错求助

问题排查与修复方案

1. Notification中PendingIntent未指定不可变标志(Android 12+必现)

在BirthdayNotification方法里,创建跳转到MainActivity的PendingIntent时传入的flag为0,Android 12(API 31)及以上版本要求必须明确指定FLAG_IMMUTABLE或FLAG_MUTABLE,否则会抛出IllegalArgumentException。

修改代码:

PendingIntent pendingIntent2;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    pendingIntent2 = PendingIntent.getActivity(mCon, 2, i2, PendingIntent.FLAG_IMMUTABLE);
} else {
    pendingIntent2 = PendingIntent.getActivity(mCon, 2, i2, 0);
}

2. 检查BroadcastReceiver的Manifest注册

确保DailyReminder已在AndroidManifest.xml中静态注册,且显式指定exported="true"(系统通过AlarmManager触发Receiver时需要该配置):

<receiver
    android:name=".DailyReminder"
    android:exported="true">
</receiver>

若App的targetSdkVersion为31+,exported属性必须显式声明,否则会导致安装失败或运行时无法触发Receiver。

3. Android 12+精确闹钟权限申请

如果需要闹钟精确触发,Android 12及以上版本需申请SCHEDULE_EXACT_ALARM权限:

  1. 在AndroidManifest.xml中添加权限声明:
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
  1. 运行时检查并请求权限:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    AlarmManager alarmManager = (AlarmManager) mCon.getSystemService(Context.ALARM_SERVICE);
    if (!alarmManager.canScheduleExactAlarms()) {
        Intent intent = new Intent(Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM);
        mCon.startActivity(intent);
    }
}

另外,setRepeating方法在Android 6.0+的Doze模式下会被延迟,若需精确重复触发,建议改用setExactAndAllowWhileIdle,并在每次闹钟触发后重新设置下一次闹钟。

4. Notification Channel创建优化

当前每次触发通知都会重复创建Channel,虽不会报错,但建议仅在Channel不存在时创建:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "Birthday Channel";
    NotificationChannel channel = mNotificationManager.getNotificationChannel(channelId);
    if (channel == null) {
        channel = new NotificationChannel(
                channelId,
                "Birthday Notification",
                NotificationManager.IMPORTANCE_HIGH);
        mNotificationManager.createNotificationChannel(channel);
    }
    mBuilder.setChannelId(channelId);
}

5. 确认PendingIntent请求码唯一性

确保闹钟PendingIntent的请求码ALARM1_ID = 10000不会与其他PendingIntent的请求码重复,避免被意外覆盖。

内容的提问来源于stack exchange,提问作者Supun Ayeshmantha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:30:43