接收应用模块中的android库模块发送的广播时遇到问题。
我创建了带有动作和组件名称的显式广播。并从android lib模块发送此广播。
val intent = Intent()
intent.action = "com.example.action.SOME_ACTION"
intent.component = ComponentName("com.example", "com.example.MyReceiver")
sendBroadcast(intent)
为了接收此广播,我创建了一个接收器并将其注册在清单中。
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.action.SOME_ACTION" />
</intent-filter>
</receiver>
此接收者打印收到的事件,但是很遗憾,我没有收到任何广播。我有什么想念的吗?还是应该是这种方式,即您无法接收从图书馆发送的广播?
尝试这样做,这对我有用
使用此代码在您想接收的接收者处注册
IntentFilter filter = new IntentFilter();
filter.addAction("myCustomAction");
registerReceiver(receiver, filter);
像这样从其他库发送广播
Intent intent = new Intent("myCustomAction");
intent.putExtra("value", 0);
intent.setComponent(null);
context.sendBroadcast(intent);
现在无需在AndroidManifest.xml
中注册接收器
将ComponentName
设置为null,因为
用于处理以下内容的应用程序组件的名称intent,或者为null,以使系统为您找到一个。