BroadcastReceiver in Singleton class not receiving intents

空扰寡人 提交于 2019-12-12 04:06:48

问题


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

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

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!?


回答1:


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!



来源:https://stackoverflow.com/questions/18283967/broadcastreceiver-in-singleton-class-not-receiving-intents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!