BroadcastReceiver无法接收事件:Android蓝牙服务广播接收失败
问题诊断与解决方案
核心原因
你遇到的是跨服务广播投递失败问题,主要源于Android 12+对全局广播的限制:你发送的广播未指定目标应用包名,被系统判定为全局广播,而动态注册时使用RECEIVER_NOT_EXPORTED的接收器无法接收全局广播。
具体修复步骤
1. 修改广播发送逻辑,限定应用内范围
在NotificationEventListener的onNotificationPosted方法中,给Intent添加当前应用包名,确保广播仅在应用内部传递:
override fun onNotificationPosted(sbn: StatusBarNotification?) { super.onNotificationPosted(sbn) Log.i("NotificationEventListener", "Sending broadcast") val broadcastIntent = Intent("com.github.example.TEST") // 指定当前应用包名,缩小广播投递范围 broadcastIntent.setPackage(packageName) sendBroadcast(broadcastIntent) }
2. 确认服务与接收器的基础配置
- 检查
AndroidManifest.xml中两个服务的声明是否正确:NotificationListenerService需添加权限和声明:<service android:name=".NotificationEventListener" android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"> <intent-filter> <action android:name="android.service.notification.NotificationListenerService" /> </intent-filter> </service>CompanionDeviceService的声明:<service android:name=".WatchCompanionDeviceService" android:permission="android.permission.BIND_COMPANION_DEVICE_SERVICE"> <intent-filter> <action android:name="android.companion.CompanionDeviceService" /> </intent-filter> </service>
- 确认用户已授予
NotificationListenerService权限(通过系统设置→应用→你的应用→通知访问权限开启)。
3. 验证服务存活状态
从你的日志来看WatchCompanionDeviceService已启动,但若后续出现服务被系统回收的情况,可将其设为前台服务,避免因进程被杀死导致接收器失效。
修复原理
Android 12及以上版本严格管控全局广播,未指定包名的广播会被系统拦截,而RECEIVER_NOT_EXPORTED标记的接收器仅接收应用内广播。通过给Intent添加包名,将广播限定为应用内范围,就能绕过系统限制,确保接收器正常接收广播。
内容的提问来源于stack exchange,提问作者doominabox1
相关产品推荐
相关产品推荐

