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);
}


目录
相关文章
|
8月前
|
JavaScript 程序员 Swift
The compiler is unable to type-check this expression in reasonable time; try breaking up the express
The compiler is unable to type-check this expression in reasonable time; try breaking up the express
101 0
|
数据库 OceanBase
RuntimeError: 'PluginContext' object has no attribute 'set_variable'
RuntimeError: 'PluginContext' object has no attribute 'set_variable'
125 2
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_ZMCertification", referenced from:解决方法
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_ZMCertification", referenced from:解决方法
218 0
|
关系型数据库 MySQL C++
Error:E0415 no suitable constructor exists to convert from “int“ to “Rational“
Error:E0415 no suitable constructor exists to convert from “int“ to “Rational“
194 0
undefined reference to `major‘
undefined reference to `major‘
285 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
undefined reference to symbol XGetWindowAttributes/cairo_destroy/XShapeGetRectangles
undefined reference to symbol XGetWindowAttributes/cairo_destroy/XShapeGetRectangles
152 0
undefined reference to `swr_init+
undefined reference to `swr_init+
116 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
356 0