-->

How to use LocalBroadcastManager without Activity

2019-03-31 13:10发布

问题:

I had my class 'ABC' by extending the BroadcastReceiver. But recently, I stumbled upon LocalBroadcastManager.

here is my class declaration:

public class ABC extends BroadcastReceiver {}

So ABC is working as the listener and based on the action it would call another object.

I checked everywhere whether I can use LocalBroadcastManager here without an activity. Actually class ABC is a core application class where it doesn't connect to any UI component.

Let me know how can I use LocalBroadcastManager in my scenario.
I'm new to Android. Please help.

回答1:

Maybe it's a bit late for the answer but I hope it'd be useful to you.

The first step is having a class which extends the application. This will be used to get the application context from outside an Activity.

public class AppContext extends Application {

    private static AppContext instance;

    public AppContext() {
      instance = this;
    }

    public static Context getContext() {
      return instance;
    }
}

Then add the following piece of code where you want to send the message to LocalBroadcasr

Intent intent = new Intent("intent-filter");
intent.putExtra("message", "your-message-here");
LocalBroadcastManager.getInstance(AppContext.getContext()).sendBroadcast(intent);

Finally, your class ABC will receive this intent as I show you next

private BroadcastReceiver receiver;

public class ABC{

public ABC(){
    receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
      //receive your message here
      String message = intent.getStringExtra("message");
    };
        LocalBroadcastManager.getInstance(AppContext.getContext()).registerReceiver(receiver, new IntentFilter("intent-filter")); 
}


回答2:

LocalBroadcastManager  localBroadcastManager = LocalBroadcastManager.getInstance(context);
localBroadcastManager.registerReceiver(receiver); // or other operations