aidl (android interface definition language) 是一种idl 语言,用于生成可以在android设备上两个进程之间进行进程间通信(interprocess communication, ipc)的代码。如果在一个进程中(例如activity)要调用另一个进程中(例如service)对象的操作,就可以使用aidl生成可序列化的参数。
aidl ipc机制是面向接口的,像com或corba一样,但是更加轻量级。它是使用代理类在客户端和实现端传递数据。
官方文档特别提醒我们何时使用aidl是必要的:只有你允许客户端从不同的应用程序为了进程间的通信而去访问你的service,以及想在你的service处理多线程。如果不需要进行不同应用程序间的并发通信(ipc),you should create your interface by implementing a binder;或者你想进行ipc,但不需要处理多线程的,则implement your interface using a messenger。无论如何,在使用aidl前,必须要理解如何绑定service——bindservice。如何绑定服务,请参考我的另一篇文章:http://blog.csdn.net/singwhatiwanna/article/details/9058143。这里先假设你已经了解如何使用bindservice。
创建一个android工程,用来充当跨进程通信的服务端。
创建一个包名用来存放aidl文件,比如com.ryg.sayhi.aidl,在里面新建imyservice.aidl文件,如果需要访问自定义对象,还需要建立对象的aidl文件,这里我们由于使用了自定义对象student,所以,还需要创建student.aidl和student.java。注意,这三个文件,需要都放在com.ryg.sayhi.aidl包里。下面描述如何写这三个文件。
imyservice.aidl代码如下:
[java] view
plaincopy
package com.ryg.sayhi.aidl;
import com.ryg.sayhi.aidl.student;
interface imyservice {
list<student> getstudent();
void addstudent(in student student);
}
说明:
aidl中支持的参数类型为:基本类型(int,long,char,boolean等),string,charsequence,list,map,其他类型必须使用import导入,即使它们可能在同一个包里,比如上面的student,尽管它和imyservice在同一个包中,但是还是需要显示的import进来。
另外,接口中的参数除了aidl支持的类型,其他类型必须标识其方向:到底是输入还是输出抑或两者兼之,用in,out或者inout来表示,上面的代码我们用in标记,因为它是输入型参数。
在gen下面可以看到,eclipse为我们自动生成了一个代理类
public static abstract class stub extends android.os.binder implements com.ryg.sayhi.aidl.imyservice
可见这个stub类就是一个普通的binder,只不过它实现了我们定义的aidl接口。它还有一个静态方法
public static com.ryg.sayhi.aidl.imyservice asinterface(android.os.ibinder obj)
这个方法很有用,通过它,我们就可以在客户端中得到imyservice的实例,进而通过实例来调用其方法。
student.aidl代码如下:
parcelable student;
说明:这里parcelable是个类型,首字母是小写的,和parcelable接口不是一个东西,要注意。
student.java代码如下:
import java.util.locale;
import android.os.parcel;
import android.os.parcelable;
public final class student implements parcelable {
public static final int sex_male = 1;
public static final int sex_female = 2;
public int sno;
public string name;
public int sex;
public int age;
public student() {
}
public static final parcelable.creator<student> creator = new
parcelable.creator<student>() {
public student createfromparcel(parcel in) {
return new student(in);
}
public student[] newarray(int size) {
return new student[size];
};
private student(parcel in) {
readfromparcel(in);
@override
public int describecontents() {
return 0;
public void writetoparcel(parcel dest, int flags) {
dest.writeint(sno);
dest.writestring(name);
dest.writeint(sex);
dest.writeint(age);
public void readfromparcel(parcel in) {
sno = in.readint();
name = in.readstring();
sex = in.readint();
age = in.readint();
public string tostring() {
return string.format(locale.english, "student[ %d, %s, %d, %d ]", sno, name, sex, age);
说明:通过aidl传输非基本类型的对象,被传输的对象需要序列化,序列化功能java有提供,但是android sdk提供了更轻量级更方便的方法,即实现parcelable接口,关于android的序列化,我会在以后写文章介绍。这里只要简单理解一下就行,大意是要实现如下函数
readfromparcel : 从parcel中读取对象
writetoparcel :将对象写入parcel
describecontents:返回0即可
parcelable.creator<student> creator:这个照着上面的代码抄就可以
需要注意的是,readfromparcel和writetoparcel操作数据成员的顺序要一致
创建一个service,比如名为myservice.java,代码如下:
/**
* @author scott
*/
public class myservice extends service
{
private final static string tag = "myservice";
private static final string package_sayhi = "com.example.test";
private notificationmanager mnotificationmanager;
private boolean mcanrun = true;
private list<student> mstudents = new arraylist<student>();
//这里实现了aidl中的抽象函数
private final imyservice.stub mbinder = new imyservice.stub() {
@override
public list<student> getstudent() throws remoteexception {
synchronized (mstudents) {
return mstudents;
}
}
public void addstudent(student student) throws remoteexception {
if (!mstudents.contains(student)) {
mstudents.add(student);
//在这里可以做权限认证,return false意味着客户端的调用就会失败,比如下面,只允许包名为com.example.test的客户端通过,
//其他apk将无法完成调用过程
public boolean ontransact(int code, parcel data, parcel reply, int flags)
throws remoteexception {
string packagename = null;
string[] packages = myservice.this.getpackagemanager().
getpackagesforuid(getcallinguid());
if (packages != null && packages.length > 0) {
packagename = packages[0];
log.d(tag, "ontransact: " + packagename);
if (!package_sayhi.equals(packagename)) {
return false;
return super.ontransact(code, data, reply, flags);
};
public void oncreate()
{
thread thr = new thread(null, new serviceworker(), "backgroundservice");
thr.start();
synchronized (mstudents) {
for (int i = 1; i < 6; i++) {
student student = new student();
student.name = "student#" + i;
student.age = i * 5;
mstudents.add(student);
mnotificationmanager = (notificationmanager) getsystemservice(notification_service);
super.oncreate();
public ibinder onbind(intent intent)
log.d(tag, string.format("on bind,intent = %s", intent.tostring()));
displaynotificationmessage("服务已启动");
return mbinder;
public int onstartcommand(intent intent, int flags, int startid)
return super.onstartcommand(intent, flags, startid);
public void ondestroy()
mcanrun = false;
super.ondestroy();
private void displaynotificationmessage(string message)
notification notification = new notification(r.drawable.icon, message,
system.currenttimemillis());
notification.flags = notification.flag_auto_cancel;
notification.defaults |= notification.default_all;
pendingintent contentintent = pendingintent.getactivity(this, 0,
new intent(this, myactivity.class), 0);
notification.setlatesteventinfo(this, "我的通知", message,
contentintent);
mnotificationmanager.notify(r.id.app_notification_id + 1, notification);
class serviceworker implements runnable
long counter = 0;
public void run()
{
// do background processing here.....
while (mcanrun)
{
log.d("scott", "" + counter);
counter++;
try
{
thread.sleep(2000);
} catch (interruptedexception e)
e.printstacktrace();
说明:为了表示service的确在活着,我通过打log的方式,每2s打印一次计数。上述代码的关键在于onbind函数,当客户端bind上来的时候,将imyservice.stub mbinder返回给客户端,这个mbinder是aidl的存根,其实现了之前定义的aidl接口中的抽象函数。
问题:问题来了,有可能你的service只想让某个特定的apk使用,而不是所有apk都能使用,这个时候,你需要重写stub中的ontransact方法,根据调用者的uid来获得其信息,然后做权限认证,如果返回true,则调用成功,否则调用会失败。对于其他apk,你只要在ontransact中返回false就可以让其无法调用imyservice中的方法,这样就可以解决这个问题了。
[html] view
<service
android:name="com.ryg.sayhi.myservice"
android:process=":remote"
android:exported="true" >
<intent-filter>
<category android:name="android.intent.category.default" />
<action android:name="com.ryg.sayhi.myservice" />
</intent-filter>
</service>
说明:上述的 <action android:name="com.ryg.sayhi.myservice" />是为了能让其他apk隐式bindservice,通过隐式调用的方式来起activity或者service,需要把category设为default,这是因为,隐式调用的时候,intent中的category默认会被设置为default。
新建一个客户端工程,将服务端工程中的com.ryg.sayhi.aidl包整个拷贝到客户端工程的src下,这个时候,客户端com.ryg.sayhi.aidl包是和服务端工程完全一样的。如果客户端工程中不采用服务端的包名,客户端将无法正常工作,比如你把客户端中com.ryg.sayhi.aidl改一下名字,你运行程序的时候将会crash,也就是说,客户端存放aidl文件的包必须和服务端一样。客户端bindservice的代码就比较简单了,如下:
import com.ryg.sayhi.aidl.imyservice;
public class mainactivity extends activity implements onclicklistener {
private static final string action_bind_service = "com.ryg.sayhi.myservice";
private imyservice mimyservice;
private serviceconnection mserviceconnection = new serviceconnection()
public void onservicedisconnected(componentname name)
mimyservice = null;
public void onserviceconnected(componentname name, ibinder service)
//通过服务端onbind方法返回的binder对象得到imyservice的实例,得到实例就可以调用它的方法了
mimyservice = imyservice.stub.asinterface(service);
try {
student student = mimyservice.getstudent().get(0);
showdialog(student.tostring());
} catch (remoteexception e) {
e.printstacktrace();
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
button button1 = (button) findviewbyid(r.id.button1);
button1.setonclicklistener(new onclicklistener() {
public void onclick(view view) {
if (view.getid() == r.id.button1) {
intent intentservice = new intent(action_bind_service);
intentservice.setflags(intent.flag_activity_new_task);
mainactivity.this.bindservice(intentservice, mserviceconnection, bind_auto_create);
public void showdialog(string message)
new alertdialog.builder(mainactivity.this)
.settitle("scott")
.setmessage(message)
.setpositivebutton("确定", null)
.show();
protected void ondestroy() {
if (mimyservice != null) {
unbindservice(mserviceconnection);
可以看到,当点击按钮1的时候,客户端bindservice到服务端apk,并且调用服务端的接口mimyservice.getstudent()来获取学生列表,并且把返回列表中第一个学生的信息显示出来,这就是整个ipc过程,需要注意的是:学生列表是另一个apk中的数据,通过aidl,我们才得到的。另外,如果你在ontransact中返回false,将会发现,获取的学生列表是空的,这意味着方法调用失败了,也就是实现了权限认证。