【发布时间】:2019-07-16 10:14:33
【问题描述】:
我正在尝试从我的 MainActivity 向服务发送意图,并从该服务开始向 BroadcastReceiver 发送广播意图。第一个意图被触发并被服务接收。服务中的广播意图被触发,但广播接收器没有接收到它
以下是我所做的:
- 配置 AndroidManifest.xml 以包含服务和接收者的详细信息
- 在服务中注册广播接收器
广播接收方代码:
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "Inside onReceive of myReceiver: " + intent.getAction());
if (intent.getAction() == "com.utils.myapp.MY_STUFF")
{
// Do something here
}
}
服务代码:
public class MyService extends IntentService {
private static BroadcastReceiver myReceiver = new MyReceiver();
...
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "Inside onHandleIntent() of service");
String action = intent.getStringExtra("ACTION");
Log.i(TAG, "ACTION: " + action);
if (action == "FIRE_INTENT_TO_RECEIVER")
{
Intent rec_intent = new Intent("com.utils.myapp.MY_STUFF");
sendBroadcast(rec_intent);
}
}
在主要活动中:
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("ACTION", "FIRE_INTENT_TO_RECEIVER");
this.startService(serviceIntent);
AndroidManifest.xml:
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="FIRE_INTENT_TO_RECEIVER" />
</intent-filter>
</service>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true"
android:priority="2147483647">
<intent-filter>
<!-- Some actions here-->
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
预期结果:应该到达 BroadcastReceiver 中的 onReceive() 实际结果:没有达到onReceive()
【问题讨论】:
-
您的接收者在
intent-filter部分中缺少正确的category名称 -
实际结果:未达到 onReceive() 好吧,根据官方文档,这是预期结果(至少 >= oreo )
-
您需要使用
new Intent(this, MyReceiver.class);明确指定广播的目标组件。自 Oreo 以来,隐式广播将被丢弃。 -
首先我会更加关注以下行:
if (action == "FIRE_INTENT_TO_RECEIVER") {... -
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);试试这个发送广播
标签: android