Search code examples
androidkotlinbroadcastreceiver

What is the proper way to use registerReceiver in Android 14/SDK 34?


I'm getting the following warning on the code below

hardwareScanBroadcastReceiver is missing RECEIVER_EXPORTED or RECEIVER_NOT_EXPORTED flag for unprotected broadcasts registered for an IntentFilter that cannot be inspected by lint

registerReceiver(
          hardwareScanBroadcastReceiver,
          scanningHardware.createIntent()
        )

But when I added RECEIVER_NOT_EXPORTED, I'm getting a warning like this

Field requires API level 33 (current min is 26): android.content.Context#RECEIVER_NOT_EXPORTED

The minimum SDK version is 26. But how can I implement the registerReceiver and make it backward compatible?

Tried to read the documentation but I didn't find any clue.

https://developer.android.com/guide/components/broadcasts


Solution

  • The simplest solution is to use ContextCompat.registerReceiver() and the ContextCompat version of RECEIVER_NOT_EXPORTED. Under the covers, it will check the version of the OS that the app is running on and call the proper real registerReceiver() method with the proper flag.