Android ApiDemos示例解析(43):App->Service->Remote Service Controller

Remote Service Controller 和使用Local Service的Android ApiDemo示例解析(40):App->Service->Local Service Controller

都是使用Service的“Started” 模式,RemoteService在 AndroidManifest.xml中的定義如下:

<service android:name=”.app.RemoteService” android:process=”:remote”>
<intent-filter>
< !– These are the interfaces supported by the service, which
you can bind to. –>
<action android:name=”com.example.android.apis.app.IRemoteService” />
<action android:name=”com.example.android.apis.app.ISecondary” />
< !– This is an action code you can use to select the service
without explicitly supplying the implementation class. –>
<action android:name=”com.example.android.apis.app.REMOTE_SERVICE” />
< /intent-filter>
< /service>

RemoteService.Controller 中啟動和停止Service的代碼如下,和“Bound” Service模式相比要簡單的多:

[java] 
// Make sure the service is started.  It will continue running  
// until someone calls stopService().  
// We use an action code here, instead of explictly supplying  
// the component name, so that other packages can replace  
// the service.  
startService(new Intent( 
 "com.example.android.apis.app.REMOTE_SERVICE")); 
  
… … 
  
 // Cancel a previous call to startService().  Note that the  
// service will not actually stop at this point if there are  
// still bound clients.  
stopService(new Intent( 
 "com.example.android.apis.app.REMOTE_SERVICE")); 
// Make sure the service is started.  It will continue running
// until someone calls stopService().
// We use an action code here, instead of explictly supplying
// the component name, so that other packages can replace
// the service.
startService(new Intent(
 "com.example.android.apis.app.REMOTE_SERVICE"));
 
… …
 
 // Cancel a previous call to startService().  Note that the
// service will not actually stop at this point if there are
// still bound clients.
stopService(new Intent(
 "com.example.android.apis.app.REMOTE_SERVICE"));

“Started” Service在啟動之後會一直運行,直到調用stopService為止。因此在按“Start Service”後,在運行 Android ApiDemo示例解析(42):App->Service->Remote Service Binding 來綁定這個RemoteService,由於RemoteService已經啟動,你會發現例42中的Received from Service的初始值一般不會為1。

作者:mapdigit
 

 

發佈留言