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

发布时间 2023-03-22 21:17:07作者: xiaowang_lj

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

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,具体代码实现如下: