androidkotlin

Not receiving events using a BroadcastReceiver


I have two classes in my android project:

class NotificationEventListener: NotificationListenerService() {

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        
        Log.i("NotificationEventListener", "Sending broadcast")
        sendBroadcast(
            Intent("com.github.example.TEST")
        )
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
    }
}

And:

class WatchCompanionDeviceService : CompanionDeviceService() {
    @SuppressLint("MissingPermission")
    override fun onDeviceAppeared(associationInfo: AssociationInfo) {
        super.onDeviceAppeared(associationInfo)
        // Unrelated bluetooth code
    }

    override fun onDeviceDisappeared(associationInfo: AssociationInfo) {
        super.onDeviceDisappeared(associationInfo)
        // Unrelated bluetooth code
    }



    private val notificationReceiver = NotificationReceiver()

    override fun onCreate() {
        super.onCreate()
        Log.i("WatchCompanionDeviceService", "CompanionDeviceService started")

        // Notification Receiver
        val notificationFilter = IntentFilter("com.github.example.TEST")
        registerReceiver(notificationReceiver, notificationFilter, RECEIVER_NOT_EXPORTED)
        Log.i("WatchCompanionDeviceService", "notificationFilter started")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.i("WatchCompanionDeviceService", "CompanionDeviceService stopped")

        // Notification Receiver
        unregisterReceiver(notificationReceiver)
    }


    class NotificationReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.i("WatchCompanionDeviceService", "Broadcast received")
        }
    }
}

When I start the app and connect the bluetooth device I get the CompanionDeviceService started and notificationFilter started log messages.
When my phone gets a notification I get the Sending broadcast log message.
So, every part of it is working except that the broadcast isn't being received by WatchCompanionDeviceService, I never get the Broadcast received log message.


Solution

  • You may need to specify a package name in your broadcast intent like:

    sendBroadcast(
      Intent("com.github.example.TEST").apply {
        setPackage(packageName) // or "com.github.example"
      }
    )