介紹
本示例展示了在eTS中分布式數據管理的使用,包括KVManager對象實例的創建和KVStore數據流轉的使用。
通過設備管理接口[@ohos.distributedDeviceManager],實現設備之間的kvStore對象的數據傳輸交互,該對象擁有以下能力 ;
1、注冊和解除注冊設備上下線變化監聽
2、發現周邊不可信設備
3、認證和取消認證設備
4、查詢可信設備列表
5、查詢本地設備信息,包括設備名稱,設備類型和設備標識
6、發布設備發現
效果預覽
使用說明 |
1.兩臺設備組網。
2.在一臺界面中點擊右上角的流轉按鈕,在彈窗中選擇對端設備拉起對端設備上的應用。
3.拉起對端設備后,在界面中點擊"+"按鈕新增筆記卡片,點擊每個卡片右上角的"X"按鈕可以刪除此卡片,可以看到對端設備和當前設備界面數據保持一致。
4.操作對端設備,當前設備界面也會保持和對端設備界面顯示一致。
具體實現
管理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) => {})",從而對可信設備列表管理。
審核編輯 黃宇
-
數據管理
+關注
關注
1文章
290瀏覽量
19609 -
分布式
+關注
關注
1文章
880瀏覽量
74470 -
HarmonyOS
+關注
關注
79文章
1967瀏覽量
30033 -
OpenHarmony
+關注
關注
25文章
3665瀏覽量
16161
發布評論請先 登錄
相關推薦
評論