android AIDL
Android Interface Definition Language : Android接口定义语言
- 新建一个AIDL文件,在这个文件中定义好Activity需要与Service进行通信的方法
定义接口
MyAIDLService.aidl
无访问修饰符
package com.example.servicetest;
interface MyAIDLService {
int plus(int a, int b);
String toUpperCase(String str);
}
支持的数据类型
- 基本数据类型
- String和CharSequence
- List:只支持ArrayList,里面的元素都必须被AIDL支持
- Map:只支持HashMap,里面的元素必须被AIDL 支持
- 实现Parcelable接口的对象
- 所有AIDL接口
实现
return new MyAIDLService.Stub(){};
public class MyService extends Service {
......
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private Binder mBinder = new MyAIDLService.Stub() {
@Override
public String toUpperCase(String str) throws RemoteException {
if (str != null) {
return str.toUpperCase();
}
return null;
}
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
};
}
跨进程调用
myAIDLService = MyAIDLService.Stub.asInterface(service);
public class MainActivity extends Activity{
private MyAIDLService myAIDLService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myAIDLService = MyAIDLService.Stub.asInterface(service);
try {
int result = myAIDLService.plus(3, 5);
String upperStr = myAIDLService.toUpperCase("hello world");
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
......
}