aidl意义:
AIDL(Android 接口定义语言) 是 Android 提供的一种进程间通信 (IPC) 机制。通过这种机制,我们只需要写好 aidl 接口文件,编译时系统会帮我们生成 Binder 接口,实现进程之间的通讯。
一、如何定义aidl文件
1、在main目录下创建文件夹aidl,然后在aidl下new aidl 创建.aidl文件-->IServerInterface.aidl
2、点击同步按钮。
重新编译后会找到IServerInterface.aidl
二、实现服务端
创建项目AidlServer
1、新建aidl文件
首先在main目录下创建aidl文件夹,然后new AIDL 生成 IServerInterface.aidl 文件
// IServerInterface.aidl
package com.example.lizhiqiang.aidlserver;
// Declare any non-default types here with import statements
interface IServerInterface {
int add(int a ,int b);
}
然后编译一下项目
2、创建服务IRemoteServer用于实现aidl
package com.example.lizhiqiang.aidlserver;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;
/**
* Created by lizhiqiang on 2018/10/17.
*/
public class IRemoteServer extends Service {
/*
* 当客户端绑定该服务的时候 onBind会被调用
*
* */
@Nullable
@Override
public IBinder onBind(Intent intent) {
Log.i("TAG", "链接到远程服务");
return iBinder;
}
private IBinder iBinder = new IServerInterface.Stub() {
@Override
public int add(int a, int b) throws RemoteException {
Log.i("TAG", "收到了远程的请求 参数一:" + a + "参数儿:" + b);
return a + b;
}
};
}
注意:要在manifest中注册此服务,同时设置exported=true 允许其他应用访问
<service android:name=".IRemoteServer"
android:exported="true"
/>
设置网络权限
<uses-permission android:name="android.permission.INTERNET"/>
3、共享方法add给客户端,如何共享这里就用到了iBinder,
iBinder是通过aidl文件IServerInterface.Stub方法生成的
当客户端链接到服务时,会调用onBind方法,这时我们将生成好的iBinder返给客户端,客户端及可调用add方法
三、实现客户端
将服务端的aidl文件复制到客户端,保证报名相同
在oncreate方法中
1、获取服务端服务
private IServerInterface sI;
private ServiceConnection conn = new ServiceConnection() {
//当绑定上服务的时候
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//拿到了远程的服务
sI = IServerInterface.Stub.asInterface(service);
}
//当服务断开的时候
@Override
public void onServiceDisconnected(ComponentName name) {
sI = null ;
}
};
private void bindServer(){
//获取到服务端
Intent intent =new Intent();
intent.setComponent(new ComponentName("com.example.lizhiqiang.aidlserver","com.example.lizhiqiang.aidlserver.IRemoteServer"));
bindService(intent,conn, Context.BIND_AUTO_CREATE);
}
private void unBind(){
unbindService(conn);
}
@Override
protected void onDestroy() {
super.onDestroy();
unBind();
}
2、通过链接服务 获取到 IBinder 然后通过ServerInterface.Stub.asInterface(service)获取到aidl
3、调用远程服务 调用方法,获取结果
int res = sI.add(Integer.valueOf(num1.getText().toString()),
Integer.valueOf(num2.getText().toString()));
result.setText("结果为:"+res);