头图

介绍

本示例展示了在eTS中分布式数据管理的使用,包括KVManager对象实例的创建和KVStore数据流转的使用。

通过设备管理接口[@ohos.distributedDeviceManager],实现设备之间的kvStore对象的数据传输交互,该对象拥有以下能力 ;
1、注册和解除注册设备上下线变化监听
2、发现周边不可信设备
3、认证和取消认证设备
4、查询可信设备列表
5、查询本地设备信息,包括设备名称,设备类型和设备标识
6、发布设备发现

效果预览

首页
main

使用说明

鸿蒙OS开发更多内容↓点击HarmonyOS与OpenHarmony技术
鸿蒙技术文档开发知识更新库gitee.com/li-shizhen-skin/harmony-os/blob/master/README.md在这。

1.两台设备组网。

2.在一台界面中点击右上角的流转按钮,在弹窗中选择对端设备拉起对端设备上的应用。

3.拉起对端设备后,在界面中点击"+"按钮新增笔记卡片,点击每个卡片右上角的"X"按钮可以删除此卡片,可以看到对端设备和当前设备界面数据保持一致。

4.操作对端设备,当前设备界面也会保持和对端设备界面显示一致。

搜狗高速浏览器截图20240326151450.png

鸿蒙next开发技术文档请前往mau12379
是v可以直接加拿取

具体实现

管理kvStore

1、页面初始化时获取此应用所需能力:引入@ohos.data.distributedKVStore初始化kvstore数据库并对使用kvstore.on数据change进行监听,通过appstorge判断获取相应的key判断是否是分布式节点 。

源码:

/*

 * Copyright (c) 2020-2023 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */



import abilityAccessCtrl from '@ohos.abilityAccessCtrl'

import common from '@ohos.app.ability.common'

import { NoteModel } from '../model/NoteDataModel'

import { NoteListItem } from '../common/NoteItem'

import NoteDataSource from '../common/BasicDataSource'

import { TitleBar } from '../common/TitleBar'

import { KvStoreModel } from '../model/KvStoreModel'

import { RemoteDeviceModel } from '../model/RemoteDeviceModel'

import { transStrToNoteModel } from '../model/NoteDataModel'

import Logger from '../util/Logger'

import Want from '@ohos.app.ability.Want';



const NOTES_CHANGE = 'notesChange'

const EXIT = 'exit'

let kvStoreModel: KvStoreModel = new KvStoreModel()

let notesNum: number = 0

const TAG = 'KvstoreIndexPage'



@Entry

@Component

struct Index {

  private noteDataSource: NoteDataSource = new NoteDataSource([new NoteModel('', '')]);

  @State isDistributed: boolean = false

  private remoteDeviceModel: RemoteDeviceModel = new RemoteDeviceModel()



  aboutToAppear() {

    let context = getContext(this) as common.UIAbilityContext

    let atManager = abilityAccessCtrl.createAtManager()

    try {

      atManager.requestPermissionsFromUser(context,['ohos.permission.DISTRIBUTED_DATASYNC']).then((data) => {

        Logger.info(TAG, `data: ${JSON.stringify(data)}`)

      }).catch((err: object) => {

        Logger.info(TAG, `err: ${JSON.stringify(err)}`)

      })

    } catch (err) {

      Logger.info(TAG, `catch err->${JSON.stringify(err)}`);

    }

    let want = JSON.parse(AppStorage.Get('wantMsg')) as Want;

    Logger.info(TAG,`getWant =${JSON.stringify(want)}`);

    if(want.parameters != undefined) {

      if (want.parameters.isStage === 'Stage') {

        this.isDistributed = true

      }

    }

    kvStoreModel.setOnMessageReceivedListener(NOTES_CHANGE, (value) => {

      Logger.info(TAG,`NOTES_CHANGE${value}`)

      if (this.isDistributed) {

        if (value.search(EXIT) !== -1) {

          Logger.info(TAG,`[json]EXIT${EXIT}`)

          context.terminateSelf((error) => {

            Logger.info(TAG,`terminateSelf finished, error=${error}`)

          })

        } else {

          let str: string = value.substring(0, value.lastIndexOf('}]') + 2);

          this.noteDataSource.dataArray = transStrToNoteModel(str);

          this.noteDataSource.notifyDataReload()

          let strNum: string = value.substring(value.lastIndexOf('numBegin') + 'numBegin'.length, value.lastIndexOf('numEnd'));

          notesNum = Number(strNum)

        }

      }

    })

  }



  deleteNoteCallBack = (item: NoteModel) => {

    Logger.info(TAG, `deleteNote${JSON.stringify(item)}`);

    let dataArray: NoteModel[] = this.noteDataSource.dataArray;

    for (let i = 0; i < dataArray.length; i++) {

      Logger.info(TAG, `i = ${i} and dataArray = ${JSON.stringify(dataArray[i])}`)

      if (dataArray[i].title === item.title) {

        Logger.info(TAG, `deleteNote index` + i);

        this.noteDataSource.dataArray.splice(i, 1);

        break

      }

    }

    this.noteDataSource.notifyDataReload()

    kvStoreModel.put(NOTES_CHANGE, JSON.stringify(this.noteDataSource.dataArray) + 'numBegin' + notesNum + 'numEnd');

  }

  startAbilityCallBack = (key: string) => {

    Logger.info(TAG,`startAbilityCallBack${key}`);

    if (NOTES_CHANGE === key) {

      kvStoreModel.put(NOTES_CHANGE, `${JSON.stringify(this.noteDataSource.dataArray)}numBegin${notesNum}numEnd`);

    }

    if (EXIT === key) {

      kvStoreModel.put(NOTES_CHANGE, EXIT)

    }

  }



  build() {

    Column() {

      TitleBar({

        startAbilityCallBack: this.startAbilityCallBack,

        remoteDeviceModel: this.remoteDeviceModel,

        isDistributed: $isDistributed

      })



      Grid() {

        LazyForEach(this.noteDataSource, (item: NoteModel, index) => {

          GridItem() {

            NoteListItem({

              note: item,

              deleteNoteCallBack: this.deleteNoteCallBack,

              noteID: index

            })

          }

          .onClick(() => {

            Logger.info(TAG,`GridItem.click${item.title}`);

            if (item.title === '' && item.content === '') {

              notesNum += 1

              this.noteDataSource.dataArray[this.noteDataSource.dataArray.length-1] = new NoteModel(`note ${notesNum}`, 'noteContent');

              this.noteDataSource.dataArray.push(new NoteModel('', ''));

              this.noteDataSource.notifyDataReload()

              if (this.isDistributed) {

                kvStoreModel.put(NOTES_CHANGE, `${JSON.stringify(this.noteDataSource.dataArray)}numBegin${notesNum}numEnd`);

              }

            }

          })

        }, (item: NoteModel) => item.title)

      }

      .columnsTemplate('1fr 1fr 1fr')

      .columnsGap(10)

      .rowsGap(10)

      .padding(10)

      .margin({ bottom: 50 })

    }

  }



  onDestroy() {

    if (this.remoteDeviceModel !== null) {

      this.remoteDeviceModel.unregisterDeviceListCallback()

    }

    if (this.isDistributed) {

      this.isDistributed = false

    }

  }

}

2、如果是分布式节点,如果数据发生变化,处理数据并使用.noteDataSource()进行reload数据。
3、页面通过kvStore对象进行增删改查会触发其他已连接设备的kvStore.on监听。

管理分布式设备(节点)

1、创建设备管理对象,并指定参数kvstore应用包deviceManager.createDeviceManager("ohos.samples.kvstore", (error, value) => {})
2、获取可信设备列表,"this.deviceManager.getTrustedDeviceListSync())" 。 3、监听设备状态,"this.deviceManager.on('deviceStateChange', (data) => {})",从而对可信设备列表管理。


烧脑猴
24 声望21 粉丝

5年JAVA,3年Android。现转入鸿蒙开发行业,每日分享一些鸿蒙技术!