1、AIDL和Binder
Android系统四大组件Activity, Content Provider, Broadcast和Service均可以进行跨进程数据传输。
Activity可以隐式调用其他进程的Activity; Content Provier可以跨进程访问其他应用中的数据;Broadcast通过广播的方式与其他应用进行通讯;Service则是通过Binder实现RPC
Binder的实现机制很复杂,在这里不展开叙述,只需要知道它是C/S模式实现RPC(Remote Procedure Call Protocol)——远程过程调用协议。例如应用程序A提供实现了加减乘除的操作,并对外提供的操作接口,其他应用程序就可以远程调用应 用程序A提供的接口实现运算,而不需要自己实现;
那么AIDL是什么呢,AIDL是AndroidInterface definition language的缩写,是android接口定义语言。把Binder比作一个管道,AIDL则定义了该管道中传输数据的格式。
下面我们以实例讲解如何使用AIDL实现远程服务的调用
2、服务端的实现
1、在Eclipse中新建Android工程,工程命名为Service。在Service工程的src目录上右键新建包,起名为com.example.aild;在新建的包中增加普通文件,命名为IRemoteService.aidl,标明该服务对外提供getPid()和basicTypes()两个接口;
package com.example.aidl;
interface IRemoteService {
/** Request the process ID of this service, to do evil things with it. */
int getPid();
/** Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
aidl文件完成后,在gen目录下会自动生成com.example.aild包和IRemoteService.java文件,我们不需要进行任何修改,完成后,Service目录结构如下
2、在com.example.service下新建服务类AIDLService.java,代码如下
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.Process;
import android.util.Log;
import com.example.aidl.IRemoteService;
public class AIDLService extends Service {
private String TAG = "REMOTESERVICE";
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d(TAG, "DDService onBind");
return mBinder;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d(TAG, "DDService onCreate........" + "Thread: " + Thread.currentThread().getName());
}
/*与本地服务不同,此处新建Stub类型的Binder*/
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() {
public int getPid(){
Log.d(TAG, "Thread: " + Thread.currentThread().getName());
/*返回给调用者当前的线程编号*/
return (int) Thread.currentThread().getId();
}
public int basicTypes(int anInt, long aLong, boolean aBoolean,
float aFloat, double aDouble, String aString) {
Log.d(TAG, "Thread: " + Thread.currentThread().getName());
Log.d(TAG, "basicTypes aDouble: " + aDouble +" anInt: " + anInt+" aBoolean " + aBoolean+" aString " + aString);
/*返回给调用者当前的线程编号*/
return (int) Thread.currentThread().getId();
}
};
}
可以看到,与本地服务不同的是,我们在onBind()中返回的是IRemoteService.Stub类型的变量,Stub类实际上是继承自Binder,并且定义了我们在AIDL中定义的接口;需要我们实现这些接口,即getPid()和basicTypes();
3、在AndroidMainfest.xml中声明该服务
<service android:name=".AIDLService"
android:process=":xlzh" >
<intent-filter>
<action android:name="com.example.aidl" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
在Serivce的属性中增加了android:process,其中冒号后可自己随意填写