纯代码实现
业务层
定义接口
public interface IMyService extends IInterface {
static final java.lang.String DESCRIPTOR = "com.demo.MyServer";
public void hellowWorld() throws RemoteException ;
static final int TRANSACTION_HELLOW_WORLD = 1;
}
客户端
public class MyServiceProxy implements IMyService {
private android.os.IBinder mRemote;
public MyServiceProxy(android.os.IBinder remote) {
mRemote = remote;
}
public java.lang.String getInterfaceDescriptor() {
return DESCRIPTOR;
}
@Override
public void hellowWorld() throws RemoteException {
android.os.Parcel _data = android.os.Parcel.obtain();
android.os.Parcel _reply = android.os.Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
mRemote.transact(TRANSACTION_HELLOW_WORLD, _data, _reply, 0);
_reply.readException();
} finally {
_reply.recycle();
_data.recycle();
}
}
@Override
public IBinder asBinder() {
return mRemote;
}
}
服务端
public abstract class MyServiceStub extends Binder implements IMyService{
public MyService() {
this.attachInterface(this, DESCRIPTOR);
}
@Override
public IBinder asBinder() {
return this;
}
public static com.demo.IMyService asInterface( android.os.IBinder obj) {
if ((obj == null)) {
return null;
}
android.os.IInterface iInterface = obj.queryLocalInterface(DESCRIPTOR);
if (((iInterface != null)&&(iInterface instanceof com.demo.IMyService))){
return ((com.demo.IMyService) iInterface);
}
return null;
}
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
switch (code) {
case INTERFACE_TRANSACTION: {
reply.writeString(DESCRIPTOR);
return true;
}
case TRANSACTION_HELLOW_WORLD: {
data.enforceInterface(DESCRIPTOR);
hellowWorld();
reply.writeNoException();
return true;
}
}
return super.onTransact(code, data, reply, flags);
}
}
实现层
public class MyService extends MyServiceStub{
@Override
public void hellowWorld() {
System.out.println("Hellow world!");
}
}
AIDL文件实现
需要2个AIDL文件和2个类。
1个AIDL文件定义业务接口:
interface IMyService {
MyData getMyData();
}
1个AIDL文件定义通信数据:
parcelable MyData;
1个类实现业务接口:
class RemoteService extend IRemoteService.Stub {
MyData mMyData;
RemoteService(MyData mMyData) {
this.mMyData = mMyData;
}
@Override
public MyData getMyData() throws RemoteException {
return mMyData;
}
};
1个类实现通信数据:
class MyData implements Parcelable{
......
}