在IPC Android中,AIDL和Messenger可以用于进程间通信。双向通信是指数据可以在服务端和客户端之间进行传递和响应。具体实现方式如下:
// 在AIDL文件中定义接口 interface IMyService { void registerCallback(IMyServiceCallback callback); void unregisterCallback(IMyServiceCallback callback); }
// 在服务端实现接口 public class MyService extends Service {
private IMyServiceCallback mCallback;
private final IMyService.Stub mBinder = new IMyService.Stub() {
@Override
public void registerCallback(IMyServiceCallback callback) throws RemoteException {
mCallback = callback;
}
@Override
public void unregisterCallback(IMyServiceCallback callback) throws RemoteException {
mCallback = null;
}
};
@Nullable
@Override
public IBinder onBind(Intent intent) {
// 返回mBinder接口实现类
return mBinder;
}
// ... 其他实现方法
}
// 客户端实现 IMyService mService; ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IMyService.Stub.asInterface(service);
try {
// 注册回调
mService.registerCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
};
// 回调接口 private final IMyServiceCallback mCallback = new IMyServiceCallback.Stub() {
@Override
public void onAction() throws RemoteException {
// 接收回调
}
};
// 服务端实现 public class MyService extends Service {
private Messenger mClientMessenger;
private final Messenger mMessenger = new Messenger(new Handler() {
上一篇:AIDL和Intent之间的区别