Android Interface Define Language
让其他应用可以调用当前应用service中的方法。
RPC remote procedure call 远程过程调用 AIDL解决RPC的问题
IPC inter process communication 进程间通信
每一个Android运行在独立的进程中 应用之间通信就是进程间通信。
Activity 通过隐式意图intent
BroadcastReceiver 通过onReceive 方法,可以处理其他应用发来的广播。
通过 Intent 携带数据
AIDL实现的过程
①创建一个Service 重写onBind 方法, 在onBinder中返回一个Binder对象 需要远程调用的 需要远程调用的发放到这个Binder对象中。
public class RemoteService extends Service {
@Override
public IBinder onBind(Intent intent) {
return new MyBinder();
}
public class MyBinder extends Binder{
public void callremoteMethod() {
remoteMethod();
}
}
public void remoteMethod() {
System.out.println("remoteMethod is called");
}
}
②在清单文件中
清单文件中声明service , 需要添加一个intent-filter , 可以通过隐式意图调用service。
<service android:name="com.haowan.RemoteService">
<intent-filter>
<action android:name="com.haowan.remoteservice"></action>
</intent-filter>
</service>
③创建一个接口,需要暴露给其他应用的方法都声明在这个接口中。(名字是随意取的)
interface IService {
void remoteMethod();
}
④把接口扩展名修改为 aidl 注意aidl不支持public关键字,若是aidl创建没有问题,则会在gen目录下生成一个 IService.java
⑤修改service代码,让其继承Stub
public class MyBinder extends Stub{
@Override
public void remoteMethod() throws RemoteException {
System.out.println("remoteMethod is called");
}
}
远程调用:
①通过隐式意图以及bindService方式开启远程服务把 Service 打开。
private ServiceConnection conn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//用隐式意图开启其他应用的service
Intent service=new Intent("com.haowan.remoteservice");
conn = new MyConnection();
bindService(service, conn, BIND_AUTO_CREATE);
}
②创建ServiceConnection 实现类
private class MyConnection implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
③在当前应用中创建一个目录,目录结构跟提供远程服务的应用aidl所在目录保持一致,把aidl文件copy过来,如果没有问题,会在gen目录下生成一个iservice.java文件 包名跟aidl文件的包名保持一致。
④在onServiceConnected方法通过
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iservice = Stub.asInterface(service);
}
把当前的Ibuilder对象转化成远程服务中的接口类型,最终通过这个对象实现远程调用方法。
public void callRemote(View v)
{
try {
iservice.remoteMethod();
} catch (RemoteException e) {
e.printStackTrace();
}
}