自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

HarmonyOS Sample 之 Pasteboard 分布式粘貼板

開發(fā) 分布式 OpenHarmony
HarmonyOS提供系統(tǒng)剪貼板服務的操作接口,支持用戶程序從系統(tǒng)剪貼板中讀取、寫入和查詢剪貼板數(shù)據(jù),以及添加、移除系統(tǒng)剪貼板數(shù)據(jù)變化的回調(diào)。

[[435097]]

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)

https://harmonyos.51cto.com

一、介紹

HarmonyOS提供系統(tǒng)剪貼板服務的操作接口,支持用戶程序從系統(tǒng)剪貼板中讀取、寫入和查詢剪貼板數(shù)據(jù),以及添加、移除系統(tǒng)剪貼板數(shù)據(jù)變化的回調(diào)。

設備內(nèi):

用戶通過系統(tǒng)剪貼板服務,可實現(xiàn)應用之間的簡單數(shù)據(jù)傳遞。例如:在應用A中復制的數(shù)據(jù),可以在應用B中粘貼,反之亦可。

設備間:

在分布式粘貼板場景中,粘貼的數(shù)據(jù)可以跨設備寫入。例如,設備A上的應用程序使用系統(tǒng)粘貼板接口將從設備A復制的數(shù)據(jù)通過IDL接口存儲到設備B的系統(tǒng)粘貼板中。如果數(shù)據(jù)允許,設備B上的應用程序可以讀取并粘貼系統(tǒng)粘貼板中的復制數(shù)據(jù)。實現(xiàn)設備之間粘貼板的分布式協(xié)同。

基于以上理解,實現(xiàn)一個分布式粘貼板應用程序,應用程序分為客戶端(copy)和服務端(paste)兩部分,通過idl實現(xiàn)數(shù)據(jù)傳遞。

客戶端負責數(shù)據(jù)采集,服務端負責數(shù)據(jù)的展示和應用,客戶端和服務端可以安裝在同一臺設備中,也可以安裝在不同的設備中,服務端也可以按照在多臺設備中,服務端通過分布式數(shù)據(jù)庫實現(xiàn)粘貼板數(shù)據(jù)的自動同步。

二、效果展示

HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)
HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)

三、搭建環(huán)境

安裝DevEco Studio,詳情請參考DevEco Studio下載。

設置DevEco Studio開發(fā)環(huán)境,DevEco Studio開發(fā)環(huán)境需要依賴于網(wǎng)絡環(huán)境,需要連接上網(wǎng)絡才能確保工具的正常使用,可以根據(jù)如下兩種情況來配置開發(fā)環(huán)境:

如果可以直接訪問Internet,只需進行下載HarmonyOS SDK操作。

如果網(wǎng)絡不能直接訪問Internet,需要通過代理服務器才可以訪問,請參考配置開發(fā)環(huán)境。

下載源碼后,使用DevEco Studio 打開項目,模擬器運行即可。

真機運行需要將config.json中的buddleName修改為自己的,如果沒有請到AGC上進行配置,參見 使用模擬器進行調(diào)試

四、項目結(jié)構(gòu)

HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)
HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)

五、代碼講解

5.1 系統(tǒng)粘貼板基礎功能介紹

系統(tǒng)粘貼板對象介紹

1.SystemPasteboard //系統(tǒng)粘貼板對象,定義系統(tǒng)粘貼板操作,包括復制、粘貼和設置粘貼板內(nèi)容更改的偵聽器。

2.PasteData//表示粘貼板上的粘貼數(shù)據(jù)。

3.PasteData.DataProperty //該類定義了系統(tǒng)粘貼板上 PasteData 的屬性,包括時間戳、MIME 類型和其他屬性數(shù)據(jù)。

4.PasteData.Record//該類將單個粘貼的數(shù)據(jù)定義為 Record,它可以是純文本、HTML 文本、URI 和意圖。 PasteData 對象包含一個或多個記錄。

客戶端(copy)CopyAbilitySlice.java

獲取系統(tǒng)粘貼板,監(jiān)聽粘貼板數(shù)據(jù)變化

  1. /** 
  2.  * 獲取系統(tǒng)粘貼板 
  3.  * 監(jiān)聽粘貼板數(shù)據(jù)變化 
  4.  */ 
  5. private void initPasteboard() { 
  6.     HiLog.debug(LABEL, "initPasteboard"); 
  7.     //獲取系統(tǒng)粘貼板對象 
  8.     pasteboard = SystemPasteboard.getSystemPasteboard(this); 
  9.     //監(jiān)聽粘貼板數(shù)據(jù)變化 
  10.     pasteboard.addPasteDataChangedListener(() -> { 
  11.         if (pasteboard.hasPasteData()) { 
  12.             sync_text = getPasteData(); 
  13.             HiLog.debug(LABEL, "%{public}s""pasteStr:" + sync_text); 
  14.         } 
  15.     }); 

獲取粘貼板內(nèi)容

  1. /** 
  2.  * 獲取粘貼板記錄 
  3.  * 
  4.  * @return 
  5.  */ 
  6. private String getPasteData() { 
  7.     HiLog.debug(LABEL, "getPasteData"); 
  8.     String result = ""
  9.  
  10.     //粘貼板數(shù)據(jù)對象 
  11.     PasteData pasteData = pasteboard.getPasteData(); 
  12.     if (pasteData == null) { 
  13.         return result; 
  14.     } 
  15.     PasteData.DataProperty dataProperty = pasteData.getProperty(); 
  16.     // 
  17.     boolean hasHtml = dataProperty.hasMimeType(PasteData.MIMETYPE_TEXT_HTML); 
  18.     boolean hasText = dataProperty.hasMimeType(PasteData.MIMETYPE_TEXT_PLAIN); 
  19.  
  20.     //數(shù)據(jù)格式類型 
  21.     if (hasHtml || hasText) { 
  22.         for (int i = 0; i < pasteData.getRecordCount(); i++) { 
  23.             //粘貼板數(shù)據(jù)記錄 
  24.             PasteData.Record record = pasteData.getRecordAt(i); 
  25.             //不同類型獲取方式不同 
  26.             String mimeType = record.getMimeType(); 
  27.             //HTML文本 
  28.             if (mimeType.equals(PasteData.MIMETYPE_TEXT_HTML)) { 
  29.                 result = record.getHtmlText(); 
  30.                 //純文本 
  31.             } else if (mimeType.equals(PasteData.MIMETYPE_TEXT_PLAIN)) { 
  32.                 result = record.getPlainText().toString(); 
  33.                 // 
  34.             } else { 
  35.                 HiLog.info(LABEL, "%{public}s""getPasteData mimeType :" + mimeType); 
  36.             } 
  37.         } 
  38.     } 
  39.     return result; 

設置文本到粘貼板中

  1. /** 
  2.  * 設置文本到粘貼板 
  3.  * 
  4.  * @param component 
  5.  */ 
  6. private void setTextToPaste(Component component) { 
  7.     HiLog.info(LABEL, "setTextToPaste"); 
  8.     if (pasteboard != null) { 
  9.         String text = syncText.getText(); 
  10.         if (text.isEmpty()) { 
  11.             showTips(this, "請?zhí)顚憙?nèi)容"); 
  12.             return
  13.         } 
  14.         //把記錄添加到粘貼板 
  15.         PasteData pasteData=  PasteData.creatPlainTextData(text); 
  16.         //設置文本到粘貼板 
  17.         pasteboard.setPasteData(pasteData); 
  18.  
  19.         showTips(this, "復制成功"); 
  20.         HiLog.info(LABEL, "setTextToPaste succeeded"); 
  21.     } 

清空粘貼板

  1. /** 
  2.  * 清空粘貼板 
  3.  * 
  4.  * @param component 
  5.  */ 
  6. private void clearPasteboard(Component component) { 
  7.     if (pasteboard != null) { 
  8.         pasteboard.clear(); 
  9.         showTips(this, "Clear succeeded"); 
  10.     } 

5.2 分布式粘貼板應用構(gòu)建思路介紹

HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)

選擇遠端連接設備

本實例是通過新增加一個DevicesSelectAbility來實現(xiàn)的。

  1. private void showDevicesDialog() { 
  2.     Intent intent = new Intent(); 
  3.     //打開選擇設備的Ability頁面DevicesSelectAbility 
  4.     Operation operation = 
  5.             new Intent.OperationBuilder() 
  6.                     .withDeviceId(""
  7.                     .withBundleName(getBundleName()) 
  8.                     .withAbilityName(DevicesSelectAbility.class) 
  9.                     .build(); 
  10.     intent.setOperation(operation); 
  11.     //攜帶一個設備選擇請求標識,打開設備選擇頁面(DevicesSelectAbility) TODO 
  12.     startAbilityForResult(intent, Constants.PRESENT_SELECT_DEVICES_REQUEST_CODE); 
  13.  
  14. /** 
  15.  * 打開設備選擇Ability后,選擇連接的設備執(zhí)行setResult后觸發(fā) 
  16.  * 
  17.  * @param requestCode 
  18.  * @param resultCode 
  19.  * @param resultIntent 
  20.  */ 
  21. @Override 
  22. protected void onAbilityResult(int requestCode, int resultCode, Intent resultIntent) { 
  23.     HiLog.debug(LABEL, "onAbilityResult"); 
  24.     if (requestCode == Constants.PRESENT_SELECT_DEVICES_REQUEST_CODE && resultIntent != null) { 
  25.         //獲取用戶選擇的設備 
  26.         String devicesId = resultIntent.getStringParam(Constants.PARAM_DEVICE_ID); 
  27.         //連接粘貼板服務端 
  28.         connectService(devicesId); 
  29.         return
  30.     } 

連接粘貼板服務端ServiceAbility服務

idl文件放在ohos.samples.pasteboard.paste目錄下,Gradl窗口,執(zhí)行compileDebugIdl 后,系統(tǒng)生成代理對象。

  1. interface ohos.samples.pasteboard.paste.ISharePasteAgent { 
  2.     /* 
  3.      * 設置系統(tǒng)粘貼板 
  4.      */ 
  5.     void setSystemPaste([in] String param); 

連接服務端ServiceAbility,如果組網(wǎng)中沒有其他設備就連接本地的服務端。

連接成功后,初始化idl的SharePasteAgentProxy代理,用于下一步的同步數(shù)據(jù)。

  1. //idl共享粘貼板代理 
  2. private SharePasteAgentProxy remoteAgentProxy; 
  3.  
  4. /** 
  5.  * 連接粘貼板服務中心 
  6.  */ 
  7. private void connectService(String deviceId) { 
  8.     HiLog.debug(LABEL, "%{public}s""connectService"); 
  9.     if (!isConnect) { 
  10.         boolean isConnectRemote = deviceId != null
  11.         //三元表達式,判斷連接本地還是遠端Service 
  12.         Intent intent = isConnectRemote 
  13.                 ? getRemoteServiceIntent(REMOTE_BUNDLE, REMOTE_SERVICE, deviceId) 
  14.                 : getLocalServiceIntent(REMOTE_BUNDLE, REMOTE_SERVICE); 
  15.  
  16.         HiLog.debug(LABEL, "%{public}s""intent:" + intent); 
  17.         //連接 Service 
  18.         connectAbility(intent, new IAbilityConnection() { 
  19.             @Override 
  20.             public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) { 
  21.                 //發(fā)個通知,Service 連接成功了 
  22.                 eventHandler.sendEvent(EVENT_ABILITY_CONNECT_DONE); 
  23.                 //初始化代理 
  24.                 remoteAgentProxy = new SharePasteAgentProxy(iRemoteObject); 
  25.                 HiLog.debug(LABEL, "%{public}s""remoteAgentProxy:" + remoteAgentProxy); 
  26.             } 
  27.  
  28.             @Override 
  29.             public void onAbilityDisconnectDone(ElementName elementName, int resultCode) { 
  30.                 //發(fā)個通知,Service 斷開連接了,主動斷開不會執(zhí)行,關閉服務端會執(zhí)行 
  31.                 eventHandler.sendEvent(EVENT_ABILITY_DISCONNECT_DONE); 
  32.             } 
  33.         }); 
  34.     } 
  35. /** 
  36.  * 獲取遠端粘貼板服務中心 
  37.  * 
  38.  * @param bundleName 
  39.  * @param serviceName 
  40.  * @return 
  41.  */ 
  42. private Intent getRemoteServiceIntent(String bundleName, String serviceName, String deviceId) { 
  43.     HiLog.debug(LABEL, "%{public}s""getRemoteServiceIntent"); 
  44.     Operation operation = new Intent.OperationBuilder() 
  45.             .withDeviceId(deviceId) 
  46.             .withBundleName(bundleName) 
  47.             .withAbilityName(serviceName) 
  48.             //重要 
  49.             .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE) 
  50.             .build(); 
  51.     Intent intent = new Intent(); 
  52.     intent.setOperation(operation); 
  53.     return intent; 
  54.  
  55. /** 
  56.  * 獲取本地粘貼板服務中心 
  57.  * 
  58.  * @param bundleName 
  59.  * @param serviceName 
  60.  * @return 
  61.  */ 
  62. private Intent getLocalServiceIntent(String bundleName, String serviceName) { 
  63.     HiLog.debug(LABEL, "%{public}s""getLocalServiceIntent"); 
  64.     Operation operation = new Intent.OperationBuilder().withDeviceId(""
  65.             .withBundleName(bundleName) 
  66.             .withAbilityName(serviceName) 
  67.             .build(); 
  68.     Intent intent = new Intent(); 
  69.     intent.setOperation(operation); 
  70.     return intent; 

同步數(shù)據(jù)到服務端

  1. /** 
  2.  * 同步粘貼板記錄到粘貼板服務中心 
  3.  * 
  4.  * @param component 
  5.  */ 
  6. private void syncData(Component component) { 
  7.     HiLog.debug(LABEL, "sync_text:" + sync_text); 
  8.     if (!sync_text.isEmpty()) { 
  9.         if (isConnect && remoteAgentProxy != null) { 
  10.             //調(diào)用服務端IPC方法 
  11.             try { 
  12.                 remoteAgentProxy.setSystemPaste(sync_text); 
  13.                 //更換文本 
  14.                 syncText.setText(getRandomText()); 
  15.                 sync_text = ""
  16.                 showTips(this, "同步成功"); 
  17.             } catch (RemoteException remoteException) { 
  18.                 remoteException.printStackTrace(); 
  19.             } 
  20.         } else { 
  21.             showTips(this, "正在連接設備"); 
  22.         } 
  23.     } else { 
  24.         showTips(this, "點擊復制到粘貼板"); 
  25.     } 

隨機生成粘貼文本

  1. /** 
  2.  * 隨機文本,模擬數(shù)據(jù) 
  3.  * 
  4.  * @return 
  5.  */ 
  6. public String getRandomText() { 
  7.     List<String> list = Arrays.asList( 
  8.             "快馬加鞭未下鞍,離天三尺三"
  9.             "我自橫刀向天笑,去留肝膽兩昆侖"
  10.             "飛流直下三千尺,疑是銀河落九天"
  11.             "君子求諸己,小人求諸人"
  12.             "吾日三省吾身:為人謀而不忠乎?與朋友交而不信乎?傳不習乎?"); 
  13.     int random = new SecureRandom().nextInt(list.size()); 
  14.     return list.get(random); 

服務端(paste)ServiceAbility.java

設置粘貼板服務

idl文件放在ohos.samples.pasteboard.paste目錄下,Gradl窗口,執(zhí)行compileDebugIdl 后,系統(tǒng)生成代理對象,idl提供了setSystemPaste接口供遠端調(diào)用。

  1. interface ohos.samples.pasteboard.paste.ISharePasteAgent { 
  2.     /* 
  3.      * 設置系統(tǒng)粘貼板 
  4.      */ 
  5.     void setSystemPaste([in] String param); 
  1. //idl的服務端實現(xiàn), 
  2. SharePasteAgentStub sharePasteAgentStub = new SharePasteAgentStub(DESCRIPTOR) { 
  3.     @Override 
  4.     public void setSystemPaste(String param) { 
  5.         HiLog.info(LABEL, "%{public}s""param:" + param); 
  6.  
  7.         //插入數(shù)據(jù)庫 
  8.         ItemChild itemChild = new ItemChild(); 
  9.         String currentTime = DateUtils.getCurrentDate("yyMMdd HH:mm:ss"); 
  10.         itemChild.setWriteTime(currentTime); 
  11.         itemChild.setWriteContent(param); 
  12.         itemChild.setIndex(String.valueOf(UUID.randomUUID())); 
  13.         //默認添加到未分類 
  14.         itemChild.setTagName(Const.CATEGORY_TAG_UNCATEGOORIZED); 
  15.         //添加粘貼板記錄到分布式數(shù)據(jù)庫 
  16.         kvManagerUtils.addItemChild(itemChild); 
  17.  
  18.     } 
  19. }; 
  20.  
  21. @Override 
  22. protected IRemoteObject onConnect(Intent intent) { 
  23.     HiLog.info(LABEL, "%{public}s""ServiceAbility onConnect"); 
  24.     return sharePasteAgentStub; 
  25.  
  26. **初始化數(shù)據(jù)庫** 
  27. ```java 
  28. //初始化數(shù)據(jù)庫工具 
  29. kvManagerUtils = KvManagerUtils.getInstance(this); 
  30.  
  31. //初始化數(shù)據(jù)庫管理對象 
  32. kvManagerUtils.initDbManager(eventHandler); 
  33.  
  34. //初始化數(shù)據(jù)庫數(shù)據(jù)按鈕 
  35. Image initDb = (Image) findComponentById(ResourceTable.Id_init_db); 
  36. initDb.setClickedListener(component -> { 
  37.     //默認選中“未定義”標簽 
  38.     current_select_category_index = 0; 
  39.     //初始化數(shù)據(jù)庫數(shù)據(jù) 
  40.     kvManagerUtils.initDbData(); 
  41.     showTip("初始化完成"); 
  42. }); 

初始化數(shù)據(jù)列表

  1. /** 
  2.  * 從分布式數(shù)據(jù)庫中查詢數(shù)據(jù) 
  3.  */ 
  4. public void queryData() { 
  5.     HiLog.debug(LABEL, "queryData"); 
  6.     try { 
  7.         //加載選中類別下的數(shù)據(jù)列表 
  8.         initItemChild(kvManagerUtils.queryDataByTag(CategoryData.tagList.get(current_select_category_index))); 
  9.     } catch (KvStoreException exception) { 
  10.         HiLog.info(LABEL, "the value must be String"); 
  11.     } 
  12.  
  13. /** 
  14.  * 初始化選中標簽的子項列表 
  15.  * 
  16.  * @param itemChildList itemChildList, the bean of itemChild 
  17.  */ 
  18. private void initItemChild(List<ItemChild> itemChildList) { 
  19.     HiLog.debug(LABEL, "initItemChild:" + itemChildList); 
  20.     if (itemChildList == null) { 
  21.         return
  22.     } 
  23.     //清空組件 
  24.     itemChildLayout.removeAllComponents(); 
  25.     // Create itemChild 
  26.     for (ItemChild itemChild : itemChildList) { 
  27.         //獲取子項類別所在的組件 
  28.         Component childComponent = 
  29.                 LayoutScatter.getInstance(this).parse(ResourceTable.Layout_paste_record_per, nullfalse); 
  30.         //寫入時間 
  31.         Text writeTime = (Text) childComponent.findComponentById(ResourceTable.Id_writeTime); 
  32.         writeTime.setText(itemChild.getWriteTime()); 
  33.         //粘貼板內(nèi)容 
  34.         Text writeContent = (Text) childComponent.findComponentById(ResourceTable.Id_writeContent); 
  35.         writeContent.setText(itemChild.getWriteContent()); 
  36.  
  37.         //復制按鈕 
  38.         Text copy = (Text) childComponent.findComponentById(ResourceTable.Id_itemChildPerCopy); 
  39.         //復制按鈕的監(jiān)聽事件 
  40.         copy.setClickedListener(component -> { 
  41.             //復制內(nèi)容到粘貼板 
  42.             pasteboard.setPasteData(PasteData.creatPlainTextData(itemChild.getWriteContent())); 
  43.             showTip("已復制到粘貼板"); 
  44.         }); 
  45.  
  46.         //收藏按鈕 
  47.         Text favorite = (Text) childComponent.findComponentById(ResourceTable.Id_itemChildPerFavorite); 
  48.         //收藏按鈕的監(jiān)聽事件 
  49.         favorite.setClickedListener(component -> { 
  50.             //修改標簽微已收藏 
  51.             itemChild.setTagName(Const.CATEGORY_TAG_FAVORITED); 
  52.             //保存數(shù)據(jù) 
  53.             kvManagerUtils.addItemChild(itemChild); 
  54.             showTip("已加入到收藏中"); 
  55.         }); 
  56.  
  57.  
  58.         /**************just for test********************/ 
  59.         //復選框 
  60.         Checkbox noteId = (Checkbox) childComponent.findComponentById(ResourceTable.Id_noteId); 
  61.         //子項列表的點擊事件 
  62.         childComponent.setClickedListener(component -> { 
  63.             if (noteId.getVisibility() == Component.VISIBLE) { 
  64.                 noteId.setChecked(!noteId.isChecked()); 
  65.             } 
  66.         }); 
  67.         //子項列表的長按事件,長按顯示復選框 
  68.         childComponent.setLongClickedListener(component -> { 
  69.             //checkbox顯示 
  70.             noteId.setVisibility(Component.VISIBLE); 
  71.             //設置復選框樣式,以及其他文本組件的縮進 
  72.             Element element = ElementScatter.getInstance(getContext()).parse(ResourceTable.Graphic_check_box_checked); 
  73.             noteId.setBackground(element); 
  74.             noteId.setChecked(true); 
  75.             writeTime.setMarginLeft(80); 
  76.             writeContent.setMarginLeft(80); 
  77.         }); 
  78.         //復選框的狀態(tài)變化監(jiān)聽事件,state表示是否被選中 
  79.         noteId.setCheckedStateChangedListener((component, state) -> { 
  80.             // 狀態(tài)改變的邏輯 
  81.             Element element; 
  82.             if (state) { 
  83.                 //設置選中的樣式 
  84.                 element = ElementScatter.getInstance(getContext()) 
  85.                         .parse(ResourceTable.Graphic_check_box_checked); 
  86.             } else { 
  87.                 //設置未選中的樣式 
  88.                 element = ElementScatter.getInstance(getContext()) 
  89.                         .parse(ResourceTable.Graphic_check_box_uncheck); 
  90.             } 
  91.             noteId.setBackground(element); 
  92.         }); 
  93.         /**************just for test********************/ 
  94.  
  95.         //添加子項列表組件到布局 
  96.         itemChildLayout.addComponent(childComponent); 
  97.     } 

標簽分類顯示

  1. //初始化列表列表的點擊的監(jiān)聽事件 
  2. categoryList.setItemClickedListener( 
  3.         (listContainer, component, index, l1) -> { 
  4.             //點的就是當前類別 
  5.             if (categoryListProvider.getSelectIndex() == index) { 
  6.                 return
  7.             } 
  8.             //切換類別索引 
  9.             categoryListProvider.setSelectIndex(index); 
  10.             //設置選中的標簽索引 
  11.             current_select_category_index = index
  12.             //獲取當前選中的標簽名稱 
  13.             String tagName = CategoryData.tagList.get(index); 
  14.             //從數(shù)據(jù)庫中查詢標簽子項列表 
  15.             initItemChild(kvManagerUtils.queryDataByTagAndKewWord(searchTextField.getText(), tagName)); 
  16.             //通知數(shù)據(jù)更新 
  17.             categoryListProvider.notifyDataChanged(); 
  18.             //滾動條到最頂部 
  19.             itemListScroll.fluentScrollYTo(0); 
  20.         }); 

搜索粘貼記錄

  1. //搜索key監(jiān)聽事件 
  2. searchTextField.setKeyEventListener( 
  3.         (component, keyEvent) -> { 
  4.             if (keyEvent.isKeyDown() && keyEvent.getKeyCode() == KeyEvent.KEY_ENTER) { 
  5.                 //獲取當前選中的標簽名稱 
  6.                 String tagName = CategoryData.tagList.get(current_select_category_index); 
  7.                 List<ItemChild> itemChildList = kvManagerUtils.queryDataByTagAndKewWord(searchTextField.getText(), tagName); 
  8.                 //從數(shù)據(jù)庫中查詢標簽子項列表 
  9.                 initItemChild(itemChildList); 
  10.                 //通知數(shù)據(jù)更新 
  11.                 categoryListProvider.notifyDataChanged(); 
  12.                 //滾動條到最頂部 
  13.                 itemListScroll.fluentScrollYTo(0); 
  14.             } 
  15.             return false
  16.         }); 

分布式數(shù)據(jù)庫工具KvManagerUtils.java

數(shù)據(jù)變化通知

提供了分布式數(shù)據(jù)庫管理工具KvManagerUtils.java,數(shù)據(jù)庫操作都集中在這里了。

為了在數(shù)據(jù)庫數(shù)據(jù)發(fā)生變化時能及時更新頁面顯示,頁面在初始化數(shù)據(jù)庫時,傳遞eventHandler對象,這樣在數(shù)據(jù)庫變化是可以通知到頁面。

  1. /** 
  2.  * 訂閱數(shù)據(jù)庫更改通知 
  3.  * @param singleKvStore Data operation 
  4.  */ 
  5. private void subscribeDb(SingleKvStore singleKvStore) { 
  6.     HiLog.info(LABEL, "subscribeDb"); 
  7.     //數(shù)據(jù)庫觀察者客戶端 
  8.     KvStoreObserver kvStoreObserverClient = new KvStoreObserverClient(); 
  9.     //訂閱遠程數(shù)據(jù)更改 
  10.     singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_REMOTE, kvStoreObserverClient); 
  11.  
  12. /** 
  13.  * 自定義分布式數(shù)據(jù)庫觀察者客戶端 
  14.  * 數(shù)據(jù)發(fā)生變化時觸發(fā)對應函數(shù) 
  15.  * Receive database messages 
  16.  */ 
  17. private class KvStoreObserverClient implements KvStoreObserver { 
  18.     @Override 
  19.     public void onChange(ChangeNotification notification) { 
  20.         HiLog.error(LABEL, "onChange"); 
  21.         eventHandler.sendEvent(Const.DB_CHANGE_MESS); 
  22.     } 

數(shù)據(jù)自動同步

默認開啟自動同步

  1. /** 
  2.  * Initializing Database Management 
  3.  * 初始化數(shù)據(jù)庫管理員 
  4.  */ 
  5. public void initDbManager(EventHandler eventHandler) { 
  6.     this.eventHandler = eventHandler; 
  7.     HiLog.info(LABEL, "initDbManager"); 
  8.     if (singleKvStore == null || kvManager == null) { 
  9.         HiLog.info(LABEL, "initDbData"); 
  10.         //創(chuàng)建數(shù)據(jù)庫管理員 
  11.         kvManager = createManager(); 
  12.         //創(chuàng)建數(shù)據(jù)庫 
  13.         singleKvStore = createDb(kvManager); 
  14.         subscribeDb(singleKvStore); 
  15.  
  16.     } 
  17.  
  18.  
  19.  
  20. /** 
  21.  * Create a distributed database manager instance 
  22.  * 創(chuàng)建數(shù)據(jù)庫管理員 
  23.  * 
  24.  * @return database manager 
  25.  */ 
  26. private KvManager createManager() { 
  27.     HiLog.info(LABEL, "createManager"); 
  28.     KvManager manager = null
  29.     try { 
  30.         // 
  31.         KvManagerConfig config = new KvManagerConfig(context); 
  32.         manager = KvManagerFactory.getInstance().createKvManager(config); 
  33.     } catch (KvStoreException exception) { 
  34.         HiLog.error(LABEL, "some exception happen"); 
  35.     } 
  36.     return manager; 
  37.  
  38. /** 
  39.  * Creating a Single-Version Distributed Database 
  40.  * 創(chuàng)建數(shù)據(jù)庫 
  41.  * 
  42.  * @param kvManager Database management 
  43.  * @return SingleKvStore 
  44.  */ 
  45. private SingleKvStore createDb(KvManager kvManager) { 
  46.     HiLog.info(LABEL, "createDb"); 
  47.     SingleKvStore kvStore = null
  48.     try { 
  49.         Options options = new Options(); 
  50.         //單版本數(shù)據(jù)庫,不加密,沒有可用的 KvStore 數(shù)據(jù)庫就創(chuàng)建 
  51.         //單版本分布式數(shù)據(jù)庫,默認開啟組網(wǎng)設備間自動同步功能, 
  52.         //如果應用對性能比較敏感建議設置關閉自動同步功能setAutoSync(false),主動調(diào)用sync接口同步。 
  53.         options.setCreateIfMissing(true
  54.                 .setEncrypt(false
  55.                 .setKvStoreType(KvStoreType.SINGLE_VERSION); 
  56.         //創(chuàng)建數(shù)據(jù)庫 
  57.         kvStore = kvManager.getKvStore(options, STORE_ID); 
  58.  
  59.     } catch (KvStoreException exception) { 
  60.         HiLog.error(LABEL, "some exception happen"); 
  61.     } 
  62.     return kvStore; 

權(quán)限config.json

  1. "reqPermissions": [ 
  2.     { 
  3.       "name""ohos.permission.DISTRIBUTED_DATASYNC"
  4.       "reason""同步粘貼板數(shù)據(jù)"
  5.       "usedScene": { 
  6.         "when""inuse"
  7.         "ability": [ 
  8.           "ohos.samples.pasteboard.paste.MainAbility"
  9.           "ohos.samples.pasteboard.paste.ServiceAbility" 
  10.         ] 
  11.       } 
  12.     }, 
  13.     { 
  14.       "name""ohos.permission.GET_DISTRIBUTED_DEVICE_INFO" 
  15.     }, 
  16.     { 
  17.       "name""ohos.permission.KEEP_BACKGROUND_RUNNING" 
  18.     } 
  19.   ] 

六、思考總結(jié)

1.粘貼板板傳遞數(shù)據(jù)可能會存在安全問題,需要注意,要根據(jù)具體場景來使用。

設備內(nèi)每次傳輸?shù)恼迟N數(shù)據(jù)大小不能超過 800 KB。每次設備間傳輸?shù)臄?shù)據(jù)不能超過64KB,且數(shù)據(jù)必須為文本格式。

2.idl的使用,在上述案例中,客戶端(copy) 和 服務端(paste) 項目idl下內(nèi)容完全一致即可。

HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)
HarmonyOS Sample 之 Pasteboard 分布式粘貼板-鴻蒙HarmonyOS技術(shù)社區(qū)

七、完整代碼

附件可以直接下載

https://harmonyos.51cto.com/resource/1489

想了解更多內(nèi)容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術(shù)社區(qū)

https://harmonyos.51cto.com

 

責任編輯:jianghua 來源: 鴻蒙社區(qū)
相關推薦

2021-12-10 15:06:56

鴻蒙HarmonyOS應用

2021-08-24 15:13:06

鴻蒙HarmonyOS應用

2018-02-08 16:45:22

前端JS粘貼板

2023-02-06 07:17:22

2018-07-17 08:14:22

分布式分布式鎖方位

2022-03-06 21:43:05

Citus架構(gòu)PostgreSQL

2019-02-13 13:41:07

MemCache分布式HashMap

2019-09-26 15:43:52

Hadoop集群防火墻

2021-10-21 10:03:09

鴻蒙HarmonyOS應用

2021-11-16 09:38:10

鴻蒙HarmonyOS應用

2019-10-10 09:16:34

Zookeeper架構(gòu)分布式

2021-12-28 17:03:29

數(shù)據(jù)質(zhì)量分布式

2019-07-04 15:13:16

分布式緩存Redis

2019-12-26 08:59:20

Redis主從架構(gòu)

2023-05-29 14:07:00

Zuul網(wǎng)關系統(tǒng)

2017-09-01 05:35:58

分布式計算存儲

2019-06-19 15:40:06

分布式鎖RedisJava

2019-09-05 13:06:08

雪花算法分布式ID

2021-12-14 08:19:59

系統(tǒng)分布式網(wǎng)絡

2020-11-06 12:12:35

HarmonyOS
點贊
收藏

51CTO技術(shù)棧公眾號