Correct template for registering the receiver?

I need to register the receiver. I used the following template:

@Override protected void onResume() { super.onResume(); registerReceiver(myReceiver, new IntentFilter(...)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(myReceiver); } private BroadcastReceiver myReceiver = new BroadcastReceiver() { ... }); 

I get crash reports from the market about my unregisterReceiver () call:

 java.lang.IllegalArgumentException: Receiver not registered 

I thought this was not possible, but it looks like this is the correct template:

 private Intent mIntent; @Override protected void onResume() { super.onResume(); if (mIntent == null) { mIntent = registerReceiver(myReceiver, new IntentFilter(...)); } } @Override protected void onPause() { super.onPause(); if (mIntent != null) { unregisterReceiver(myReceiver); mIntent = null; } } private BroadcastReceiver myReceiver = new BroadcastReceiver() { ... }); 

Is the above the correct pattern? I assume that registration may fail, and should we save the result from registerReceiver () and check it in onPause () before making a call to unregister ()?

thanks


I base a change on this question: Problem with BroadcastReceiver (Recipient registration error)

I saw only the first template above, nowhere where you check the answer for intent - any refinement will be wonderful.

+7
source share
1 answer

Is the above the correct pattern?

No, this will not necessarily work. From the docs for registerReceiver(...) ...

Returns . The first sticky design found what matches the filter, or null if none exist.

In other words, even if the call to register the receiver is successful, it can still return null if there are no sticky translations for this intent filter.

My approach would be to just use a boolean and a try / catch block ...

 private boolean isReceiverRegistered; @Override protected void onResume() { super.onResume(); if (!isReceiverRegistered) { registerReceiver(myReceiver, new IntentFilter(...)); isReceiverRegistered = true; } } @Override protected void onPause() { super.onPause(); if (isReceiverRegistered) { try { unregisterReceiver(myReceiver); } catch (IllegalArgumentException e) { // Do nothing } isReceiverRegistered = false; } } 
+5
source

All Articles