Android Studio报废弃API错误,Notification.Builder如何适配全安卓版本?
解决方案
你碰到的废弃警告是因为原生Notification.Builder在API 26及以上版本被废弃,同时高版本安卓系统新增了通知通道、PendingIntent可变性限制等要求,需要统一适配才能覆盖全版本安卓系统。
修改步骤
- 替换原生Builder为AndroidX兼容库提供的
NotificationCompat.Builder,自动向下兼容旧系统 - 新增Android 8.0(API 26)以上所需的通知通道注册逻辑,高版本系统必须有通道才能正常发通知
- 修改PendingIntent的flags参数,适配Android 12以上的可变性强制要求
完整修改后代码
// 自定义常量,可根据业务需求调整取值 private static final String CHANNEL_ID = "words_reminder_channel"; private static final int NOTIFICATION_ID = 1; // 替换为你自己原来的通知ID // 1. 注册通知通道,仅Android 8.0+执行,旧版本自动跳过该逻辑 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence channelName = "单词提醒"; String channelDesc = "用于推送单词复习通知"; int importance = NotificationManager.IMPORTANCE_HIGH; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, channelName, importance); channel.setDescription(channelDesc); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } // 2. 替换为兼容版Builder,传入上下文和通道ID NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setContentTitle("Words reminder"); builder.setContentText("It's time to try yourself!"); builder.setSmallIcon(R.drawable.ic_stat_name); builder.setAutoCancel(true); builder.setPriority(NotificationCompat.PRIORITY_HIGH); Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); builder.setSound(alarmSound); Intent notifyIntent = new Intent(this, RightOrNot.class); notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); // 3. 修改flags适配Android 12+可变性要求 PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); builder.setContentIntent(pendingIntent); Notification notificationCompat = builder.build(); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this); managerCompat.notify(NOTIFICATION_ID, notificationCompat);
修改说明
NotificationCompat.Builder由AndroidX官方兼容库提供,可向下兼容至API 14,覆盖目前所有主流仍在使用的安卓版本,不会触发废弃API警告- 通知通道逻辑仅在Android 8.0及以上系统生效,旧版本会自动忽略通道参数,不会影响运行
- 调整后的PendingIntent flags明确声明了不可变属性,符合Android 12及以上系统的强制要求,同时旧版本系统可以正常识别该参数
内容的提问来源于stack exchange,提问作者Sergei
相关产品推荐
相关产品推荐

