之前Android11时候加了个通知栏常驻通知,今天升级Android12突然就凉了,项目框框报错
java.lang.IllegalArgumentException: com.ibptadb: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
2022-07-13 10:48:01.939 31160-31160/com.xxx I/info: 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.
报错写的清楚明了,就是SDK31版本的问题,然后网上一搜索是在Android12中待处理的PendingIntent必须声明可变性。
要声明给定PendingIntent对象是可变的或不可变的 ,请分别使用 PendingIntent.FLAG_MUTABLE 或 PendingIntent.FLAG_IMMUTABLE标志。
代码就是:
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Main.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
Notification notify = new Notification.Builder(this).setSmallIcon(R.drawable.ic_launcher)
// 设置通知常驻,不会通过左右滑动消除,只能通过cancel消除
.setOngoing(true)
// 设置通知将要启动程序的Intent
.setContentIntent(pi)
// 设置打开该通知,该通知不会自动消失
.setAutoCancel(false).build();
// 发送通知
nm.notify(NOTIFICATION_ID, notify);