android 中通过 AIDL (Android Interface definition language) 机制 (远程服务调用)实现进程间的通信。
1. aidl是 Android Interface definition language的缩写,一看就明白,它是一种android内部进程通信接口的描述语言,通过它我们可以定义进程间的通信接口
icp:interprocess communication :内部进程通信
既然aidl可以定义并实现进程通信,那么我们怎么使用它呢?文档/android-sdk/docs/guide/developing/tools/aidl.html中对步骤作了详细描述:
--2.1.Create your .aidl file - This file defines an interface (YourInterface.aidl) that defines the methods and fields available to a client.
我在后面给出了一个例子,它的aidl文件定义如下:写法跟java代码类似,但是这里有一点值得注意的就是它可以引用其它aidl文件中定义的接口,但是不能够引用你的java类文件中定义的接口
package com.cao.android.demos.binder.aidl; import com.cao.android.demos.binder.aidl.AIDLActivity; interface AIDLService { void registerTestCall(AIDLActivity cb); void invokCallBack(); }
--2.3.Implement your interface methods - The AIDL compiler creates an interface in the Java programming language from your AIDL interface. This interface has an inner abstract class named Stub that inherits the interface (and implements a few additional methods necessary for the IPC call). You must create a class that extends YourInterface.Stub and implements the methods you declared in your .aidl file.
private final AIDLService.Stub mBinder = new AIDLService.Stub() { @Override public void invokCallBack() throws RemoteException { Log("AIDLService.invokCallBack"); Rect1 rect = new Rect1(); rect.bottom=-1; rect.left=-1; rect.right=1; rect.top=1; callback.performAction(rect); } @Override public void registerTestCall(AIDLActivity cb) throws RemoteException { Log("AIDLService.registerTestCall"); callback = cb; } };
--2.4.Expose your interface to clients - If you're writing a service, you should extend Service and override Service.onBind(Intent) to return an instance of your class that implements your interface.
AIDLService mService; private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { Log("connect service"); mService = AIDLService.Stub.asInterface(service); try { mService.registerTestCall(mCallback); } catch (RemoteException e) { } } public void onServiceDisconnected(ComponentName className) { Log("disconnect service"); mService = null; } };mService就是AIDLService对象,具体可以看我后面提供的示例代码,需要注意在客户端需要存一个服务端实现了的aidl接口描述文件,但是客户端只是使用该aidl接口,不需要实现它的Stub类,获取服务端得aidl对象后mService = AIDLService.Stub.asInterface(service);,就可以在客户端使用它了,对mService对象方法的调用不是在客户端执行,而是在服务端执行。
aidl中使用java类,需要实现Parcelable接口,并且在定义类相同包下面对类进行声明:
上面我定义了Rect1类
之后你就可以在aidl接口中对该类进行使用了
package com.cao.android.demos.binder.aidl; import com.cao.android.demos.binder.aidl.Rect1; interface AIDLActivity { void performAction(in Rect1 rect); }
链接:
原文:http://blog.csdn.net/stonecao/article/details/6425019
Android中AIDL使用例子