In onResume() I do:
registerReceiver(timeTickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
and in onPause():
unregisterReceiver(timeTickReceiver);
I see "java.lang.IllegalArgumentException: Receiver not registered" reports in Android Developer Console (there are only 2 reports and my app has thousands of users). The exception is triggered by unregisterReceiver(). What can be happening? I don't feel very confident to just surround it with try-catch.
If you register a receiver in onResume() , you should unregister it in onPause() to prevent registering it multiple times (If you don't want to receive broadcasts when paused, and this can cut down on unnecessary system overhead).
You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered. Create a class that extends the Receiver and there you can use: Singleton pattern for only have one instance of this class in your project.
We've seen this error when doing a long press on a particular screen, and then immediately doing two orientation changes (e.g. turning the device upside down).
The API docs for unregisterReceiver says:
Unregister a previously registered BroadcastReceiver.
It doesn't say explicitly, but as you've seen, you hit IllegalArgumentException: Receiver not registered
if it isn't already registered.
The workaround I'm using is to store my Receiver as a member field, and have it set to null whenever it is not registered, i.e. I initialize it to null, and then only set it when I register it. This might not be perfect, but it does solve my crashes!
private Receiver mReceiver = null;
From my onServiceConnected:
sLog.debug("Registering receiver"); mReceiver = new Receiver(); registerReceiver(mReceiver, filter);
From my onServiceDisconnected:
if (mReceiver == null) { sLog.info("Do not unregister receiver as it was never registered"); } else { sLog.debug("Unregister receiver"); unregisterReceiver(mReceiver); mReceiver = null; }
A broadcast receiver should be unregister in the onPause()
lifecycle method
protected void onPause() { this.unregisterReceiver(reciever); super.onPause(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With