Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified

简介: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified

Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified


最近在写代码时碰到如下错误:

java.lang.IllegalArgumentException: com.example.imdemo: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.

错误分析:

错误提示在使用PendingIntent时,无论是创建或使用的时候,flags参数要求必须添加 FLAG_IMMUTABLE或者FLAG_MUTABLE的两个之中其中一个,而且官方还强烈推荐使用FLAG_IMMUTABLE(代码不同,依情况而定官方的推荐)。

解决方法

1.将项目的targetSdkVersion由31改为30

2.如果不想改targetSdkVersion,那就在在创建PendingIntent的时候判断当前系统版本,根据不同系统版本创建带有不同flag的PendingIntent,具体代码实现如下:

PendingIntent pendingIntent;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_IMMUTABLE);
} else {
pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT);
}


目录
相关文章
|
6月前
|
JavaScript 前端开发
15 Uncaught TypeError: Cannot set properties of null (setting ‘onclick‘)
这篇文章解释了在HTML文档中因JavaScript代码在页面元素加载之前执行导致的"Cannot set properties of null (setting ‘onclick’)"错误,并提供了将JavaScript代码置于`<body>`标签内或使用`window.onload`事件确保DOM完全加载后再绑定事件处理器的解决办法。
15 Uncaught TypeError: Cannot set properties of null (setting ‘onclick‘)
|
数据库 OceanBase
RuntimeError: 'PluginContext' object has no attribute 'set_variable'
RuntimeError: 'PluginContext' object has no attribute 'set_variable'
127 2
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_ZMCertification", referenced from:解决方法
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_ZMCertification", referenced from:解决方法
221 0
undefined reference to `major‘
undefined reference to `major‘
287 0
GLib-CRITICAL : g_variant_get_uint32: assertion ‘g_variant_is_of_type (value, G_VARIANT_TYPE_UINT32)
GLib-CRITICAL : g_variant_get_uint32: assertion ‘g_variant_is_of_type (value, G_VARIANT_TYPE_UINT32)
183 0
undefined reference to `swr_init+
undefined reference to `swr_init+
116 0
error: ‘nullptr’ was not declared in this scope
error: ‘nullptr’ was not declared in this scope
245 0
undefined reference to symbol XGetWindowAttributes/cairo_destroy/XShapeGetRectangles
undefined reference to symbol XGetWindowAttributes/cairo_destroy/XShapeGetRectangles
152 0
The 'manifest_version' key must be present and set to 2 (without quotes)
The 'manifest_version' key must be present and set to 2 (without quotes)
94 0
解决办法:Type safety: The expression of type List needs unchecked conversion to conform
解决办法:Type safety: The expression of type List needs unchecked conversion to conform
360 0