OpenHarmony standard equipment application development (3) – distributed data management

(The following content is shared by developers and does not represent the views of the OpenHarmony Project Group Working Committee)

Xing Lu
 

In the previous chapter, we used distributed music players, distributed bombs, and distributed shopping carts to explain how related controls are used in the layout of OpenAtom OpenHarmony (hereinafter referred to as “OpenHarmony”), and how to implement them in OpenHarmony. Music playback, display animation, transition animation (transition between pages) and other functions.

This chapter is the third article on OpenHarmony standard device application development. Based on the previous two chapters, we will explain to you distributed data management among multiple devices. When the data changes, multiple devices can be implemented through subscription. The data is updated synchronously. For a better understanding, we used eTS to develop a tic-tac-toe three-level game as shown in the following animation to explain the use of distributed data management in applications.

Demo introduction: The Demo is written based on the OpenHarmony system using the eTS language. This Demo is mainly implemented through device certification, distributed pull-up, distributed data management and other functions.

Project creation and page layout will not be described in detail here. This chapter focuses on custom pop-up windows and distributed data management.

1. Customized pop-up window


Through the explanation of custom pop-up windows, I hope you can learn how to implement your own custom pop-up windows in your project.

1.1 Create a custom pop-up window through the @CustomDialog decorator. For usage, please refer to the custom pop-up window:

Official reference link:zh-cn/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md · OpenHarmony/docs – Gitee.com


1.2 The layout is composed of Text, List, and Button from top to bottom. The sub-elements in List are composed of Text and Radio. The ellipsis in the following code indicates non-UI related logic code. For specific implementation, please refer to the source code:

@CustomDialog
struct gameStart {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
        //Top title
        Text('The following online devices were found').fontColor(Color.Black).fontSize(30)
      }.width('100%').height('20%')

      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
       //Use List container to dynamically load online devices
       List() {
          ForEach(this.deviceName, (item) => {
            ListItem() {
              Row() {
                //Text component displays device name
                Text(item.deviceName).width('80%').fontSize(30).fontColor(Color.Black)
                //Radio component displays radio button
                Radio({ value: '' }).checked(this.check[item.id]).onChange(() => {
                  //This ensures that when multiple Radio components are clicked in the List, only the currently clicked one is selected.
                  for (let i = 0; i < this.check.length; i++) {
                    this.check[i] = false
                  }
                  this.check[item.id] = true
                })
              }
            }
          }, item => item.id)
        }
        .height('80%')

        Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
          Button('OK').width(200).height(50).fontSize(30).onClick(() => {
            //......
            this.controller.close()
          })
        }.height('30%')

      }.width('100%').height('80%')
    }.height('100%').width('100%')
  }
}


Through the above method, we can complete our custom pop-up window. You can also try to complete your own custom pop-up window in your own project.

2. Distributed data management


Distributed data management can achieve synchronous data updates among multiple devices through subscription when data changes among multiple devices. When we need to synchronize data updates among multiple devices, we can use distributed data management to achieve this. The Tic Tac Toe Three Levels game uses distributed data management to realize synchronous updates of the game interface between multiple devices, allowing multiple devices to play the same game at the same time.

Official website reference link:zh-cn/application-dev/reference/apis/js-apis-distributed-data.md · OpenHarmony/docs – Gitee.com


The schematic diagram of data distributed operation is shown below.

Implementation steps:

Distributed data management relies on the @ohos.data.distributedData module. For details, refer to the RemoteDataManager.ets implementation steps in the project source code.

2.1 Import the module

import factory from '@ohos.data.distributedData';

2.2 Create KVManager instance for managing database objects

registerDataListCallback(callback) {
    let that = this
    if (this.kvManager == null) {
      try {
        const config = {
          userInfo: {
            userId: '0',
            userType: 0
          },
          bundleName: 'com.example.tictactoegame'
        }
        factory.createKVManager(config).then((manager) => {
          that.kvManager = manager
          that.registerDataListCallback_(callback)
        }).catch((err) => {
        })
      } catch (e) {
      }
    } else {
      this.registerDataListCallback_(callback)
    }
  }


Note: change bundleName to corresponding content

2.3 Create and obtain the KVStore database

registerDataListCallback_(callback) {
    let that = this
    if (that.kvManager == null) {
      callback()
      return
    }
    if (that.kvStore == null) {
      try {
        let options =
          {
            createIfMissing: true,
            encrypt: false,
            backup: false,
            autoSync: true,
            kvStoreType: 1,
            securityLevel: 3
          }
        this.kvManager.getKVStore(this.STORE_ID, options).then((store) => {
          that.kvStore = store
          that._registerDataListCallback_(callback)
        }).catch((err) => {
        })
      } catch (e) {
      }
    } else {
      this._registerDataListCallback_(callback)
    }
  }


Note: Change STORE_ID to the corresponding content

2.4 Subscribe to specified types of data change notifications

_registerDataListCallback_(callback) {
    let that = this
    if (that.kvManager == null) {
      callback()
      return
    }
    this.kvStore.on('dataChange', 1, function(data) {
      if (data) {
         that.arr = data.updateEntries
        callback()
      }
    })
  }


Note: 1 in the kvStore.on method corresponds to the subscription type. For details, see the detailed description in the official website reference above.

2.5 Add key-value pairs of specified types to the database

dataChange(key, value) {
    let that = this
      try {
        that.kvStore.put(JSON.stringify(key), JSON.stringify(value)).then((data) => {
        }).catch((err) => {
          prompt.showToast({message:'put err:'+JSON.stringify(value)})
        })

      } catch (e) {
      }
  }


Project download link:OpenHarmony-SIG/knowledge_demo_temp – Gitee.com


Related question description:

During the data transmission process of distributed data management, if the data contains Chinese characters, garbled characters will appear. Therefore, try not to use Chinese characters in data storage.

Through this three-chapter explanation, we know how to run the simplest OpenHarmony program on a standard device from scratch, and on this basis, we know how to play music, display animations, and convert images in OpenHarmony. Relevant advanced skills such as field animation, and how to achieve synchronous data updates between multiple devices through distributed data management.

In the latest version of OpenHarmony, we will bring more new features, more development boards, and more samples to you, so stay tuned.

 

Related Posts

vscode optimized user experience (settings | plug-ins)

[001] [ESP32 Development Notes] IDF project creation and CMake configuration

My NBIOT learning – BC35-G uses AT commands to connect to Huawei Cloud through CoAP protocol

The simplest Anaconda+Python3.7 installation tutorial on the Internet for Win10 (100% successful)

STM32+ESP8266+MQTT connects to Alibaba Cloud server (3. AT command connects to Alibaba Cloud platform)

[Graphic tutorial to solve the problem of Chinese garbled output in vscode terminal]

LeetCode Greedy Algorithm 1005. Maximized array sum after K times inversion

Robomaster wheel motion calculation

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*