最近在寫代碼時(shí)碰到如下錯(cuò)誤:
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.
出錯(cuò)的代碼主要是在創(chuàng)建通知欄消息時(shí)拋出的,主要代碼如下:
private void createNotification() {
Intent intent = new Intent(this, OtherActivity.class);
// 這一行報(bào)錯(cuò)
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);
}
查了一番資料后,發(fā)現(xiàn)如下幾個(gè)修復(fù)的方法:
-
將項(xiàng)目的targetSdkVersion由31改為30
-
如果不想改targetSdkVersion,那就在在創(chuàng)建PendingIntent的時(shí)候判斷當(dāng)前系統(tǒng)版本,根據(jù)不同系統(tǒng)版本創(chuàng)建帶有不同flag的PendingIntent,具體代碼實(shí)現(xiàn)如下:
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); }
-
直接在項(xiàng)目中依賴下面的庫文章來源:http://www.zghlxwxcb.cn/news/detail-664833.html
dependencies { // For Java implementation 'androidx.work:work-runtime:2.7.1' // For Kotlin implementation 'androidx.work:work-runtime-ktx:2.7.1' }
這里最推薦的是使用上面的方法2。文章來源地址http://www.zghlxwxcb.cn/news/detail-664833.html
到了這里,關(guān)于Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!