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.
The answer to your question is "yes". However...
...you need to call
unregisterReceiver()
on the sameContext
that you calledregisterReceiver()
on. In the code you posted you are callingunregisterReceiver()
on theContext
passed in as an argument toonReceive()
. This is not the sameContext
which is why you are getting the exception.