Android 12 Pending Intent Immutable 标志在 API 23 下不可用

标签 android android-pendingintent android-12

类似于这个 question ,但不一样
更新到 Android 12 (SDK 31) 后,我们将 PendingIntent.getActivity(context, 0, intent, 0) 更改为 PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE) ,如 suggested
但是 PendingIntent.FLAG_IMMUTABLE 不适用于 23 岁以下的 SDK。如果我添加 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 以保留两个版本,我将继续使用 lint 警告,即没有为 else 案例使用正确的标志。
这里的预期行为是什么?谢谢!

最佳答案

来自 PendingIntent.FLAG_MUTABLE 的文档:

Up until Build.VERSION_CODES.R, PendingIntents are assumed to be mutable by default, unless FLAG_IMMUTABLE is set. Starting with Build.VERSION_CODES.S, it will be required to explicitly specify the mutability of PendingIntents on creation with either FLAG_IMMUTABLE or FLAG_MUTABLE. It is strongly recommended to use FLAG_IMMUTABLE when creating a PendingIntent. FLAG_MUTABLE should only be used when some functionality relies on modifying the underlying intent, e.g. any PendingIntent that needs to be used with inline reply or bubbles.


总之,您应该添加 FLAG_IMMUTABLE以 API 31 或更高版本为目标时标记您的 PendingIntent,除非您需要 PendingIntent 是可变的,在这种情况下您需要使用 FLAG_MUTABLE .
因为FLAG_IMMUTABLE在 API 23 中引入,您必须使用 FLAG_MUTABLE作为较低版本的后备。
val flag =
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE
  else PendingIntent.FLAG_MUTABLE
您可以将其与现有的 Intent 标志(如果有)结合使用按位 or手术。例如:
val flags = flag or PendingIntent.FLAG_ONE_SHOT

关于Android 12 Pending Intent Immutable 标志在 API 23 下不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69088578/

相关文章:

android - PendingIntent 与 IntentService 不起作用

android - 无法从 Intent 中获取额外的值

cordova-plugins - 有人成功地将 "Email Composer"Cordova 插件添加到 Ionic 5 项目(适用于 Android12)吗?

android - 在 Android 12 上未收到 Firebase 推送通知

android - 什么是 XML 属性 xmlns :app?

android - 带有自定义 ArrayAdapter 的 ArrayList

Android:AlarmManager 无法取消警报

Android 12 启动画面 API 定制

java - 集合不能包含重复项。但确实如此

android - 如何完全隐藏 ExpandableListView 的 groupIndicator?