我有一个主应用程序,我们称之为“app”,然后有名为“module1”和“module2”的子模块。这些模块是“app”的依赖项。
“app”启动“module1”,它完成其工作后广播一条消息,该消息应该被“app”接收,以便它可以继续其流程。但是,我似乎无法在“app”中成功接收它。
我想知道,是否可能从子模块发送广播消息?
模块应尽可能独立于主应用程序,以便也可以与其他应用程序一起使用,例如插件。这就是为什么我没有在主应用程序的清单中添加与模块相关的内容。模块有自己的清单。
广播在模块内部正常工作。
代码非常直观:
public class MyReceiver extends BroadcastReceiver {
mFilter = new IntentFilter("com.myapp.main.CUSTOM_INTENT");
mReceiver = new MyReceiver();
@Override
public void onReceive(Context context, Intent intent) {
Log.i(Constants.TAG, "receiver worked");
}
// constructor
public MyReceiver(){
}
}
在清单文件中:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.myapp.main.CUSTOM_INTENT" />
</intent-filter>
</receiver>
在子模块中:
Intent intent = new Intent("com.myapp.main.CUSTOM_INTENT");
intent.putExtra("value", 0);
sendBroadcast(intent);
LocalBroadcastManager
或其他形式的进程内事件总线(例如greenrobot的EventBus,Square的Otto),以获得更好的性能、安全性和简洁性。 - CommonsWare