android使用aidl实现进程间通讯

Android每一个应用程序都有本身的进程,当须要在不一样的进程之间传递对象时,该如何实现呢?java

显然,Java中是不支持跨进程内存共享的。所以要传递对象须要把对象解析成操做系统可以理解的数据格式以达到跨界对象访问的目的。JavaEE中,采用RMI经过序列化传递对象。android

AndroidAIDL(Android Interface Definition Language:接口定义语言)方式实现。eclipse


AIDL是一种接口定义语言,用于约束两个进程间的通信规则,供编译器生成代码,实现Android设备上的两个进程间通讯(IPC)因为进程之间的通讯信息须要双向转换,因此android采用代理类在背后实现了信息的双向转换,代理类由android编译器生成,对开发人员来讲是透明的。ide


具体实现this

假设A应用须要与B应用进行通讯,调用B应用中的download(String path)方法,B应用以Service方式向A应用提供服务。须要下面四个步骤spa

1 在B应用中建立*.aidl文件aidl文件的定义和接口的定义很相类,如:在com.alex.aidl包下建立IDownloadService.aidl文件,内容以下:操作系统

package com.alex.aidl;
interface IDownloadService {
void download(String path);
}

当完成aidl文件建立后,eclipse会自动在项目的gen目录中同步生成IDownloadService.java接口文件。接口文件中生成一个Stub的抽象类,里面包括aidl定义的方法,还包括一些其它辅助方法。值得关注的是asInterface(IBinder iBinder),它返回接口类型的实例,对于远程服务调用,远程服务返回给客户端的对象为代理对象,客户端在onServiceConnected(ComponentName name, IBinder service)方法引用该对象时不能直接强转成接口类型的实例,而应该使用asInterface(IBinder iBinder)进行类型转换。代理


2B应用中实现aidl文件生成的接口(本例是IDownloadService),但并不是直接实现接口,而是经过继承接口的Stub来实现(Stub抽象类内部实现了aidl接口),而且实现接口方法的代码。内容以下:code

public class ServiceBinder extends IDownloadService.Stub {
@Override
public void download(String path) throws RemoteException {
Log.i("DownloadService", path);
}
}

3 在B应用中建立一个Service(服务),在服务的onBind(Intent intent)方法中返回实现了aidl接口的对象(本例是ServiceBinder)。内容以下:xml

public class DownloadService extends Service {
private ServiceBinder serviceBinder = new ServiceBinder();
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
public class ServiceBinder extends IDownloadService.Stub {
@Override
public void download(String path) throws RemoteException {
Log.i("DownloadService", path);
}
}
}


其余应用能够经过隐式意图访问服务,意图的动做能够自定义,AndroidManifest.xml配置代码以下:

<service android:name=".DownloadService" >
<intent-filter>
<action android:name="com.alex.process.aidl.DownloadService" />
</intent-filter>
</service>


4 把B应用中aidl文件所在package连同aidl文件一块儿拷贝到客户端A应用eclipse会自动在A应用的gen目录中为aidl文件同步生成IDownloadService.java接口文件,接下来就能够在A应用中实现与B应用通讯,代码以下:

public class ClientActivity extends Activity {
private IDownloadService downloadService;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.bindService(new Intent("com.alex.process.aidl.DownloadService"), 
                                    this.serviceConnection, BIND_AUTO_CREATE);//绑定到服务
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unbindService(serviceConnection);//解除服务
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
downloadService = IDownloadService.Stub.asInterface(service);
try {
downloadService.download("http://www.test.com/...");
} catch (RemoteException e) {
Log.e("ClientActivity", e.toString());
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
downloadService = null;
}
};
}
相关文章
相关标签/搜索