我有几个活动发送到服务的意图。 那些所有登记在清单:Android:为什么intent不会被broadcastreciever收到?
<service android:name=".location.LocationService" android:label="@string/location_service_started">
<intent-filter>
<action android:name="@string/location_service_set" />
<action android:name="@string/location_service_start" />
<action android:name="@string/location_service_stop" />
</intent-filter>
</service>
但只有location_service_start和接收location_service_stop意图。可能是什么原因? 还有就是我的接收器代码:
private BroadcastReceiver LocationServiceReceiever = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(getString(R.string.location_service_stop)))
{
showMessage("stop");
}
if(intent.getAction().equals(getString(R.string.location_service_start)))
{
showMessage("start");
}
if(intent.getAction().equals(getString(R.string.location_service_set)))
{
showAlertBox("set");
}
}
};
所以我从来没有看到“设置”的消息。我甚至试着把sendBroadcast放在同一个地方的“开始”和“设置”消息,但所有东西都一样。 “开始” - 确定,“设置” - 从未收到。
功能将触发意图:
protected void start()
{
Intent intent = new Intent(getString(R.string.location_service_start));
getApplicationContext().sendBroadcast(intent);
}
protected void set(double lat, double lon, double rad)
{
Intent intent = new Intent(getString(R.string.location_service_set));
intent.putExtra("lat", lat);
intent.putExtra("lon", lon);
intent.putExtra("rad", rad);
getApplicationContext().sendBroadcast(intent);
}
都正确发送,没有错误,行动是正确的。
UPD:
哦,我的错。我忘了为新的意图添加filter.addAction ...。 对不起。但答案真的很有用!谢谢!
谢谢。这很有用。而且我知道不是服务,而是在服务中注册的广播接收机收到意图。但它不能解决问题。 – Ksice
“除非知道自己在做什么,否则不要使用getApplicationContext()” - 使用getApplicationContext()来广播超出当前Activity的范围会更好吗?我认为活动不会在广播未完成时被回收,但看到您的评论我不确定。你能评论吗? – auval
@uval:“使用getApplicationContext()进行广播,超出当前Activity的范围会更好吗?” - 没有。 “我认为活动不会在广播未完成时被回收” - 从广播者的角度来看,广播将在几微秒内“完成”。所有的框架级广播(例如'sendBroadcast()')都涉及IPC。因此,'Context'将广播请求发送到核心OS进程,此时'Context'的工作就完成了。 – CommonsWare