Android Auto通知无法显示,已按官方文档配置求代码问题排查
问题修复方案
代码存在的问题和修改点
- PendingIntent flag 配置错误:Android 12及以上系统强制要求PendingIntent显式声明
FLAG_IMMUTABLE或FLAG_MUTABLE,你当前只使用了FLAG_UPDATE_CURRENT,Android Auto对PendingIntent合法性校验比普通手机严格,异常的PendingIntent会直接导致通知被过滤。
修正后的PendingIntent代码:// Android 12+ 必须加IMMUTABLE/MUTABLE,这里通知的pendingIntent不需要修改就用IMMUTABLE val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } val pendingIntent = PendingIntent.getActivity(context, 2 ,intent, flag) - MessagingStyle消息时间戳异常:你给
Message构造传入的时间戳是固定值1,Android Auto会过滤时间戳异常的会话通知,需要传入真实的时间戳:// 传入当前时间戳,不要用固定错误值 val messageTime = System.currentTimeMillis() val style: Notification.Style = Notification.MessagingStyle(p) .setConversationTitle("this is a title") .addMessage(Notification.MessagingStyle .Message("this is the text", messageTime, p)) - 未使用兼容的通知构建类:原生框架的
Notification.Builder在不同Android Auto版本上兼容性很差,建议替换为AndroidX的NotificationCompat.Builder、NotificationCompat.MessagingStyle等兼容类,同时补充CarExtender的必要配置:// 替换为兼容类构建,补充CarExtender配置 val newMessageNotification = NotificationCompat.Builder(context, channelId) .setContentTitle(title) .setContentText(subject) .setCategory(Notification.CATEGORY_MESSAGE) .setSmallIcon(R.drawable.ic_logo) .setLargeIcon(icon) .setStyle(style) .setVisibility(Notification.VISIBILITY_PUBLIC) .addAction(action) // 补充CarExtender的未读计数配置 .extend(NotificationCompat.CarExtender() .setUnreadCount(1)) .build() - Person对象参数不全:建议给Person对象添加唯一key,避免Android Auto识别会话出错:
val p = Person.Builder() .setName("Gopass") .setKey("gopass_conversation") .build()
额外检查项
- 检查清单文件是否已经添加汽车通知相关权限,以及Android Auto的配置元数据
- 检查手机端Android Auto设置中,你的应用的通知权限是否已经开启,手机系统的通知权限不代表Auto端的权限
- 测试用的Desktop Head Unit需要开启通知同步开关,确认和手机端Android Auto服务配对正常
内容的提问来源于stack exchange,提问作者Juan Pablo Ariza
相关产品推荐
相关产品推荐

