上一篇已经介绍完服务端的创建,在此基础上创建客户端来实现进程间通信。
客户端
可以看到客户端的包(com.hm.aidl)下的文件和服务端的一样,文件和包名一定要相同。
布局文件很简单:四个button,负责bind服务,注册回调,获取数据
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_bind_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Bind Service" />
<Button
android:id="@+id/btn_register_callback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Register Callback" />
<Button
android:id="@+id/btn_get_current_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Get Current Data" />
<Button
android:id="@+id/btn_get_datas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickButton"
android:text="Get Datas" />
</LinearLayout>
客户端绑定服务使用ServiceConnection
ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName componentName) {
Log.d(TAG, "onServiceDisconnected");
mService = null;
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder binder) {
Log.d(TAG, "onServiceConnected");
mService = IService.Stub.asInterface(binder);
}
};
上一篇文章提到服务端回调客户端需要一个IBinder,这里是ICallback
ICallback mCallback = new ICallback.Stub() {
@Override
public void notify(String action, Bundle bundle) throws RemoteException {
Log.d(TAG, "notify : " + action);
}
};
bindService使用ServiceConnection
private void bindService() {
Intent intent = new Intent();
intent.setAction("android.intent.action.HM_SERVICE");
bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
Log.d(TAG, "bindService");
}
注册回调,获取数据
private void registerCallback() {
if (mService != null) {
try {
mService.registerCallback(mCallback);
Log.d(TAG, "registerCallback");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private void getCurrentData() {
if (mService != null) {
try {
EntityData data = mService.getCurrentData();
if (data != null) {
Log.d(TAG, "getCurrentData : id = " + data.id + " name = " + data.name);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
private void getDatas() {
if (mService != null) {
try {
List<EntityData> datas = mService.getDatas();
if (datas != null) {
Log.d(TAG, "getDatas : size = " + datas.size());
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
先运行服务端,再来启动客户端,下面来看通信的log信息:
先绑定服务
以上就可以实现客户端和服务端之间的双向通信了。
本文介绍了如何在Android中创建客户端以实现与服务端的进程间通信,通过AIDL进行双向通信。客户端的包结构和服务端一致,包含相同的文件。客户端布局包括四个按钮,分别用于绑定服务、注册回调和获取数据。使用ServiceConnection进行bindService操作。在确保服务端运行后,客户端可以成功实现通信,并展示了相关的log信息。
1031

被折叠的 条评论
为什么被折叠?



