我通过扩展BroadcastReceiver
让我的类"ABC"。但最近,我偶然发现了LocalBroadcastManager
.
这是我的类声明:
public class ABC extends BroadcastReceiver {}
因此,ABC作为侦听器工作,并根据操作调用另一个对象。
我到处检查是否可以在没有活动的情况下在这里使用LocalBroadcastManager
。实际上,类ABC是一个核心应用程序类,它不连接到任何UI组件。
让我知道如何在我的方案中使用LocalBroadcastManager
。
我是安卓新手。请帮忙。
也许答案有点晚了,但我希望它对你有用。
第一步是拥有一个扩展应用程序的类。这将用于从活动外部获取应用程序上下文。
public class AppContext extends Application {
private static AppContext instance;
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将收到这个意图,正如我接下来向您展示的那样
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"));
}
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(context);
localBroadcastManager.registerReceiver(receiver); // or other operations