Android 12呼入/呼出通知prominent chip功能NotificationCompat适配问题
实现方案
AndroidX Core 1.7.0 及以上版本已经提供了NotificationCompat.CallStyle兼容类,可以直接基于它实现prominent chip效果,无需调用原生非Compat API,具体操作如下:
1. 依赖版本确认
首先确保项目build.gradle中引入的AndroidX Core库版本不低于1.7.0:
dependencies { implementation "androidx.core:core:1.7.0" // 可升级到最新稳定版获得更好的兼容性 }
2. 兼容版代码实现
注意要使用兼容包下的Person类(androidx.core.app.Person),不要使用系统Framework层的Person类,具体示例代码如下:
// 构建来电人信息,使用兼容版Person类 Person incomingCaller = new Person.Builder() .setName("Jane Doe") .setImportant(true) // 可选设置来电人头像:.setIcon(icon) .build(); // 构建通知,使用NotificationCompat.Builder NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID) .setContentIntent(contentIntent) .setSmallIcon(smallIcon) .setFullScreenIntent(contentIntent, true) // 可选,锁屏场景下显示全屏来电界面 // 设置呼入通话样式,对应prominent chip效果 .setStyle(NotificationCompat.CallStyle.forIncomingCall( incomingCaller, declineIntent, answerIntent )) .addPerson(incomingCaller); // 呼出通话场景可以用forOngoingCall方法 // .setStyle(NotificationCompat.CallStyle.forOngoingCall(incomingCaller, hangupIntent)) // 最后展示通知即可 NotificationManagerCompat.from(context).notify(notificationId, builder.build());
注意事项
- 通知渠道必须设置为
IMPORTANCE_HIGH(优先级高),否则Android 12及以上系统不会展示为prominent chip样式 - Android 10及以上版本使用全屏通知需要申请
android.permission.USE_FULL_SCREEN_INTENT权限 - 低于Android 12的系统会自动将该样式降级为普通通话通知,无需额外适配
内容的提问来源于stack exchange,提问作者motis10
相关产品推荐
相关产品推荐

