<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:
Oh, my fault. I forgot to add filter.addAction… for new intent.
I’m sorry. But answers was really useful! Thank you!
解决方法:
All of those are registered in manifest:
通常,您不对< intent-filter>中的操作字符串使用字符串资源,因为您从不希望对其进行国际化.
通常,您不使用< intent-filter>除非您要将服务公开给第三方应用程序,否则根本不会使用该服务.实际上,现在,您正在将服务公开给第三方应用程序,因此任何人都可以将这些命令发送到您的服务.
But only location_service_start and location_service_stop intents are received
不,服务均未接收到它们.您正在使用Java代码发送广播.服务不接收广播.
Functions that fires intents:
除非您知道自己在做什么,否则不要使用getApplicationContext().调用getApplicationContext()的对象都是上下文,因此可以仅在其上调用sendbroadcast().