问题描述
我通过扩展 BroadcastReceiver
来获得我的班级 ABC 。但最近,我偶然发现了 LocalBroadcastManager
。
这是我的班级声明:
public class ABC extends BroadcastReceiver {}
因此,ABC作为监听器工作,并根据它将调用另一个对象的操作。 / p>
我到处检查是否可以在没有活动的情况下使用 LocalBroadcastManager
。实际上,ABC类是一个核心应用程序类,它不连接到任何UI组件。
让我知道如何在我的场景中使用 LocalBroadcastManager
。
我是Android新手。请帮忙。
也许答案有点晚了但我希望它对你有用。
第一步是有一个扩展应用程序的类。这将用于从Activity外部获取应用程序上下文。
public class AppContext extends Application {
private static AppContext实例;
public AppContext(){
instance = this;
}
public static Context getContext(){
return instance;
}
}
然后将以下代码添加到您想要的位置将消息发送到LocalBroadcasr
Intent intent = new Intent(intent-filter);
intent.putExtra(message,your-message-here);
LocalBroadcastManager.getInstance(AppContext.getContext())。sendBroadcast(intent);
最后,你的班级ABC会收到这个意图,因为我向你显示下一个
私有BroadcastReceiver接收器;
公共类ABC {
public ABC(){
receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context,Intent intent){
//在这里接收你的消息
String message = intent.getStringExtra(message);
};
LocalBroadcastManager.getInstance(AppContext.getContext())。registerReceiver(receiver,new IntentFilter(intent-filter));
}
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.
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"));
}
这篇关于如何在没有Activity的情况下使用LocalBroadcastManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!