可以从接收者自己的onReceive()方法中注销“动态" BroadcastReceiver吗? [英] Is it OK to unregister 'dynamic' BroadcastReceiver from receiver's own onReceive() method?

查看:80
本文介绍了可以从接收者自己的onReceive()方法中注销“动态" BroadcastReceiver吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也就是说,我有一个我即时创建的BroadcastReceiver来监听一个广播,然后希望它取消注册.

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

我还没有找到任何这样做的示例代码,但是我也没有在android在线文档中找到任何禁止此操作的规则.但是我不能让它在活动中停留这么长时间,而且它仍然在一个匿名类中,因此包含类甚至都不知道变量名.

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

但是,当我运行此程序时,Android会在调用unregister时抱怨,坚持认为接收者不在那儿进行注销(我忘记了确切的用词,但引发了IllegalArgumentException).

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).

我还尝试修改代码以检查'intt'中的动作是否与预期的相同-但随后它仍然执行onReceive,但无声地无法注销.

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...

...您需要在调用registerReceiver()的同一Context上调用unregisterReceiver().在您发布的代码中,您正在作为参数传递给onReceive()Context上调用unregisterReceiver().这与Context不同,这就是为什么您要获取异常.

...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.

这篇关于可以从接收者自己的onReceive()方法中注销“动态" BroadcastReceiver吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆