如何在WearOS配置Firebase通知?移动端正常穿戴端无通知
解决穿戴端同包名无法接收Firebase通知的问题
以下是针对问题的排查和解决方案:
确认穿戴端Firebase配置正确性
虽然移动端和穿戴端包名相同,但需确保穿戴端的google-services.json文件与移动端完全一致,且正确放置在wear模块的app/src/main目录下。同时检查wear模块的build.gradle是否正确应用了Google Services插件:plugins { id 'com.android.application' id 'com.google.gms.google-services' }并添加与移动端版本一致的Firebase Messaging依赖:
implementation 'com.google.firebase:firebase-messaging:23.4.0'检查FirebaseMessagingService的Manifest注册
确保穿戴端的AndroidManifest.xml中正确注册了自定义的FirebaseMessagingService,并添加对应的intent-filter:<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>Android 12+版本需正确设置
android:exported属性(此处设为false即可)。验证通知权限与通道配置
- 对于Android 13+的穿戴设备,需在Manifest中声明
POST_NOTIFICATIONS权限:
并在代码中动态请求该权限。<uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> - Android 8.0+设备必须创建通知通道才能显示通知,确保穿戴端代码中完成通道初始化:
发送通知时需指定该通道ID。if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel( "wear_notification_channel", "穿戴设备通知通道", NotificationManager.IMPORTANCE_DEFAULT ).apply { description = "用于接收Firebase通知的通道" } val notificationManager = getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) }
- 对于Android 13+的穿戴设备,需在Manifest中声明
确认穿戴端已获取Firebase注册Token
在自定义FirebaseMessagingService的onNewToken方法中打印Token,验证穿戴端是否成功完成Firebase注册:override fun onNewToken(token: String) { Log.d("WearFirebase", "注册Token: $token") // 将Token上传至你的服务器,确保发送通知时使用该Token }如果未生成Token,检查网络连接及Firebase项目配置是否正确。
排查消息类型与接收逻辑
Firebase通知分为通知消息和数据消息:- 通知消息由Firebase SDK自动处理显示,但部分穿戴设备可能不会自动触发显示,建议改用数据消息,在
onMessageReceived方法中自行构建并显示通知。 - 确保
onMessageReceived方法中正确处理消息,例如:override fun onMessageReceived(remoteMessage: RemoteMessage) { remoteMessage.data?.let { data -> val title = data["title"] ?: "默认标题" val content = data["content"] ?: "默认内容" // 构建并显示通知 val notification = NotificationCompat.Builder(this, "wear_notification_channel") .setSmallIcon(R.drawable.ic_notification) .setContentTitle(title) .setContentText(content) .build() NotificationManagerCompat.from(this).notify(1, notification) } }
- 通知消息由Firebase SDK自动处理显示,但部分穿戴设备可能不会自动触发显示,建议改用数据消息,在
检查穿戴设备状态
- 若穿戴设备依赖手机蓝牙连接,确保设备已与手机配对且连接正常,手机端未限制穿戴设备的通知权限。
- 若为独立联网的穿戴设备(如LTE版),确保设备已连接网络,且未开启省电模式限制后台服务运行。
内容的提问来源于stack exchange,提问作者Rahul Mishra
相关产品推荐
相关产品推荐

