Matt J. Matt J. - 2 months ago 11
Android Question

Is it OK to unregister 'dynamic' BroadcastReceiver from receiver's own onReceive() method?

That is, I have this BroadcastReceiver I create on the fly to listen for one broadast, after which I want it to unregister itself.

I haven't found any sample code that does it this way, but neither have I found any rule in the android online docs that forbids this. But I cannot let it hang around for as long as the activity, and it is in an anonymous class anyway, so the containing class does not even know the variable name.

That is, the code looks something like this:

myInfoReceiver = new BroadcastReceiver() {
onReceive(Context ctx, Intent intt) {
// do some Notification when I get here
nm.notify("I got here") // obvious pseudo code
ctx.unregisterReceiver(myInfoReceiver);
} // end onReceive
ctx.registerReceiver),uInfoReceiver, new IntentFilter(...));
}; // end BroadcastReceiver


But when I run this, Android complains when it calls unregister, insisting that the receiver is not there to unregister (I forget the exact wording, but it threw IllegalArgumentException).

I also tried modifying the code to check that the action in 'intt' is the same as expected -- but then it still executest onReceive but silently fails to unregister.

Answer

The answer to your question is "yes". However...

...you need to call unregisterReceiver() on the same Context that you called registerReceiver() on. In the code you posted you are calling unregisterReceiver() on the Context passed in as an argument to onReceive(). This is not the same Context which is why you are getting the exception.