1. 项目介绍      远程教育,多屏协同是智慧教育的一个重要场景。本篇Codelab通过一个亲子早教系统,完成了分布式早教算数题和分布式拼图游戏两个综合案例,旨在帮助开发者快速了解HarmonyOS应用开发、多屏互动和分布式跨设备协同的体验。
本篇Codelab将为您重点介绍Page Ability、Service Ability、Intent以及分布式任务调度、公共事件等。同时我们还将为您介绍多屏互动,分布式跨设备协同、绘图画布的使用、经典拼图算法。正式介绍之前,我们先对亲子早教系统进行展示,让您快速了解到本篇Codelab所实现的功能。
功能1:早教算数题点击早教算数题,系统会为您随机出一道两位数的加法,点击实时辅导会拉起两个画布,本地端可以用黑色笔迹进行草稿运算,远程端可以用红色笔迹进行实时指导,操作步骤两端实时同步,效果图如下所示。

 
功能2:益智拼图游戏点击益智拼图游戏会拉起一个九宫格的拼图游戏(图片会随机乱序),点击图片可以进行拼图。在本地端点击亲子协同,远程端会拉起一个一模一样的游戏页面,两个设备可以进行实时互动,同步对图片进行拼接,操作步骤亦可实时同步,效果图如下所示。

 想知道上述两个亲子游戏是如何实现的吗?快来跟随我们的Codelab进行学习吧。
2. 搭建HarmonyOS环境      
我们首先需要完成HarmonyOS开发环境搭建,可参照如下步骤进行。
- 安装DevEco Studio,详情请参考下载和安装软件。
 - 设置DevEco Studio开发环境,DevEco Studio开发环境需要依赖于网络环境,需要连接上网络才能确保工具的正常使用,可以根据如下两种情况来配置开发环境:
- 如果可以直接访问Internet,只需进行下载HarmonyOS SDK操作。
 - 如果网络不能直接访问Internet,需要通过代理服务器才可以访问,请参考配置开发环境。
 
 - 开发者可以参考以下链接,完成设备调试的相关配置:
 
   
3. 代码结构解读      
本篇Codelab我们只是对核心代码进行讲解,您可以在最后的参考中下载完整代码,首先来介绍下整个工程的代码结构:

- devices:封装了选择设备的Dialog,您可直接调用SelectDeviceDialog里面的相关方法。
 - point:封装了绘图的相关功能,您可直接调用DrawPoint里面的相关方法。
 - slice:MainAbilitySlice为应用主页面,MathGameAbilitySlice为早教算数题主页面,MathDrawRemSlice为早教算数题绘图页面,PictureGameAbilitySlice为拼图游戏主页面。
 - utils:封装了公共方法和公共数据。
 - MathGameServiceAbility、PictureGameServiceAbility:供远端连接的Service Ability。
 - resources:存放工程使用到的资源文件,其中resourcesbaselayout下存放xml布局文件;resourcesbasemedia下存放图片资源。
 - config.json:配置文件。
 
   
4. 亲子早教系统页面流转      
亲子早教系统主页面和各个游戏页面的布局如下图所示,首先给大家介绍一下相关的布局代码。

首页的布局文件为ability_main.xml、页面控制逻辑MainAbilitySlice;早教系统的布局文件为math_game.xml、页面控制逻辑MathGameAbilitySlice;拼图游戏的布局文件为ability_picture.xml、页面控制逻辑PictureGameAbilitySlice。要实现页面的相互流转首先需要在MainAbility中设置路由,并在MainAbilitySlice中实现按钮的点击事件。
以跳转早教算数题为例,首先需要在MainAbility中设置路由,代码如下所示:
- addActionRoute(CommonData.MATH_PAGE,MathGameAbilitySlice.class.getName());
 
 复制代码 而后,需要在MainAbilitySlice中添加点击事件,代码如下所示:
- private void mathGame() { 
 -     LogUtil.info(TAG, "Click ResourceTable Id_math_game"); 
 -     Intent mathGameIntent = new Intent(); 
 -     Operation operationMath = new Intent.OperationBuilder() 
 -             .withBundleName(getBundleName()) 
 -             .withAbilityName(CommonData.ABILITY_MAIN) 
 -             .withAction(CommonData.MATH_PAGE) 
 -             .build(); 
 -     mathGameIntent.setOperation(operationMath); 
 -     startAbility(mathGameIntent); 
 - }
 
 复制代码
至此,您已实现跳转到早教算数题和益智拼图游戏两个页面了:
- 早教算数题的出题逻辑可以参考setQuestion和checkAnswer两个方法
 - 拼图游戏图片乱序、移动图片、判断游戏结束、重新开始可分别参考pictureRandom、moveFun、gameOverFun、restartFun相关方法
 
因篇幅有限且相关游戏算法不属于本篇Codelab想为您重点介绍的HarmonyOS特性,因此不再赘述,您可自行调用相关函数、理解相关代码实现游戏功能,附件代码中也已进行了详细的注释。以上即完成了单机版本的HarmonyOS应用开发,接下来我们将为您重点介绍基于HarmonyOS分布式能力的相关系统设计。    
5. 发现设备和建立连接      
在早教算数题中点击实时辅导或者在拼图游戏中点击亲子协同,会弹出选择设备页面,如下图所示。我们已经在devices目录下为您封装好了选择设备的dialog,具体代码请参考DevicesListAdapter(设备列表适配器)、item_device_list.xml (设备列表item布局)、SelectDeviceDialog(选择设备列表的弹窗)、dialog_select_device.xml(弹窗布局)。

SelectDeviceDialog中选择设备弹窗的构造函数如下,需要传入三个参数:上下文、设备列表、选择结果的回调事件。在业务代码中调用如下构造函数即可打开选择设备的弹窗,代码如下所示:
- public SelectDeviceDialog(Context context, List<DeviceInfo> devices, SelectResultListener listener) { 
 -     initView(context, devices, listener); 
 - }
 
 复制代码 其中List<DeviceInfo> devices可以通过如下函数去获取,代码如下所示:
- private void getDevices() { 
 -     if (devices.size() > 0) { 
 -         devices.clear(); 
 -     } 
 -     List<DeviceInfo> deviceInfos = 
 -         DeviceManager.getDeviceList(ohos.distributedschedule.interwork.DeviceInfo.FLAG_GET_ONLINE_DEVICE); 
 -     LogUtil.info(TAG, "deviceInfos size is :" + deviceInfos.size()); 
 -     devices.addAll(deviceInfos); 
 -     showDevicesDialog(); 
 - }
 
 复制代码 选择结果的回调事件可以根据业务的不同传入不同的回调事件,例如早教算数题中选择设备后,需要拉起本地端和远程端两个画布,此订阅事件为startLocalFa和startRemoteFa,代码如下所示:
- private void showDevicesDialog() { 
 -     new SelectDeviceDialog(this, devices, deviceInfo -> { 
 -         startLocalFa(deviceInfo.getDeviceId()); 
 -         startRemoteFa(deviceInfo.getDeviceId()); 
 -     }).show(); 
 - }
 
 复制代码 而拼图游戏需要和另外一台设备建立连接,拉起另外一台设备的拼图页面,此回调事件为connectRemotePa,代码如下所示:
- private void showDevicesDialog() { 
 -     new SelectDeviceDialog(this, devices, deviceInfo -> { 
 -         connectRemotePa(deviceInfo.getDeviceId(), PictureRemoteProxy.REQUEST_START_ABILITY); 
 -     }).show(); 
 - }
 
 复制代码 需要说明的是回调函数中deviceInfo是单击选中的设备信息,具体实现在SelectDeviceDialog的initView方法中,代码如下所示:
- DevicesListAdapter devicesListAdapter = new DevicesListAdapter(devices, context); 
 - devicesListContainer.setItemProvider(devicesListAdapter); 
 - devicesListContainer.setItemClickedListener((listContainer, component, position, l) -> { 
 -     listener.callBack(devices.get(position)); 
 -     commonDialog.hide(); 
 - });
 
 复制代码 至此,您已经完成了多设备协同中发现设备和建立连接这一关键步骤。
   
6. 早教算数题      点击早教算数题,系统会为您随机出一道两位数的加法,点击实时辅导会拉起两个画布,本地端可以用黑色笔迹进行草稿运算,远程端可以用红色笔迹进行实时指导,操作步骤两端实时同步,效果如下图所示。接下来我们将为您详细介绍如何利用HarmonyOS分布式威廉希尔官方网站
实现两端的同步绘制。

 步骤 1 -  选择设备
详见"5 发现设备和建立连接"。
步骤 2 -  建立连接
点击选择设备后会进入绘图页面,在onStart方法中会调用初始化并连接设备的函数initAndConnectDevice,通过intent传参获取远程设备的remoteDeviceId,并调用connectRemotePa进行连接,代码如下所示:
- private void initAndConnectDevice(Intent intent) { 
 -     // 页面初始化 
 -     this.context = MathDrawRemSlice.this; 
 -     String remoteDeviceId = intent.getStringParam(CommonData.KEY_REMOTE_DEVICEID); 
 -     isLocal = intent.getBooleanParam(CommonData.KEY_IS_LOCAL, false); 
 -     if (findComponentById(ResourceTable.Id_text_title) instanceof Text) { 
 -         Text textTitle = (Text) findComponentById(ResourceTable.Id_text_title); 
 -         textTitle.setText(isLocal ? "本地端" : "远程端"); 
 -     } 
 -  
 -     // 连接远程服务 
 -     if (!remoteDeviceId.isEmpty()) { 
 -         connectRemotePa(remoteDeviceId); 
 -     } else { 
 -         LogUtil.info(TAG, "localDeviceId is null"); 
 -     } 
 - }
 
 复制代码其中调用connectRemotePa方法后会和MathGameServiceAbility建立服务连接,代码如下所示:
- Intent connectPaIntent = new Intent(); 
 - Operation operation = new Intent.OperationBuilder() 
 -        .withDeviceId(deviceId) 
 -        .withBundleName(getBundleName()) 
 -        .withAbilityName(CommonData.MATH_GAME_SERVICE_NAME) 
 -        .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) 
 -        .build(); 
 - connectPaIntent.setOperation(operation);
 
 复制代码连接成功后会回调onAbilityConnectDone方法,此时两台设备即建立了连接。而后,可以调用senDataToRemote方法进行数据发送,代码如下所示:
- public void onAbilityConnectDone(ElementName elementName, IRemoteObject remote, int resultCode) { 
 -     LogUtil.info(TAG, "onAbilityConnectDone......"); 
 -     connectAbility(elementName, remote, requestType); 
 - } 
 -   
 - private void connectAbility(ElementName elementName, IRemoteObject remote, int requestType) { 
 -     proxy = new PictureRemoteProxy(remote); 
 -     LogUtil.error(TAG, "connectRemoteAbility done"); 
 -     if (proxy != null) { 
 -         try { 
 -             proxy.senDataToRemote(requestType); 
 -         } catch (RemoteException e) { 
 -             LogUtil.error(TAG, "onAbilityConnectDone RemoteException"); 
 -         } 
 -     } 
 - }
 
 复制代码步骤 3 -  绘图操作(具体业务,准备要发送的数据)
DrawPoint是一个绘图的工具类,绘制一个点会记录三个信息:X轴坐标、Y轴坐标、是否是最后一个点。将此信息记录到数组pointXs、pointYs、isLastPoints中,并封装在localPoints和remotePoints 中,定义如下:
- private float[] pointXs;
 - private boolean[] isLastPoints; 
 - private List<MyPoint> localPoints = new ArrayList<>(); 
 - private List<MyPoint> remotePoints = new ArrayList<>();
 
 复制代码其中,是否为最后一个点是通过TouchEvent.PRIMARY_POINT_UP事件进行区分的。当检测到该事件时,会调用回调函数callBack.callBack(localPoints) ,代码如下所示:
- if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP) { 
 -     point.setLastPoint(true); 
 -     localPoints.add(point); 
 -     callBack.callBack(localPoints); 
 - }
 
 复制代码此时会向上回调到setOnDrawBack方法,代码如下所示:
- public void setOnDrawBack(OnDrawCallBack drawCallBack) { 
 -     callBack = drawCallBack; 
 - }
 
 复制代码MathDrawRemSlice中initDraw()会初始化画布,一次绘制完成后会回调setOnDrawBack方法,其中points是上述步骤中绘制的点,将其存入数组pointXs、pointYs、isLastPoints中,代码如下所示:
- drawl.setOnDrawBack(points -> { 
 -     drawPoint(points); 
 - });
 
 复制代码此时就完成了本地画布绘制并将绘制的点信息存放到了数组pointsX、pointsY、isLastPoints中,即已经准备好了要发送的数据。
步骤 4 -  发送数据
发送数据涉及到Service Ability、分布式任务调度、公共事件三项HarmonyOS能力,如果您还不熟悉相关基础知识可以先参考官方文档进行学习。一次绘制完成后,会调用senDataToRemote方法,将绘制的点信息(pointXs、pointYs、isLastPoints)存放到data中并发送出去,代码如下所示:
- private void senDataToRemote(int requestType) throws RemoteException { 
 -     LogUtil.info(TAG, "send data to local draw service"); 
 -     MessageParcel data = MessageParcel.obtain(); 
 -     MessageParcel reply = MessageParcel.obtain(); 
 -     MessageOption option = new MessageOption(MessageOption.TF_SYNC); 
 -     try { 
 -         if (pointsX != null && pointsY != null && isLastPoint != null) { 
 -            data.writeFloatArray(pointXs); 
 -            data.writeFloatArray(pointYs); 
 -            data.writeBooleanArray(isLastPoint); 
 -         } 
 -         remote.sendRequest(requestType, data, reply, option); 
 -         int ec = reply.readInt(); 
 -         if (ec != ERR_OK) { 
 -             LogUtil.error(TAG, "RemoteException:"); 
 -         } 
 -     } catch (RemoteException e) { 
 -         LogUtil.error(TAG, "RemoteException:"); 
 -     } finally { 
 -         data.reclaim(); 
 -         reply.reclaim(); 
 -     } 
 - }
 
 复制代码其中,remote.sendRequest是将数据发送到MathGameServiceAbility的服务中(因为步骤2是和MathGameServiceAbility建立服务连接),建立服务连接后会回调onRemoteRequest方法,代码如下所示:
- [url=home.php?mod=space&uid=2735960]@Override[/url] 
 - public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) { 
 -     LogUtil.info(TAG, "onRemoteRequest......"); 
 -     float[] pointXs = data.readFloatArray(); 
 -     float[] pointYs = data.readFloatArray(); 
 -     boolean[] isLastPoints = data.readBooleanArray(); 
 -     reply.writeInt(ERR_OK); 
 -     sendEvent(isLastPoints, pointXs , pointYs ); 
 -     return true; 
 - }
 
 复制代码在onRemoteRequest方法中,会调用sendEvent将数组pointXs、pointYs、isLastPoints发送出去。sendEvent是通过公共事件的方式进行数据传递的,其注册的公共事件是CommonData.MATH_DRAW_EVENT,代码如下所示:
- private void sendEvent(boolean[] isLastPoint, float[] pointsX, float[] pointsY) { 
 -     LogUtil.info(TAG, "sendEvent......"); 
 -     try { 
 -         Intent intent = new Intent(); 
 -         Operation operation = new Intent.OperationBuilder() 
 -                 .withAction(CommonData.MATH_DRAW_EVENT) 
 -                 .build(); 
 -         intent.setOperation(operation); 
 -         intent.setParam(CommonData.KEY_POINT_X, pointXs); 
 -         intent.setParam(CommonData.KEY_POINT_Y, pointYs); 
 -         intent.setParam(CommonData.KEY_IS_LAST_POINT, isLastPoint); 
 -         CommonEventData eventData = new CommonEventData(intent); 
 -         CommonEventManager.publishCommonEvent(eventData); 
 -     } catch (RemoteException e) { 
 -         LogUtil.error(TAG, "publishCommonEvent occur exception."); 
 -     } 
 - }
 
 复制代码步骤 5 -  接收数据
MathDrawRemSlice中会订阅CommonData.MATH_DRAW_EVENT的公共事件,代码如下所示:
- private void subscribe() { 
 -     MatchingSkills matchingSkills = new MatchingSkills(); 
 -     matchingSkills.addEvent(CommonData.MATH_DRAW_EVENT); 
 -     matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); 
 -     CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
 -     subscriber = new MyCommonEventSubscriber(subscribeInfo); 
 -     try { 
 -         CommonEventManager.subscribeCommonEvent(subscriber); 
 -     } catch (RemoteException e) { 
 -         LogUtil.error("", "subscribeCommonEvent occur exception."); 
 -     } 
 - }
 
 复制代码当订阅到相关事件时会回调onReceiveEvent方法,此时即可将pointXs、pointYs、isLastPoints解析出来,然后调用drawl.setDrawParams(isLastPoints, pointXs, pointYs)方法在远程端进行绘制,代码如下所示:
- public void onReceiveEvent(CommonEventData commonEventData) { 
 -     Intent intent = commonEventData.getIntent(); 
 -     pointXs = intent.getFloatArrayParam(CommonData.KEY_POINT_X); 
 -     pointYs = intent.getFloatArrayParam(CommonData.KEY_POINT_Y); 
 -     isLastPoint = intent.getBooleanArrayParam(CommonData.KEY_IS_LAST_POINT); 
 -     // 接收数据后,对远程端画布进行绘制 
 -     drawl.setDrawParams(isLastPoint, pointXs, pointYs); 
 -     LogUtil.info(TAG, "onReceiveEvent....."); 
 - }
 
 复制代码步骤 6 -  数据的双向通信
步骤1-5中为您讲解了数据的单向通信,即本地端向远程端的交互。本例的绘图是双向通信,两端都可以进行绘制,这是怎么做到的呢?原来在步骤1中选择设备时,会调用startLocalFa和startRemoteFa,其中startLocalFa传出的remoteDeviceId是所选择的设备ID,startRemoteFa传出的remoteDeviceId是当前设备的ID,由此实现了双向通信,代码如下所示
- private void showDevicesDialog() { 
 -     new SelectDeviceDialog(this, devices, deviceInfo -> { 
 -         startLocalFa(deviceInfo.getDeviceId()); 
 -         startRemoteFa(deviceInfo.getDeviceId()); 
 -     }).show(); 
 - } 
 - private void startLocalFa(String deviceId) { 
 -     LogUtil.info(TAG, "startLocalFa......"); 
 -     Intent intent = new Intent(); 
 -     intent.setParam(CommonData.KEY_REMOTE_DEVICEID, deviceId); 
 -     ... 
 - } 
 - private void startRemoteFa(String deviceId) { 
 -     LogUtil.info(TAG, "startRemoteFa......"); 
 -     String localDeviceId = KvManagerFactory.getInstance() 
 -             .createKvManager(new KvManagerConfig(this)).getLocalDeviceInfo().getId(); 
 -     Intent intent = new Intent(); 
 -     intent.setParam(CommonData.KEY_REMOTE_DEVICEID, localDeviceId); 
 -     ... 
 - }
 
 复制代码通过选择设备、建立连接、发送数据、接收数据这几个关键步骤,您就可以实现两台设备的同步绘图、实时显示的功能。
7. 益智拼图游戏      点击益智拼图游戏会拉起一个九宫格的拼图游戏(图片会随机乱序),点击图片可以进行拼图。在本地端中点击亲子协同,远程端会拉起一个一模一样的游戏页面,两个设备可以进行实时互动,同步对图片进行拼接,操作步骤亦可实时同步,效果图如下所示。接下来我们将为您详细介绍如何利用HarmonyOS分布式威廉希尔官方网站
实现一个益智拼图游戏。

 步骤 1 -  选择设备
详见"5 发现设备和建立连接"这一章节。
步骤 2 -  建立连接并拉起设备
点击亲子协同后会记录选择设备的deviceId,调用connectRemotePa方法后会和PictureGameServiceAbility建立服务连接,其中标识位传递的是REQUEST_START_ABILITY,代码如下所示:
- private void showDevicesDialog() { 
 -     new SelectDeviceDialog(this, devices, deviceInfo -> { 
 -         connectRemotePa(deviceInfo.getDeviceId(), PictureRemoteProxy.REQUEST_START_ABILITY); 
 -     }).show(); 
 - } 
 - private void connectRemotePa(String deviceId, int requestType) { 
 -     if (!deviceId.isEmpty()) { 
 -         Intent connectPaIntent = new Intent(); 
 -         Operation operation = new Intent.OperationBuilder() 
 -                 .withDeviceId(deviceId) 
 -                 .withBundleName(getBundleName()) 
 -                 .withAbilityName(CommonData.PICTURE_GAME_SERVICE_NAME) 
 -                 .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) 
 -                 .build(); 
 -         connectPaIntent.setOperation(operation); 
 -     ... 
 - }
 
 复制代码连接成功后会回调onAbilityConnectDone方法,此时两台设备即建立了连接。然后调用sendDataToRemote方法进行数据发送,其中requestType为REQUEST_START_ABILITY,代码如下所示:
- public void onAbilityConnectDone(ElementName elementName, IRemoteObject remote, int resultCode) { 
 -     LogUtil.info(TAG, "onAbilityConnectDone......"); 
 -     connectAbility(elementName, remote, requestType); 
 - } 
 -   
 - private void connectAbility(ElementName elementName, IRemoteObject remote, int requestType) { 
 -     proxy = new PictureRemoteProxy(remote); 
 -     LogUtil.error(TAG, "connectRemoteAbility done"); 
 -     if (proxy != null) { 
 -         try { 
 -             proxy.sendDataToRemote(requestType); 
 -         } catch (RemoteException e) { 
 -             LogUtil.error(TAG, "onAbilityConnectDone RemoteException"); 
 -         } 
 -     } 
 - }
 
 复制代码PictureGameServiceAbility服务中接收到了senDataToRemote的消息后会回调onRemoteRequest,因为此时code为REQUEST_START_ABILITY,所以会拉起远程端的拼图页面,代码如下所示:
- public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) { 
 -     ... 
 -     if (code == REQUEST_START_ABILITY) { 
 -         LogUtil.error(TAG, "RemoteServiceAbility::isFirstStart:"); 
 -         Intent secondIntent = new Intent(); 
 -         Operation operation = new Intent.OperationBuilder().withDeviceId("") 
 -                 .withBundleName(getBundleName()) 
 -                 .withAbilityName(CommonData.ABILITY_MAIN) 
 -                 .withAction(CommonData.PICTURE_PAGE) 
 -                 .build(); 
 -     ... 
 -     } else { 
 -     ... 
 -     } 
 -     ... 
 - }
 
 复制代码以上即完成了本地端到远程端的单向通信。远程端设备拉起后,会在PictureGameAbilitySlice执行onStart方法,进而执行initRemoteView方法,其中会再次调用connectRemotePa方法,此时传递的标识位为REQUEST_SEND_DATA,不会重复拉起本地端设备的页面,只会建立数据连接,代码如下所示:
- private void initRemoteView(Intent intent) { 
 -     if (!isLocal) { 
 -         remoteDeviceId = intent.getStringParam(CommonData.KEY_REMOTE_DEVICEID); 
 -         connectRemotePa(remoteDeviceId, PictureRemoteProxy.REQUEST_SEND_DATA); 
 -         if (imageIndexs != null) { 
 -             updateDataInfo(intent); 
 -         } 
 -     } 
 - }
 
 复制代码如上步骤即完成了本地端和远程端的双向通信,实现了数据互传的功能。
步骤 3 -  拼图操作(具体业务,准备要发送的数据)
因篇幅有限且拼图游戏不属于本篇Codelab想为您重点介绍的HarmonyOS特性,因此不再赘述,请读者自行理解。我们告诉您的结论是,完成一次拼图操作需要记录三个关键数据:移动图片的下标moveImageId,移动图片的位置movePosition和最终排列的图片下标imageIndexs。点击一次拼图,我们就会记录以上三个数据,代码如下所示:
- private class ImageClick implements Component.ClickedListener { 
 -     @Override 
 -     public void onClick(Component component) { 
 -         int imageId = component.getId(); 
 -         for (int position = 0; position < imageIndexs.length; position++) { 
 -             if (imageId == imageResourceTable[position]) { 
 -                 // 完成图片移动,并记录移动信息 
 -                 moveFun(imageId, position); 
 -                 moveImageId = imageId; 
 -                 movePosition = position; 
 -             } 
 -         } 
 -         // 刷新页面显示 
 -         setImageAndDecodeBounds(imageIndexs); 
 -         // 发送数据 
 -         senDataToRemoteFun(); 
 -     } 
 - }
 
 复制代码 
步骤 4 -  发送数据
发送数据的流程和早教算数题一样,我们再次为您做详细介绍,您可参考早教算数题进行对照学习。一次拼图完成后,会调用senDataToRemote方法,将关键信息(imageIndexs、moveImageId、movePosition)存放到data中并发送出去,代码如下所示:
- private void senDataToRemote(int requestType) throws RemoteException { 
 -     MessageParcel data = MessageParcel.obtain(); 
 -      ... 
 -     try { 
 -      ... 
 -         data.writeIntArray(imageIndexs); 
 -         data.writeInt(moveImageId); 
 -         data.writeInt(movePosition); 
 -         remote.sendRequest(requestType, data, reply, option); 
 -      ... 
 -     } catch (RemoteException e) { 
 -      ... 
 -     } finally { 
 -      ... 
 -     } 
 - }
 
 复制代码 
其中,remote.sendRequest是将数据发送到PictureGameServiceAbility的服务中(因为步骤2是和PictureGameServiceAbility建立服务连接),建立服务连接后会回调onRemoteRequest方法。接收顺序应该和发送顺序一致(imageIndexs、moveImageId、movePosition),否则会操作接收错误的情况,代码如下所示:
- public boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) { 
 -     LogUtil.info(TAG, "onRemoteRequest......"); 
 -     int[] imageIndexs= data.readIntArray(); 
 -     int moveImageId = data.readInt(); 
 -     int movePosition = data.readInt(); 
 -      ... 
 -     LogUtil.info(TAG, "receive number:" + imageIndexs.length); 
 -     reply.writeInt(ERR_OK); 
 -     if (code == REQUEST_START_ABILITY) { 
 -      ... 
 -     } else { 
 -         sendEvent(imageIndexs, moveImageId, movePosition); 
 -     } 
 -     return true; 
 - }
 
 复制代码 
在onRemoteRequest方法中,会调用sendEvent将imageIndexs、moveImageId、movePosition发送出去。sendEvent是通过注册公共事件的方式进行数据传递的,其注册的公共事件是CommonData. PICTURE_GAME_EVENT,代码如下所示:
- private void sendEvent(int[] imageIndexs, int moveImageId, int movePosition) { 
 -     try { 
 -         Intent intent = new Intent(); 
 -         Operation operation = new Intent.OperationBuilder() 
 -                 .withAction(CommonData.PICTURE_GAME_EVENT) 
 -                 .build(); 
 -         intent.setOperation(operation); 
 -         intent.setParam(CommonData.KEY_IMAGE_INDEX, imageIndexs); 
 -         intent.setParam(CommonData.KEY_MOVE_IMAGE_ID, moveImageId); 
 -         intent.setParam(CommonData.KEY_MOVE_POSITION, movePosition); 
 -         CommonEventData eventData = new CommonEventData(intent); 
 -         CommonEventManager.publishCommonEvent(eventData); 
 -     } catch (RemoteException e) { 
 -         LogUtil.error(TAG, "publishCommonEvent occur exception."); 
 -     } 
 - }
 
 复制代码 
步骤 5 -  接收数据
接收数据的代码流程和早教算数题一样,我们再次为您做详细介绍,您可参考早教算数题进行对照学习。PictureGameAbilitySlice会订阅CommonData. PICTURE_GAME_EVENT的公共事件,代码如下所示:
- private void subscribe() { 
 -     MatchingSkills matchingSkills = new MatchingSkills(); 
 -     matchingSkills.addEvent(CommonData.PICTURE_GAME_EVENT); 
 -     matchingSkills.addEvent(CommonEventSupport.COMMON_EVENT_SCREEN_ON); 
 -     CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills); 
 -     subscriber = new MyCommonEventSubscriber(subscribeInfo); 
 -     try { 
 -         CommonEventManager.subscribeCommonEvent(subscriber); 
 -     } catch (RemoteException e) { 
 -         LogUtil.error("", "subscribeCommonEvent occur exception."); 
 -     } 
 - }
 
 复制代码 
当订阅到相关事件时会回调onReceiveEvent方法,此时即可将imageIndexs、moveImageId、movePosition解析出来,并调用updateDataInfo更新对端的布局文件,代码如下所示:
- @Override 
 - public void onReceiveEvent(CommonEventData commonEventData) { 
 -     ... 
 -     Intent intent = commonEventData.getIntent(); 
 -     updateDataInfo(intent); 
 - } 
 -   
 - private void updateDataInfo(Intent intent) { 
 -     imageIndexs= intent.getIntArrayParam(CommonData.KEY_IMAGE_INDEX); 
 -     moveImageId = intent.getIntParam(CommonData.KEY_MOVE_IMAGE_ID, -1); 
 -     movePosition = intent.getIntParam(CommonData.KEY_MOVE_POSITION, -1); 
 -     getUITaskDispatcher().delayDispatch(() -> setImageAndDecodeBounds(imageIndexs), DELAY_TIME); 
 - }
 
 复制代码 
通过选择设备、建立连接、发送数据、接收数据这几个关键步骤,您就可以实现两台设备的同步拼图的功能。以上两个案例,我们完整的学习了两台设备之间的数据交互,体验了HarmonyOS分布式特性,相信您一定有所收获。
说明
以上代码仅demo演示参考使用,产品化的代码需要考虑数据校验和国际化。
   
8. 回顾和总结      
本篇Codelab通过一个亲子早教系统,完整的为您介绍了早教算数题和益智拼图游戏两个综合案例,旨在帮助您快速了解HarmonyOS应用开发、多屏互动、分布式跨设备协同的功能了解。您需要重点掌握跨设备协同、分布式任务调度、公共事件三项HarmonyOS能力。特别的,我们通过拆解步骤的方式详细为您介绍了如何在两台设备之间进行数据传递,这是您需要重点学习和掌握的知识点。
另外,本篇Codelab的两个案例还可以通过分布式数据服务和分布式文件服务去优化代码,我们将在后续Codelab中为您介绍这方面的知识点和案例。
   
9. 恭喜你      
目前你已经成功完成了Codelab并且学到了:
- 常用布局、自定义控件的使用
 - Page Ability、Service Ability、Intent
 - 多屏互动、分布式跨设备协同、分布式任务调度
 - 公共事件
 
   
10. 完整示例