成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

HarmonyOS 分布式之聊天室應用

開發 分布式 OpenHarmony
此次給大家介紹一下基于鴻蒙分布式數據服務開發的聊天室應用,模擬現實中的聊天室對話,可以與小伙伴們互動、分享自己的故事給小伙伴。

[[434771]]

想了解更多內容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術社區

https://harmonyos.51cto.com

介紹

之前給大家介紹過【#星光計劃1.0# HarmonyOS 分布式之仿抖音應用】,此次給大家介紹一下基于鴻蒙分布式數據服務開發的聊天室應用,模擬現實中的聊天室對話,可以與小伙伴們互動、分享自己的故事給小伙伴。

效果演示

#星光計劃1.0# HarmonyOS 分布式之聊天室應用-鴻蒙HarmonyOS技術社區

項目類說明

#星光計劃1.0# HarmonyOS 分布式之聊天室應用-鴻蒙HarmonyOS技術社區

主要知識點

分布式數據服務

官方介紹:分布式數據服務主要實現用戶設備中應用程序的數據內容的分布式同步。當設備1上的應用A在分布式數據庫中增、刪、改數據后,設備2上的應用A也可以獲取到該數據庫變化,總結一句話:多個設備共用一個數據庫。

主頁代碼

沒有特別復雜的邏輯,主要是分布式數據服務的使用,關鍵地方都有注釋。

  1. import com.ldd.myapp.bean.ChatDataBean; 
  2. import com.ldd.myapp.provider.ChatProvider; 
  3. import com.ldd.myapp.util.Tools; 
  4. import ohos.aafwk.ability.AbilitySlice; 
  5. import ohos.aafwk.content.Intent; 
  6. import ohos.agp.components.Button; 
  7. import ohos.agp.components.ListContainer; 
  8. import ohos.agp.components.TextField; 
  9. import ohos.app.Context; 
  10. import ohos.bundle.IBundleManager; 
  11. import ohos.data.distributed.common.*; 
  12. import ohos.data.distributed.user.SingleKvStore; 
  13. import ohos.utils.zson.ZSONArray; 
  14. import ohos.utils.zson.ZSONObject; 
  15.  
  16. import java.util.ArrayList; 
  17. import java.util.List; 
  18.  
  19. import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; 
  20.  
  21. /** 
  22.  * 主頁 
  23.  */ 
  24. public class MainAbilitySlice extends AbilitySlice { 
  25.     private Context mContext; 
  26.     // 聊天列表 
  27.     private ListContainer lcList; 
  28.     // 聊天數據 
  29.     private final List<ChatDataBean> listData = new ArrayList<>(); 
  30.     // 聊天數據適配器 
  31.     private ChatProvider chatProvider; 
  32.     // 輸入框 
  33.     private TextField tfContent; 
  34.     // 發送按鈕 
  35.     private Button btnSend; 
  36.  
  37.     // 分布式數據庫管理器 
  38.     private KvManager kvManager; 
  39.     // 分布式數據庫 
  40.     private SingleKvStore singleKvStore; 
  41.     // 數據庫名稱 
  42.     private static final String STORE_NAME = "ChatStore"
  43.     // 存入的列表數據key 
  44.     private static final String KEY_DATA = "key_data"
  45.     // 存入的頭像索引 
  46.     private static final String KEY_PIC_INDEX = "key_pic_index"
  47.     private int picIndex = 0; 
  48.  
  49.     @Override 
  50.     public void onStart(Intent intent) { 
  51.         super.onStart(intent); 
  52.         super.setUIContent(ResourceTable.Layout_ability_main); 
  53.         mContext = this; 
  54.         requestPermission(); 
  55.         initComponent(); 
  56.         initDatabase(); 
  57.     } 
  58.  
  59.     /** 
  60.      * 請求分布式權限 
  61.      */ 
  62.     private void requestPermission() { 
  63.         if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { 
  64.             if (canRequestPermission(DISTRIBUTED_DATASYNC)) { 
  65.                 requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, 0); 
  66.             } 
  67.         } 
  68.     } 
  69.  
  70.     /** 
  71.      * 初始化組件 
  72.      */ 
  73.     private void initComponent() { 
  74.         lcList = (ListContainer) findComponentById(ResourceTable.Id_lc_list); 
  75.         tfContent = (TextField) findComponentById(ResourceTable.Id_tf_content); 
  76.         tfContent.setAdjustInputPanel(true); 
  77.         btnSend = (Button) findComponentById(ResourceTable.Id_btn_send); 
  78.         btnSend.setEnabled(false); 
  79.  
  80.         // 初始化適配器 
  81.         chatProvider = new ChatProvider(mContext, listData); 
  82.         lcList.setItemProvider(chatProvider); 
  83.  
  84.         // 輸入框內容變化監聽 
  85.         tfContent.addTextObserver((text, start, before, count) -> { 
  86.             btnSend.setEnabled(text.length() != 0); 
  87.         }); 
  88.         // 點擊發送按鈕 
  89.         btnSend.setClickedListener(component -> { 
  90.             String content = tfContent.getText().trim(); 
  91.             listData.add(new ChatDataBean(Tools.getDeviceId(mContext),picIndex,content)); 
  92.             // 存入數據庫中 
  93.             singleKvStore.putString(KEY_DATA, ZSONObject.toZSONString(listData)); 
  94.  
  95.             // 清空輸入框 
  96.             tfContent.setText(""); 
  97.         }); 
  98.     } 
  99.  
  100.     /** 
  101.      * 初始化分布式數據庫 
  102.      */ 
  103.     private void initDatabase() { 
  104.         // 創建分布式數據庫管理器 
  105.         kvManager = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)); 
  106.  
  107.         // 數據庫配置 
  108.         Options options = new Options(); 
  109.         options.setCreateIfMissing(true) // 設置數據庫不存在時是否創建 
  110.                 .setEncrypt(false) // 設置數據庫是否加密 
  111.                 .setKvStoreType(KvStoreType.SINGLE_VERSION); //數據庫類型 
  112.         // 創建分布式數據庫 
  113.         singleKvStore = kvManager.getKvStore(options, STORE_NAME); 
  114.         // 監聽數據庫數據改變 
  115.         singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, new KvStoreObserver() { 
  116.             @Override 
  117.             public void onChange(ChangeNotification changeNotification) { 
  118.                 List<Entry> insertEntries = changeNotification.getInsertEntries(); 
  119.                 List<Entry> updateEntries = changeNotification.getUpdateEntries(); 
  120.  
  121.                 // 第一次存入數據,獲取insertEntries 
  122.                 if(insertEntries.size()>0){ 
  123.                     for (Entry entry : insertEntries) { 
  124.                         if (KEY_DATA.equals(entry.getKey())) { 
  125.                             // 回調為非UI線程,需要在UI線程更新UI 
  126.                             getUITaskDispatcher().syncDispatch(() -> { 
  127.                                 listData.clear(); 
  128.                                 listData.addAll(ZSONArray.stringToClassList(entry.getValue().getString(),ChatDataBean.class)); 
  129.                                 chatProvider.notifyDataChanged(); 
  130.                                 lcList.scrollTo(listData.size() - 1); 
  131.                             }); 
  132.                         } 
  133.                     } 
  134.                 }else if(updateEntries.size()>0){ 
  135.                     for (Entry entry : updateEntries) { 
  136.                         if (KEY_DATA.equals(entry.getKey())) { 
  137.                             // 回調為非UI線程,需要在UI線程更新UI 
  138.                             getUITaskDispatcher().syncDispatch(() -> { 
  139.                                 listData.clear(); 
  140.                                 listData.addAll(ZSONArray.stringToClassList(entry.getValue().getString(),ChatDataBean.class)); 
  141.                                 chatProvider.notifyDataChanged(); 
  142.                                 lcList.scrollTo(listData.size() - 1); 
  143.                             }); 
  144.                         } 
  145.                     } 
  146.                 } 
  147.             } 
  148.         }); 
  149.  
  150.         try { 
  151.             picIndex = singleKvStore.getInt(KEY_PIC_INDEX); 
  152.             singleKvStore.putInt(KEY_PIC_INDEX, picIndex + 1); 
  153.         } catch (KvStoreException e) { 
  154.             e.printStackTrace(); 
  155.             // 沒有找到,首次進入 
  156.             if (e.getKvStoreErrorCode() == KvStoreErrorCode.KEY_NOT_FOUND) { 
  157.                 picIndex = 0; 
  158.                 singleKvStore.putInt(KEY_PIC_INDEX, picIndex + 1); 
  159.             } 
  160.         } 
  161.     } 
  162.  
  163.     @Override 
  164.     protected void onStop() { 
  165.         super.onStop(); 
  166.         kvManager.closeKvStore(singleKvStore); 
  167.     } 

簡單案例

1、config.json配置

  1. "reqPermissions": [ 
  2.       { 
  3.         "reason""多設備協同"
  4.         "name""ohos.permission.DISTRIBUTED_DATASYNC"
  5.         "usedScene": { 
  6.           "ability": [ 
  7.             "MainAbility" 
  8.           ], 
  9.           "when""always" 
  10.         } 
  11.       }, 
  12.       { 
  13.         "name""ohos.permission.DISTRIBUTED_DEVICE_STATE_CHANGE" 
  14.       }, 
  15.       { 
  16.         "name""ohos.permission.GET_DISTRIBUTED_DEVICE_INFO" 
  17.       }, 
  18.       { 
  19.         "name""ohos.permission.GET_BUNDLE_INFO" 
  20.       } 
  21.     ] 

2、布局頁面

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <DirectionalLayout 
  3.     xmlns:ohos="http://schemas.huawei.com/res/ohos" 
  4.     ohos:height="match_parent" 
  5.     ohos:width="match_parent" 
  6.     ohos:alignment="center" 
  7.     ohos:orientation="vertical"
  8.  
  9.     <Text 
  10.         ohos:id="$+id:text" 
  11.         ohos:height="match_content" 
  12.         ohos:width="match_content" 
  13.         ohos:text="數據:0" 
  14.         ohos:text_size="15fp"/> 
  15.  
  16.     <Button 
  17.         ohos:margin="20vp" 
  18.         ohos:id="$+id:button" 
  19.         ohos:height="match_content" 
  20.         ohos:width="match_parent" 
  21.         ohos:background_element="$graphic:button_bg" 
  22.         ohos:padding="10vp" 
  23.         ohos:text="點擊+1" 
  24.         ohos:text_color="white" 
  25.         ohos:text_size="15fp"/> 
  26.  
  27. </DirectionalLayout> 

3、MainAbilitySlice代碼

  1. import ohos.aafwk.ability.AbilitySlice; 
  2. import ohos.aafwk.content.Intent; 
  3. import ohos.agp.components.Button; 
  4. import ohos.agp.components.ListContainer; 
  5. import ohos.agp.components.Text; 
  6. import ohos.agp.components.TextField; 
  7. import ohos.bundle.IBundleManager; 
  8. import ohos.data.distributed.common.*; 
  9. import ohos.data.distributed.user.SingleKvStore; 
  10. import ohos.utils.zson.ZSONArray; 
  11.  
  12. import java.util.List; 
  13.  
  14. import static ohos.security.SystemPermission.DISTRIBUTED_DATASYNC; 
  15.  
  16. public class MainAbilitySlice extends AbilitySlice { 
  17.     // 顯示數據 
  18.     private Text text; 
  19.     // 分布式數據庫管理器 
  20.     private KvManager kvManager; 
  21.     // 分布式數據庫 
  22.     private SingleKvStore singleKvStore; 
  23.     // 數據庫名稱 
  24.     private static final String STORE_NAME = "MyStore"
  25.     // 存入的數據key 
  26.     private static final String KEY_COUNT = "key_count"
  27.  
  28.     @Override 
  29.     public void onStart(Intent intent) { 
  30.         super.onStart(intent); 
  31.         super.setUIContent(ResourceTable.Layout_ability_main); 
  32.         requestPermission(); 
  33.         initDatabase(); 
  34.         initComponent(); 
  35.     } 
  36.  
  37.     /** 
  38.      * 請求分布式權限 
  39.      */ 
  40.     private void requestPermission() { 
  41.         if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) { 
  42.             if (canRequestPermission(DISTRIBUTED_DATASYNC)) { 
  43.                 requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, 0); 
  44.             } 
  45.         } 
  46.     } 
  47.  
  48.     /** 
  49.      * 初始化分布式數據庫 
  50.      */ 
  51.     private void initDatabase() { 
  52.         // 創建分布式數據庫管理器 
  53.         kvManager = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)); 
  54.  
  55.         // 數據庫配置 
  56.         Options options = new Options(); 
  57.         options.setCreateIfMissing(true) // 設置數據庫不存在時是否創建 
  58.                 .setEncrypt(false) // 設置數據庫是否加密 
  59.                 .setKvStoreType(KvStoreType.SINGLE_VERSION); //數據庫類型 
  60.         // 創建分布式數據庫 
  61.         singleKvStore = kvManager.getKvStore(options, STORE_NAME); 
  62.         // 監聽數據庫數據改變 
  63.         singleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, new KvStoreObserver() { 
  64.             @Override 
  65.             public void onChange(ChangeNotification changeNotification) { 
  66.                 List<Entry> insertEntries = changeNotification.getInsertEntries(); 
  67.                 List<Entry> updateEntries = changeNotification.getUpdateEntries(); 
  68.  
  69.                 // 第一次存入數據,獲取insertEntries 
  70.                 if (insertEntries.size() > 0) { 
  71.                     for (Entry entry : insertEntries) { 
  72.                         if (KEY_COUNT.equals(entry.getKey())) { 
  73.                             // 回調為非UI線程,需要在UI線程更新UI 
  74.                             getUITaskDispatcher().syncDispatch(() -> { 
  75.                                 int count = entry.getValue().getInt(); 
  76.                                 text.setText("數據:"+count); 
  77.                             }); 
  78.                         } 
  79.                     } 
  80.                 } else if (updateEntries.size() > 0) { 
  81.                     for (Entry entry : updateEntries) { 
  82.                         if (KEY_COUNT.equals(entry.getKey())) { 
  83.                             // 回調為非UI線程,需要在UI線程更新UI 
  84.                             getUITaskDispatcher().syncDispatch(() -> { 
  85.                                 int count = entry.getValue().getInt(); 
  86.                                 text.setText("數據:"+count); 
  87.                             }); 
  88.                         } 
  89.                     } 
  90.                 } 
  91.             } 
  92.         }); 
  93.  
  94.     } 
  95.  
  96.     /** 
  97.      * 初始化組件 
  98.      */ 
  99.     private void initComponent() { 
  100.         text = (Text) findComponentById(ResourceTable.Id_text); 
  101.         Button button = (Button) findComponentById(ResourceTable.Id_button); 
  102.  
  103.         // 點擊事件 
  104.         button.setClickedListener(component -> { 
  105.             try { 
  106.                 int count = singleKvStore.getInt(KEY_COUNT); 
  107.                 singleKvStore.putInt(KEY_COUNT, count + 1); 
  108.             } catch (KvStoreException e) { 
  109.                 e.printStackTrace(); 
  110.                 // 沒有找到,首次進入 
  111.                 if (e.getKvStoreErrorCode() == KvStoreErrorCode.KEY_NOT_FOUND) { 
  112.                     int count = 0; 
  113.                     singleKvStore.putInt(KEY_COUNT, count + 1); 
  114.                 } 
  115.             } 
  116.         }); 
  117.     } 

注釋比較詳細,主要注意2個點:

  1. 獲取數據時加入try catch塊,處理key未找到的情況
  2. 數據庫數據改變監聽回調是非UI線程,如果更新UI必須切換到UI線程

以上簡單案例就是讓你快速掌握分布式數據服務:多個設備相同的應用之間使用同一個數據庫。

想了解更多內容,請訪問:

51CTO和華為官方合作共建的鴻蒙技術社區

https://harmonyos.51cto.com

 

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

2022-07-26 14:53:10

WebSocket網絡通信協議

2015-07-06 10:42:18

PHP聊天室應用

2011-12-15 11:11:51

JavaNIO

2023-02-10 08:16:48

WebSocket簡易聊天室

2021-10-21 10:03:09

鴻蒙HarmonyOS應用

2021-12-09 16:48:25

鴻蒙HarmonyOS應用

2021-12-13 11:07:10

鴻蒙HarmonyOS應用

2018-07-17 08:14:22

分布式分布式鎖方位

2021-01-21 09:45:36

鴻蒙HarmonyOS分布式

2021-05-28 09:52:00

鴻蒙HarmonyOS應用

2023-01-13 00:02:41

2023-01-05 09:17:58

2025-05-09 08:35:00

聊天室FastAPIWebSocket

2025-06-13 07:30:51

2022-03-06 21:43:05

Citus架構PostgreSQL

2019-02-13 13:41:07

MemCache分布式HashMap

2019-09-26 15:43:52

Hadoop集群防火墻

2020-11-06 12:12:35

HarmonyOS

2018-12-14 10:06:22

緩存分布式系統

2021-12-10 15:06:56

鴻蒙HarmonyOS應用
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 欧美一级淫片免费视频黄 | 欧美日韩一区二区在线观看 | 亚洲精品日本 | www.亚洲一区二区三区 | 成人久久久久 | 久久精品无码一区二区三区 | 91嫩草精品| 羞羞在线视频 | 九九九久久国产免费 | 日韩精品1区2区 | 91婷婷韩国欧美一区二区 | 欧美精品在线免费 | 奇米四色在线观看 | 成人免费小视频 | 一级国产精品一级国产精品片 | 亚洲二区在线观看 | 日韩视频一区在线观看 | 人人做人人澡人人爽欧美 | 国产精品网页 | 欧美激情 一区 | 伊人网影院 | 91精品久久久久久久久99蜜臂 | 日本小视频网站 | 久久91av| 一级片av | 亚洲二区在线 | 欧美激情在线精品一区二区三区 | 亚洲午夜精品在线观看 | 欧美久久久电影 | 久久噜噜噜精品国产亚洲综合 | 精品av | 天天操天天插 | 午夜影院在线观看 | 亚洲免费网| 波多野吉衣在线播放 | 亚洲成人av在线播放 | 久久激情视频 | 亚洲小视频 | 免费在线观看一区二区 | 久久久蜜桃一区二区人 | 亚洲美女在线一区 |