广播接收器在Singleton类没有接受意图 [英] BroadcastReceiver in Singleton class not receiving intents

查看:232
本文介绍了广播接收器在Singleton类没有接受意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这不是接收广播意图单个类的广播接收机。

I have a Broadcast receiver in a singleton class that's not receiving Broadcast intents.

单例与上下文初始化(即的getInstance(上下文))。

The singleton is initialized with a context (i.e. getInstance(context)).

我打电话的getContext()sendBroadcast(意向)。但广播接收器并没有得到任何东西。我已经证实了这一意图过滤器是匹配的。

I call getContext().sendBroadcast(intent); but the BroadcastReceiver doesn't get anything. I've confirmed the intent filters are matching.

我注册接收器的方式是在我的单身构造像这样

The way I register the receiver is in my singleton constructor like so

private class Singleton(Context context) {
    context.registerReceiver(mReceiver, INTENT_FILTER);
....

private onDestroy(Context context) {
    context.unregisterReceiver(mReceiver);
....

这是怎么回事!?

What's going on!?

推荐答案

行,所以我想通了,我做错了什么。是由活动创建的辛格尔顿,因此传递的上下文是活动上下文因此,我需要我的构造更新到这一点:

OK so I figured out what I did wrong. The Singleton is being created by activity and hence the context being passed in is an Activity Context. Hence I needed to update my constructor to this:

private class Singleton(Context context) {
    context.getApplicationContext().registerReceiver(mReceiver, INTENT_FILTER);

不知道为什么这有差别。我的猜测是,活动场景被破坏,因此它的广播接收器?额外的观点是值得欢迎的!

Not sure why this makes a difference. My guess is that the activity context is destroyed and hence the BroadcastReceiver with it? Additional insight is welcome!

这篇关于广播接收器在Singleton类没有接受意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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