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 来源: 鸿蒙社区
相关推荐

2021-10-21 10:03:09

鸿蒙HarmonyOS应用

2022-07-26 14:53:10

WebSocket网络通信协议

2021-12-13 11:07:10

鸿蒙HarmonyOS应用

2021-12-09 16:48:25

鸿蒙HarmonyOS应用

2015-07-06 10:42:18

PHP聊天室应用

2023-02-10 08:16:48

WebSocket简易聊天室

2011-12-15 11:11:51

JavaNIO

2021-07-22 10:20:21

鸿蒙HarmonyOS应用

2021-07-23 08:57:32

鸿蒙HarmonyOS应用

2021-12-10 15:06:56

鸿蒙HarmonyOS应用

2021-12-02 10:11:44

鸿蒙HarmonyOS应用

2021-08-24 15:13:06

鸿蒙HarmonyOS应用

2020-09-29 19:20:05

鸿蒙

2021-12-14 14:47:18

鸿蒙HarmonyOS应用

2021-01-21 09:45:36

鸿蒙HarmonyOS分布式

2021-05-28 09:52:00

鸿蒙HarmonyOS应用

2018-07-17 08:14:22

分布式分布式锁方位

2020-11-06 12:12:35

HarmonyOS

2023-01-05 09:17:58

2023-01-13 00:02:41

点赞
收藏

51CTO技术栈公众号