I need to register a receiver. I have been using the following pattern:
@Override
protected void onResume() {
super.onResume();
registerReceiver(myReceiver, new IntentFilter(...));
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
...
});
I’m getting crash reports from marketplace about my unregisterReceiver() call:
java.lang.IllegalArgumentException: Receiver not registered
I thought this could not be possible, but it seems this is the correct pattern instead:
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 guess it’s possible for registration to fail, and we have to keep the result from registerReceiver(), and check it in onPause() before making the call to unregister()?
Thanks
I am basing the change off of this question:
Problem with BroadcastReceiver (Receiver not registered error)
I’ve only ever seen the first pattern above, never one where you check the intent response – any clarification would be great.
No, this isn’t necessarily going to work. From the docs for
registerReceiver(...)…In other words even if the call to register the receiver is successful, it may still return null if there are no sticky broadcasts for that intent filter.
My approach would be to simply use a boolean and a try/catch block…