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

项目有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.

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

rivate void createNotification() {
    Intent intent = new Intent(this, OtherActivity.class);
    // 这一行报错
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 123, intent, PendingIntent.FLAG_ONE_SHOT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("测试")
            .setContentText("收到一条通知消息")
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setAutoCancel(true);
    Notification build = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(
                new NotificationChannel(NOTIFICATION_CHANNEL_ID, "测试测试", NotificationManager.IMPORTANCE_HIGH)
        );
    }
    NotificationManagerCompat.from(this).notify(notificationId++, build);
}

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

  1. 将项目的targetSdkVersion由31改为30,也就是退回去,但是Google Play 现在最低是31

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

    文章来源地址https://uudwc.com/A/odMzV

原文地址:https://blog.csdn.net/Jason_HD/article/details/127949845

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年08月19日 05:02
git上传仓库内容超过100M解决方法git
下一篇 2023年08月19日 05:07