也许答案有点晚了,但我希望它对你有用。
第一步是拥有一个扩展应用程序的类。这将用于从 Activity 外部获取应用程序上下文。
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"));
}