Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird "Receiver not registered" exception

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.

like image 997
fhucho Avatar asked Feb 12 '11 12:02

fhucho


People also ask

Do we need to unregister broadcast receiver?

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).

How do you check if receiver is registered or not?

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.


2 Answers

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; } 
like image 155
Dan J Avatar answered Oct 10 '22 13:10

Dan J


A broadcast receiver should be unregister in the onPause() lifecycle method

protected void onPause() {     this.unregisterReceiver(reciever);     super.onPause(); } 
like image 22
Sunil Pandey Avatar answered Oct 10 '22 13:10

Sunil Pandey