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

HarmonyOS 分布式之聊天室應(yīng)用

開發(fā) 分布式 OpenHarmony
此次給大家介紹一下基于鴻蒙分布式數(shù)據(jù)服務(wù)開發(fā)的聊天室應(yīng)用,模擬現(xiàn)實(shí)中的聊天室對話,可以與小伙伴們互動、分享自己的故事給小伙伴。

[[434771]]

想了解更多內(nèi)容,請?jiān)L問:

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

https://harmonyos.51cto.com

介紹

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

效果演示

#星光計(jì)劃1.0# HarmonyOS 分布式之聊天室應(yīng)用-鴻蒙HarmonyOS技術(shù)社區(qū)

項(xiàng)目類說明

#星光計(jì)劃1.0# HarmonyOS 分布式之聊天室應(yīng)用-鴻蒙HarmonyOS技術(shù)社區(qū)

主要知識點(diǎn)

分布式數(shù)據(jù)服務(wù)

官方介紹:分布式數(shù)據(jù)服務(wù)主要實(shí)現(xiàn)用戶設(shè)備中應(yīng)用程序的數(shù)據(jù)內(nèi)容的分布式同步。當(dāng)設(shè)備1上的應(yīng)用A在分布式數(shù)據(jù)庫中增、刪、改數(shù)據(jù)后,設(shè)備2上的應(yīng)用A也可以獲取到該數(shù)據(jù)庫變化,總結(jié)一句話:多個(gè)設(shè)備共用一個(gè)數(shù)據(jù)庫。

主頁代碼

沒有特別復(fù)雜的邏輯,主要是分布式數(shù)據(jù)服務(wù)的使用,關(guān)鍵地方都有注釋。

  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.     // 聊天數(shù)據(jù) 
  29.     private final List<ChatDataBean> listData = new ArrayList<>(); 
  30.     // 聊天數(shù)據(jù)適配器 
  31.     private ChatProvider chatProvider; 
  32.     // 輸入框 
  33.     private TextField tfContent; 
  34.     // 發(fā)送按鈕 
  35.     private Button btnSend; 
  36.  
  37.     // 分布式數(shù)據(jù)庫管理器 
  38.     private KvManager kvManager; 
  39.     // 分布式數(shù)據(jù)庫 
  40.     private SingleKvStore singleKvStore; 
  41.     // 數(shù)據(jù)庫名稱 
  42.     private static final String STORE_NAME = "ChatStore"
  43.     // 存入的列表數(shù)據(jù)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.      * 請求分布式權(quán)限 
  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.         // 輸入框內(nèi)容變化監(jiān)聽 
  85.         tfContent.addTextObserver((text, start, before, count) -> { 
  86.             btnSend.setEnabled(text.length() != 0); 
  87.         }); 
  88.         // 點(diǎn)擊發(fā)送按鈕 
  89.         btnSend.setClickedListener(component -> { 
  90.             String content = tfContent.getText().trim(); 
  91.             listData.add(new ChatDataBean(Tools.getDeviceId(mContext),picIndex,content)); 
  92.             // 存入數(shù)據(jù)庫中 
  93.             singleKvStore.putString(KEY_DATA, ZSONObject.toZSONString(listData)); 
  94.  
  95.             // 清空輸入框 
  96.             tfContent.setText(""); 
  97.         }); 
  98.     } 
  99.  
  100.     /** 
  101.      * 初始化分布式數(shù)據(jù)庫 
  102.      */ 
  103.     private void initDatabase() { 
  104.         // 創(chuàng)建分布式數(shù)據(jù)庫管理器 
  105.         kvManager = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)); 
  106.  
  107.         // 數(shù)據(jù)庫配置 
  108.         Options options = new Options(); 
  109.         options.setCreateIfMissing(true) // 設(shè)置數(shù)據(jù)庫不存在時(shí)是否創(chuàng)建 
  110.                 .setEncrypt(false) // 設(shè)置數(shù)據(jù)庫是否加密 
  111.                 .setKvStoreType(KvStoreType.SINGLE_VERSION); //數(shù)據(jù)庫類型 
  112.         // 創(chuàng)建分布式數(shù)據(jù)庫 
  113.         singleKvStore = kvManager.getKvStore(options, STORE_NAME); 
  114.         // 監(jiān)聽數(shù)據(jù)庫數(shù)據(jù)改變 
  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.                 // 第一次存入數(shù)據(jù),獲取insertEntries 
  122.                 if(insertEntries.size()>0){ 
  123.                     for (Entry entry : insertEntries) { 
  124.                         if (KEY_DATA.equals(entry.getKey())) { 
  125.                             // 回調(diào)為非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.                             // 回調(diào)為非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.             // 沒有找到,首次進(jìn)入 
  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""多設(shè)備協(xié)同"
  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="數(shù)據(jù):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="點(diǎn)擊+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.     // 顯示數(shù)據(jù) 
  18.     private Text text; 
  19.     // 分布式數(shù)據(jù)庫管理器 
  20.     private KvManager kvManager; 
  21.     // 分布式數(shù)據(jù)庫 
  22.     private SingleKvStore singleKvStore; 
  23.     // 數(shù)據(jù)庫名稱 
  24.     private static final String STORE_NAME = "MyStore"
  25.     // 存入的數(shù)據(jù)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.      * 請求分布式權(quán)限 
  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.      * 初始化分布式數(shù)據(jù)庫 
  50.      */ 
  51.     private void initDatabase() { 
  52.         // 創(chuàng)建分布式數(shù)據(jù)庫管理器 
  53.         kvManager = KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(this)); 
  54.  
  55.         // 數(shù)據(jù)庫配置 
  56.         Options options = new Options(); 
  57.         options.setCreateIfMissing(true) // 設(shè)置數(shù)據(jù)庫不存在時(shí)是否創(chuàng)建 
  58.                 .setEncrypt(false) // 設(shè)置數(shù)據(jù)庫是否加密 
  59.                 .setKvStoreType(KvStoreType.SINGLE_VERSION); //數(shù)據(jù)庫類型 
  60.         // 創(chuàng)建分布式數(shù)據(jù)庫 
  61.         singleKvStore = kvManager.getKvStore(options, STORE_NAME); 
  62.         // 監(jiān)聽數(shù)據(jù)庫數(shù)據(jù)改變 
  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.                 // 第一次存入數(shù)據(jù),獲取insertEntries 
  70.                 if (insertEntries.size() > 0) { 
  71.                     for (Entry entry : insertEntries) { 
  72.                         if (KEY_COUNT.equals(entry.getKey())) { 
  73.                             // 回調(diào)為非UI線程,需要在UI線程更新UI 
  74.                             getUITaskDispatcher().syncDispatch(() -> { 
  75.                                 int count = entry.getValue().getInt(); 
  76.                                 text.setText("數(shù)據(jù):"+count); 
  77.                             }); 
  78.                         } 
  79.                     } 
  80.                 } else if (updateEntries.size() > 0) { 
  81.                     for (Entry entry : updateEntries) { 
  82.                         if (KEY_COUNT.equals(entry.getKey())) { 
  83.                             // 回調(diào)為非UI線程,需要在UI線程更新UI 
  84.                             getUITaskDispatcher().syncDispatch(() -> { 
  85.                                 int count = entry.getValue().getInt(); 
  86.                                 text.setText("數(shù)據(jù):"+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.         // 點(diǎn)擊事件 
  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.                 // 沒有找到,首次進(jìn)入 
  111.                 if (e.getKvStoreErrorCode() == KvStoreErrorCode.KEY_NOT_FOUND) { 
  112.                     int count = 0; 
  113.                     singleKvStore.putInt(KEY_COUNT, count + 1); 
  114.                 } 
  115.             } 
  116.         }); 
  117.     } 

注釋比較詳細(xì),主要注意2個(gè)點(diǎn):

  1. 獲取數(shù)據(jù)時(shí)加入try catch塊,處理key未找到的情況
  2. 數(shù)據(jù)庫數(shù)據(jù)改變監(jiān)聽回調(diào)是非UI線程,如果更新UI必須切換到UI線程

以上簡單案例就是讓你快速掌握分布式數(shù)據(jù)服務(wù):多個(gè)設(shè)備相同的應(yīng)用之間使用同一個(gè)數(shù)據(jù)庫。

想了解更多內(nèi)容,請?jiān)L問:

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

https://harmonyos.51cto.com

 

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

2022-07-26 14:53:10

WebSocket網(wǎng)絡(luò)通信協(xié)議

2015-07-06 10:42:18

PHP聊天室應(yīng)用

2011-12-15 11:11:51

JavaNIO

2023-02-10 08:16:48

WebSocket簡易聊天室

2021-10-21 10:03:09

鴻蒙HarmonyOS應(yīng)用

2021-12-09 16:48:25

鴻蒙HarmonyOS應(yīng)用

2018-07-17 08:14:22

分布式分布式鎖方位

2021-12-13 11:07:10

鴻蒙HarmonyOS應(yīng)用

2023-01-13 00:02:41

2023-01-05 09:17:58

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集群防火墻

2022-11-14 08:01:48

2021-05-28 09:52:00

鴻蒙HarmonyOS應(yīng)用

2018-12-14 10:06:22

緩存分布式系統(tǒng)

2021-01-21 09:45:36

鴻蒙HarmonyOS分布式

2022-12-01 08:25:23

eTsTCP聊天室

2011-06-09 15:44:29

Spring

2021-12-10 15:06:56

鴻蒙HarmonyOS應(yīng)用
點(diǎn)贊
收藏

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