在Android中,如果我们需要在不同进程间实现通信,就需要用到AIDL技术去完成。
AIDL(Android Interface Definition Language)是一种接口定义语言,编译器通过*.aidl文件的描述信息生成符合通信协议的Java代码,我们无需自己去写这段繁杂的代码,只需要在需要的时候调用即可,通过这种方式我们就可以完成进程间的通信工作。关于AIDL的编写规则我在这里就不多介绍了,读者可以到网上查找一下相关资料。
接下来,我就演示一个操作AIDL的最基本的流程。
首先,我们需要建立一个服务端的工程,如图所以:
在IPerson.aidl中我们定义了一个“问候”的方法,代码如下:
package com.scott.aidl;
interface IPerson {
String greet(String someone);
}
在Eclipse插件的帮助下,编译器会自动在gen目录中生成对应的IPerson.java文件,格式化后的代码如下:
package com.scott.aidl;
public interface IPerson extends android.os.IInterface {
/** Local-side IPC implementation stub class. */
public static abstract class Stub extends android.os.Binder implements com.scott.aidl.IPerson {
private static final java.lang.String DESCRIPTOR = "com.scott.aidl.IPerson";
/** Construct the stub at attach it to the interface. */
public Stub() {
this.attachInterface(this, DESCRIPTOR);
}
/**
* Cast an IBinder object into an com.scott.aidl.IPerson interface,
* generating a proxy if needed.
*/
public static com.scott.aidl.IPerson asInterface(android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iin = (android.os.IInterface) obj.queryLocalInterface(DESCRIPTOR);
if (((iin != null) && (iin instanceof com.scott.aidl.IPerson))) {
return ((com.scott.aidl.IPerson) iin);
}
return new com.scott.aidl.IPerson.Stub.Proxy(obj);
}
public android.os.IBinder asBinder() {
return this;
}
@Override
public boolean onTransact(int code, an