远程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) ;    

  以上就是这两种开启方式。

原文地址:https://www.cnblogs.com/aimqqroad-13/p/8921227.html