BroadcastReceiver in Singleton class not receiving

2019-08-30 18:27发布

问题:

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!