How to use LocalBroadcastManager without Activity

拜拜、爱过 提交于 2019-12-05 02:48:53

问题


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


来源:https://stackoverflow.com/questions/18758613/how-to-use-localbroadcastmanager-without-activity

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