什么是AIDL
1.AIDL是一个缩写,全称是Android Interface Definition Language,也就是Android接口定义语言。
2.设计这门语言的目的是为了实现 进程间通信 。
3.默认支持的数据类型包括:
- Java中的八种基本数据类型,包括 byte,short,int,long,float,double,boolean,char。
- String 类型。
- CharSequence类型。
- List类型:List中的所有元素必须是AIDL支持的类型之一,或者是一个其他AIDL生成的接口,或者是定义的parcelable(下文关于这个会有详解)。List可以使用泛型。
- Map类型:Map中的所有元素必须是AIDL支持的类型之一,或者是一个其他AIDL生成的接口,或者是定义的parcelable。Map是不支持泛型的。
什么时候用AIDL
通信方式 | 条件 | 是否跨应用 | 是否多线程 |
---|---|---|---|
AIDL | IPC | 多个应用 | 多线程 |
binder | IPC | 单个应用 | 无多线程 |
Messager | IPC | 无多线程 |
创建AIDL
在Android studio中创建AIDL文件是需要Gradle一下的,在Eclipse中是不需要进行构建。
代码
AIDL接口
interface IMyAidlInterface {
int add(int num1,int num2);
}
server
public class RmoteService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return iBinder;
}
private IBinder iBinder = new IMyAidlInterface.Stub(){
@Override
public int add(int num1, int num2) throws RemoteException {
return num1+num2;
}
};
}
client
public class MainActivity extends AppCompatActivity {
private EditText editText1;
private EditText editText2;
private EditText editText3;
IMyAidlInterface i;
private Button button;
int num2;
int num1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText)findViewById(R.id.editText);
editText2 = (EditText)findViewById(R.id.editText2);
editText3 = (EditText)findViewById(R.id.editText3);
button = (Button)findViewById(R.id.button);
num1 = Integer.parseInt(editText1.toString());
num2 = Integer.parseInt(editText2.toString());
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
int re = i.add(num1,num2);
editText3.setText(re+"");
} catch (RemoteException e) {
e.printStackTrace();
}
}
private void bindServices() {
Intent intent = new Intent();
intent.setComponent(new ComponentName("wu.com.aidl_test","wu.com.aidl_test.RmoteService"));
bindService(intent,conn, Context.BIND_AUTO_CREATE);
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(conn);
}
ServiceConnection conn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//拿到了远程的服务
i = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
i= null;
}
};
}
实现的功能:
在客户端中输入两个数字,绑定服务器,在服务器端进行计算后返回给客户端并显示在界面上。
在Activity销毁时记得解绑Service。