用于进程间通讯
- 创建hellosumaidl.aidl文件,定义好返回数据的接口方法
package com.android.hellosumaidl;
// Interface declaration
interface IAdditionService {
// You can pass the value of in, out or inout
// The primitive types (int, boolean, etc) are only passed by in
int add(in int value1, in int value2);
}
编译器会自动生成对应的.java文件
- 在service中返回实现了该接口的binder
package com.android.hellosumaidl;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
/*
* This class exposes the service to client
*/
public class AdditionService extends Service {
@override
public void onCreate() {
super.onCreate();
}
@override
public IBinder onBind(Intent intent) {
return new IAdditionService.Stub() {
/*
* Implement com.android.hellosumaidl.IAdditionService.add(int, int)
*/
@override
public int add(int value1, int value2) throws RemoteException {
return value1 + value2;
}
};
}
@override
public void onDestroy() {
super.onDestroy();
}
}
- 在manefest里注册service,注意action写上aidl文件的路径
<service
android:name="com.android.hellosumaidl.AdditionService"
android:enabled="true"
android:label="@string/app_name"
android:exported="false" >
<intent-filter>
<intent-filter>
<action android:name="com.android.hellosumaidl.IAdditionService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</intent-filter>
</service>
- 其他客户端aidl连接service->在bindService的时候Intent加入服务service注册的Action
/**
* 尝试与服务端建立连接
*/
private void attemptToBindService() {
Intent intent = new Intent();
intent.setAction("com.android.hellosumaidl.IAdditionService");
intent.setPackage("com.android.hellosumaidl");
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
- 接下来就和service通讯一致
注意的内容
AIDL支持的数据种类:
- 八种基础数据类型
- List、Map、String、Charsquence
- 实现parcelable的类
- 其他AIDL接口类型
实现parcelable的类如何声明、关于权限tag(in、out、inout) 查看
Messenger是对AIDL的封装
Messenger是线程安全的(不支持并发),AIDL是非线程安全的(支持并发)
延展:Messenger
网友评论