android 提供的进程间通信的框架是aidl,使用他可以更方便的进行进程间的通信,现在让我们来写一个demo。
进程间通信,分为两个角色,服务端和客户端,服务端提供技术支持,客户端申请服务端方法。
首先我们写编写服务端进程:
第一步:是创建.aidl文件,该文件就是告诉其他客户端我可以提供哪些技术的支持
interface AidlTest {
String getName(String name);
}
第二步:编译完成后,我们就要实现.aidl文件中的方法,我们需要创建一个Stub类,继承AidlTest.Stub类
public class AidlTestStub extends AidlTest.Stub{
@Override
public String getName(String name) throws RemoteException {
return "xxx";
}
}
第三步:实现了方法后,接下来我们就要通过Service的方法将该stub对象输出给其他进程。
/**
* Created by malei on 2018/11/13.
* 对外提供服务的binder
*/
public class AidlTestNative extends Service {
private AidlTestStub mStub;
@Override
public void onCreate() {
super.onCreate();
mStub = new AidlTestStub();
}
public String getName(String name) throws RemoteException {
return mStub.getName(name);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mStub;
}
}
然后给service进行注册
<service android:name=".AidlTestNative"
android:enabled="true"
android:process=":marsservice"/>
第四步:编写客户端代码
客户端要链接到其他进程,就需要使用bindService()
Intent intent = new Intent(this, AidlTestNative.class);
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
然后获取进程的链接状态和其他进程的IBinder
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.e(getLocalClassName(), "service connected");
mAidlManager = AidlTest.Stub.asInterface(service);
mBound = true;
if (mAidlManager != null) {
try {
String namex = mAidlManager.getName("x");
Log.i("TAG",namex);
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e(getLocalClassName(), "service disconnected");
mBound = false;
}
};