Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 637
C0NTRERAS Avatar asked Sep 03 '25 16:09

C0NTRERAS


1 Answers

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.

like image 183
CommonsWare Avatar answered Sep 05 '25 08:09

CommonsWare



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!