介紹
本示例展示了在eTS中分布式數(shù)據(jù)管理的使用,包括KVManager對(duì)象實(shí)例的創(chuàng)建和KVStore數(shù)據(jù)流轉(zhuǎn)的使用。
通過設(shè)備管理接口[@ohos.distributedDeviceManager],實(shí)現(xiàn)設(shè)備之間的kvStore對(duì)象的數(shù)據(jù)傳輸交互,該對(duì)象擁有以下能力 ;
1、注冊(cè)和解除注冊(cè)設(shè)備上下線變化監(jiān)聽
2、發(fā)現(xiàn)周邊不可信設(shè)備
3、認(rèn)證和取消認(rèn)證設(shè)備
4、查詢可信設(shè)備列表
5、查詢本地設(shè)備信息,包括設(shè)備名稱,設(shè)備類型和設(shè)備標(biāo)識(shí)
6、發(fā)布設(shè)備發(fā)現(xiàn)
效果預(yù)覽
使用說明 |
1.兩臺(tái)設(shè)備組網(wǎng)。
2.在一臺(tái)界面中點(diǎn)擊右上角的流轉(zhuǎn)按鈕,在彈窗中選擇對(duì)端設(shè)備拉起對(duì)端設(shè)備上的應(yīng)用。
3.拉起對(duì)端設(shè)備后,在界面中點(diǎn)擊"+"按鈕新增筆記卡片,點(diǎn)擊每個(gè)卡片右上角的"X"按鈕可以刪除此卡片,可以看到對(duì)端設(shè)備和當(dāng)前設(shè)備界面數(shù)據(jù)保持一致。
4.操作對(duì)端設(shè)備,當(dāng)前設(shè)備界面也會(huì)保持和對(duì)端設(shè)備界面顯示一致。
具體實(shí)現(xiàn)
管理kvStore
1、頁(yè)面初始化時(shí)獲取此應(yīng)用所需能力:引入@ohos.data.distributedKVStore初始化kvstore數(shù)據(jù)庫(kù)并對(duì)使用kvstore.on數(shù)據(jù)change進(jìn)行監(jiān)聽,通過appstorge判斷獲取相應(yīng)的key判斷是否是分布式節(jié)點(diǎn) 。
源碼:
/*
* 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、如果是分布式節(jié)點(diǎn),如果數(shù)據(jù)發(fā)生變化,處理數(shù)據(jù)并使用.noteDataSource()進(jìn)行reload數(shù)據(jù)。
3、頁(yè)面通過kvStore對(duì)象進(jìn)行增刪改查會(huì)觸發(fā)其他已連接設(shè)備的kvStore.on監(jiān)聽。
管理分布式設(shè)備(節(jié)點(diǎn))
1、創(chuàng)建設(shè)備管理對(duì)象,并指定參數(shù)kvstore應(yīng)用包deviceManager.createDeviceManager("ohos.samples.kvstore", (error, value) => {})
2、獲取可信設(shè)備列表,"this.deviceManager.getTrustedDeviceListSync())" 。
3、監(jiān)聽設(shè)備狀態(tài),"this.deviceManager.on('deviceStateChange', (data) => {})",從而對(duì)可信設(shè)備列表管理。
審核編輯 黃宇
-
數(shù)據(jù)管理
+關(guān)注
關(guān)注
1文章
294瀏覽量
19610 -
分布式
+關(guān)注
關(guān)注
1文章
895瀏覽量
74498 -
HarmonyOS
+關(guān)注
關(guān)注
79文章
1973瀏覽量
30143 -
OpenHarmony
+關(guān)注
關(guān)注
25文章
3713瀏覽量
16254
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
評(píng)論