客户端在执行bindService的时候,成功绑定服务之后,会回调MyConnection的onServiceConnected(),并且传回了服务端的通信接口抽象类Stub,抽象类Stub是继承自Binder对象,Binder对象是IBinder的实现类。此IBinder即服务onBind()时返回的IBinder。
DataService.aidl
package com.example.serivceractivity.service;
interface DataService{
double getData(String args);
}
测试在ServiceConnection的onServiceConnection回调函数中,以及在Service的onBind中分别打印一下Binder就好了,如下代码
MyService中的onBind方法:
@Override
public IBinder onBind(Intent intent) {
System.out.println("bind的方法启动");
// 被绑定后返回一个aidl远程服务接口实现类(DataService.Stub)的子类(MyBinder)
// 返回该类后其中就有aidl远程接口中方法的具体实现getData()
MyBinder mBinder= new MyBinder();
System.out.println("MyService中的Binder"+mBinder.getClass());
return mBinder;
}
//定义提供给Client端用的方法
public class MyBinder extends DataService.Stub {
@Override
public double getData(String args) throws RemoteException {
if (args.equals("a")) {
return 1d;
} else if (args.equals("b")) {
return 2d;
}
return 0;
}
}
MainActivity中实现ServiceConnection的类MyConnection
public class MyConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
dataservice = DataService.Stub.asInterface(service);
/*
* 如果是跨进程就是会返回 BinderProxy type:class android.os.BinderProxy
* 与onBind中打印的结果是不一致的。 跨进程才有transact和Ontransact通信
*/
/*
* 如果是非跨进程,在onServiceConnection与onBind的打印的内容是一模一样的
*/
System.out.println("ServiceConnectiontype:" + service.getClass());
// aidl的client连接上class
// com.example.serivceractivity.service.DataService$Stub$Proxy
System.out.println("ServiceConnectionaidl的client连接上" + dataservice.getClass());
}
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("断开连接");
}
}
1) 利用android:process=”:remote”设置为相同的进程间传输 。如下
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:process=":remote"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.serviceclient.MyService"
android:exported="true"
android:process=":remote"
>
<intent-filter>
<action android:name="com.example.serviceclient.service.action" />
</intent-filter>
</service>
运行结果:
2) 取消Activity的android:process=”:remote”设置为不相同的进程间传输
<activity
android:name=".MainActivity"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.serviceclient.MyService"
android:exported="true"
android:process=":remote"
>
<intent-filter>
<action android:name="com.example.serviceclient.service.action" />
</intent-filter>
</service>
“`
运行结果: