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

亦凉 2024-03-31 09:15 80阅读 0赞

项目有Target30升级到31后项目,Firebase 出现Crash:

Fatal Exception: java.lang.IllegalArgumentException

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.

出错的代码主要是在创建通知栏消息时抛出的,主要代码如下:

  1. rivate void createNotification() {
  2. Intent intent = new Intent(this, OtherActivity.class);
  3. // 这一行报错
  4. PendingIntent pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT);
  5. NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
  6. .setSmallIcon(R.mipmap.ic_launcher)
  7. .setContentTitle("测试")
  8. .setContentText("收到一条通知消息")
  9. .setContentIntent(pendingIntent)
  10. .setPriority(NotificationCompat.PRIORITY_HIGH)
  11. .setAutoCancel(true);
  12. Notification build = builder.build();
  13. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  14. NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
  15. notificationManager.createNotificationChannel(
  16. new NotificationChannel(NOTIFICATION_CHANNEL_ID, "测试测试", NotificationManager.IMPORTANCE_HIGH)
  17. );
  18. }
  19. NotificationManagerCompat.from(this).notify(notificationId++, build);
  20. }

查资料后,发现如下几个修复的方法:

  1. 将项目的targetSdkVersion由31改为30,也就是退回去,但是Google Play 现在最低是31
  2. 如果不想改targetSdkVersion,那就在在创建PendingIntent的时候判断当前系统版本,根据不同系统版本创建带有不同flag的PendingIntent,具体代码实现如下:

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

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读