Android interface Definition Language
如何通过Aidl进行跨进程间的服务调用?
在server端需要三步:
1) 创建一个aidl文件;
Package com.example.test
Interface AppConnect {
Void connect(String key, String value);
}
在定义好aidl之后,eclipe集成的ADT会编译直接在gen目录下生成AppConnect.java,googel在其中做不了少事,有兴趣的同学,可以看看;
2) 实现定义的接口;
private AppConnect.Stub mConnectBinder = new AppConnect.Stub() {
@Override
public void connect(String key, String value) throws RemoteException {
debugLog("key:"+key+" value:"+value);
}
};
3) 将你定义的接口显露给外部;
在实现好接口后,还需要提供给外部接口,而这里的接口就是(2)中的mConnectBinder。重载Service的OnBinder()接口,提供接口给外部:
public IBinder onBind(Intent arg0) {
debugLog("onBind mConnectBinder:"+mConnectBinder);
return mConnectBinder;
}
到此服务器端的工作完成,下面是client端的调用过程:
4) 在manifest.xml的Service中加入intent-filter,这个好像也可以不用;
<intent-filter>
<action android:name="com.example.test.AppConnectService"/>
</intent-filter>
Client端:
1) BindService,获得Serive接口;
static final String serviceActionName = " com.example.test.AppConnectService ";
private Context context = null;
private AppConnect mService = null;
public void ConnectStatService(Context ctx){
Log.d(TAG,"ConnectStatService");
context = ctx;
if (context != null) {
Intent intent = new Intent(serviceActionName);
context.bindService(intent,mConnection,Context.BIND_AUTO_CREATE);
}
}
public void DisConnectStatService(){
Log.d(TAG,"DisConnectStatService");
if (context != null) {
context.unbindService(mConnection);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name){
Log.d(TAG,"disconnect from service");
mService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = AppConnect.Stub.asInterface(service);
if(mService == null){
Log.d(TAG,"connect failed");
return;
}
Log.d(TAG,"finish invoking AIDL");
}
};
2) 接口调用
try {
mService.connect(appkey, value);
} catch (RemoteException e) {
e.printStackTrace();
}
总的来说,还是比较装简单的。具体的原理,暂没有细看。后续补充。
如何通过Aidl进行跨进程间的服务调用?
最新推荐文章于 2023-06-12 16:49:07 发布