遠程Service的顯示 / 隱式啟動


  在進程間通信時,常會設計開啟遠程 Service 的情況。開啟遠程 Service 的方式有兩種,一種時顯示開啟,一種是隱式開啟。下面分別來看:

一、隱式開啟

  服務端:Service 所在 AndroidManifest.xml 中的配置如下,注意 exported = "true" ,為 true 才可被其他 App 訪問,否則就只限於應用內。

 <service
       android:name=".BookManagerService"
       android:exported="true">
       <intent-filter>
           <action android:name="com.sl.aidl"/>
           <category android:name="android.intent.category.DEFAULT"/>
       </intent-filter>
</service>

  客戶端:需要開啟遠程服務

Intent service = new Intent();
service.setAction("com.sl.aidl"); //service 的 action 值
service.setPackage("com.sl.binderservice"); //遠程服務所在包名
//綁定服務 bindService(service, mConnection, Context.BIND_AUTO_CREATE);
//啟動服務
startService(service);

二、顯示開啟

  服務端:AndroidManifest.xml

<service android:name=".BookManagerService" android:exported="true"/>

  客戶端

public static final String NAME_REMOTE_SERVICE = "com.sl.binderservice.BookManagerService" ;
public static final String PACKAGE_REMOTE_SERVICE = "com.sl.binderservice" ;
//啟動服務
Intent startIntent = new Intent ();
ComponentName componentName = new ComponentName(PACKAGE_REMOTE_SERVICE ,NAME_REMOTE_SERVICE);
startIntent .setComponent (componentName );
startService( startIntent) ;
//綁定服務
Intent startIntent = new Intent ();
ComponentName componentName = new ComponentName(PACKAGE_REMOTE_SERVICE ,NAME_REMOTE_SERVICE);
startIntent .setComponent (componentName );
bindService( startIntent, mConnection, Context.BIND_AUTO_CREATE) ;    

  以上就是這兩種開啟方式。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM