2011-08-08 37 views
3

我有几个活动发送到服务的意图。 那些所有登记在清单: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 ...。 对不起。但答案真的很有用!谢谢!

回答

3

所有这些都登记在清单:

一般情况下,你不要在<intent-filter>使用字符串资源的操作字符串,因为你不希望他们国际化。

通常,除非您将该服务暴露给第三方应用程序,否则您根本不会使用<intent-filter>服务。事实上,现在,您将您的服务暴露给第三方应用程序,所以任何人都可以将这些命令发送到您的服务。

但只有location_service_start和location_service_stop意图接收

不,他们都不是由服务接收。您正在用Java代码发送广播。服务不收到广播。

功能将触发意图:

不要使用getApplicationContext()除非你知道自己在做什么。无论你打电话getApplicationContext() a Context,所以你可以拨打电话sendBroadcast()就可以了。

+0

谢谢。这很有用。而且我知道不是服务,而是在服务中注册的广播接收机收到意图。但它不能解决问题。 – Ksice

+0

“除非知道自己在做什么,否则不要使用getApplicationContext()” - 使用getApplicationContext()来广播超出当前Activity的范围会更好吗?我认为活动不会在广播未完成时被回收,但看到您的评论我不确定。你能评论吗? – auval

+1

@uval:“使用getApplicationContext()进行广播,超出当前Activity的范围会更好吗?” - 没有。 “我认为活动不会在广播未完成时被回收” - 从广播者的角度来看,广播将在几微秒内“完成”。所有的框架级广播(例如'sendBroadcast()')都涉及IPC。因此,'Context'将广播请求发送到核心OS进程,此时'Context'的工作就完成了。 – CommonsWare

1

复制&从this question粘贴我刚才回答。应该是同样的问题。

您必须将每个<action />标记放在清单中的单独<intent-filter />标记中。

这应该是一个错误,因为文档指出,你可以把多个动作的过滤器标签中:

零个或多个动作[..]标签应包括 里面描述的内容的过滤器。

Source

相关问题