My current Android application employs an IntentService
to call a SOAP WebService.
The IntentService
returns the SOAP response data to the calling activity via a LocalBroadcastManager
from within its onHandleIntent()
method
final Intent localIntent = new Intent(FASTEST_BROADCAST_ACTION);
localIntent.putExtra(FASTEST_EXTENDED_DATA, xmlUtility.getFastestServiceId());
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(localIntent);
My calling activity registers a broadcast listener as follows in its onResume()
method
@Override
protected void onResume() {
super.onResume();
mDepartureBroadcastReceiver = new DepartureBroadcastReceiver();
final IntentFilter statusIntentFilter = new IntentFilter(FASTEST_BROADCAST_ACTION);
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mDepartureBroadcastReceiver, statusIntentFilter);
Log.v(LOG_TAG, "Register receiver = " + mDepartureBroadcastReceiver);
}
Everything works fine, the Web Service is called and the required response data is returned to my activity.
The issue comes when I leave the current activity and attempt to call unregisterReceiver
I have this code in my onPause
method:-
/**
* Dispatch onPause() to fragments.
*/
@Override
protected void onPause() {
super.onPause();
if (mDepartureBroadcastReceiver == null) {
//INTENTIONALLY LEFT BLANK
} else {
try {
Log.v(LOG_TAG, "About to unregister receiver");
unregisterReceiver(mDepartureBroadcastReceiver);
Log.v(LOG_TAG, "Successfully unregistered receiver");
} catch (final Exception exception) {
Log.e(LOG_TAG, "Failed unregistered receiver", exception);
} finally {
mDepartureBroadcastReceiver = null;
}
}
}
I always get this exception:-
Failed unregistered receiver java.lang.IllegalArgumentException: Receiver not registered
The receiver registered:-
Register receiver = com.aaa.bbb.departure.DepartureBroadcastReceiver@2879575
Matches the exception:-
java.lang.IllegalArgumentException: Receiver not registered: com.aaa.bbb.departure.DepartureBroadcastReceiver@2879575
Why does this exception occur?
Why cant I unregister this receiver?
Is it due to my IntentService
finishing (e.g calling its onDestroy()
method) before I call unregister?
You aren't unregistering using the LocalBroadcastManager
.
You need to use this LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mDepartureBroadcastReceiver);