键值型数据库跨设备数据同步demo

键值型数据库跨设备数据同步demo

HarmonyOS
2024-05-22 23:24:19
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
励志做个有为人

demo主要通过键值型数据库实现同应用跨设备同步数据

主要流程

1、申请多设备间数据交换权限

2、创建分布式数据库写入数据

3、将数据同步到其他设备

4、其他设备获取数据,查询数据库

前提

进行验证的两台设备在同一个局域网内并且登陆了同一个华为账号

核心代码解释

1、module.json5声明使用DISTRIBUTED_DATASYNC权限

"requestPermissions": [ 
  { 
    "name": 'ohos.permission.DISTRIBUTED_DATASYNC' 
  } 
],

2、应用拉起时拉起授权窗口,让用户选择

onPageShow(){ 
  // 获取分布式授权 
  let permission:Permissions[] = ['ohos.permission.DISTRIBUTED_DATASYNC']; 
  this.requestPermission(permission); 
} 
 
//拉起授权窗口 
requestPermission(permission:Permissions[]):void{ 
  let atManager:abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); 
  atManager.requestPermissionsFromUser(this.context,permission).then((data:PermissionRequestResult) =>{ 
    let grantStatus: Array<number> = data.authResults; 
    let length: number = grantStatus.length; 
    for (let i = 0; i < length; i++) { 
      if (grantStatus[i] != 0) { 
        // 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开对应的权限 
        return; 
      } 
    } 
    // 授权成功 
  }).catch((err: BusinessError) => { 
    console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`); 
  }) 
}

3、创建键值型数据库

创建分布式数据库管理器实例之后,通过管理器创建数据库

//创建分布式数据库,并订阅数据变化 
createKVStore(){ 
  try { 
    const kvManagerConfig: distributedKVStore.KVManagerConfig = { 
      bundleName: this.context.applicationInfo.name, 
      context: this.context 
    } 
    kvManager = distributedKVStore.createKVManager(kvManagerConfig); 
    console.info('Succeeded in creating KVManager.'); 
  } catch (e) { 
    let error = e as BusinessError; 
    console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`); 
  } 
 
  if (kvManager !== undefined) { 
    kvManager = kvManager as distributedKVStore.KVManager; 
  }else { 
    return; 
  } 
 
  try { 
    const options: distributedKVStore.Options = { 
      createIfMissing: true, 
      encrypt: false, 
      backup: false, 
      autoSync: false, 
      // kvStoreType不填时,默认创建多设备协同数据库 
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 
      // 多设备协同数据库:kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION, 
      securityLevel: distributedKVStore.SecurityLevel.S1 
    }; 
    kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { 
      if (err) { 
        console.error(`Failed to get KVStore: Code:${err.code},message:${err.message}`); 
        return; 
      } 
      console.info('Succeeded in getting KVStore.'); 
      kvStore = store; 
    }); 
  } catch (e) { 
    let error = e as BusinessError; 
    console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 
  } 
  if (kvStore !== undefined) { 
    kvStore = kvStore as distributedKVStore.SingleKVStore; 
  }else { 
    return; 
  } 
 
  //订阅分布式数据变化 
  try { 
    kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => { 
      console.info(`dataChange callback call data: ${data}`); 
    }); 
  } catch (e) { 
    let error = e as BusinessError; 
    console.error(`An unexpected error occurred. code:${error.code},message:${error.message}`); 
  } 
 
}

4、通过数据库的put或者get接口,分别写入或者查询数据库内容

写入数据库

kvStore.put(keyStr, valueStr, (err) => { 
  if (err !== undefined) { 
    console.error(`Failed to put data. Code:${err.code},message:${err.message}`); 
    return; 
  } 
  console.info('Succeeded in putting data.'); 
});

查询数据库

kvStore.get(this.getKeyStr, (err, data) => { 
  if (err != undefined) { 
    console.error(`Failed to get data. Code:${err.code},message:${err.message}`); 
    return; 
  } 
  console.info(`Succeeded in getting data. Data:${data}`); 
  this.resultValue = data.toString(); 
});

5、同步数据到其他设备

获取局域网内可用的设备列表,通过sysnc将数据同步到其他设备,或者拉去数据到本地,通过mode进行控制

shareDateToOtherDevice(mode: distributedKVStore.SyncMode){ 
  try { 
    // create deviceManager 
    devManager = deviceManager.createDeviceManager(this.context.applicationInfo.name); 
    this.devices = devManager.getAvailableDeviceListSync(); 
    //另一种获取设备列表方式 
    // devManager.getAvailableDeviceList().then((data: Array<deviceManager.DeviceBasicInfo>) => { 
    //   console.log('getAvailableDeviceList device info: ' + JSON.stringify(data)); 
    //   this.devices =data; 
    // }) 
    let deviceIds: string[] = []; 
      for (let i = 0; i < this.devices.length; i++) { 
        deviceIds[i] = this.devices[i].networkId as string; 
      } 
      if (kvStore!==undefined){ 
        try { 
          // 1000表示最大延迟时间为1000ms 
          kvStore.sync(deviceIds, mode, 1000); 
        } catch (e) { 
          let error = e as BusinessError; 
          console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`); 
        } 
      } 
  } catch (err) { 
    let error = err as BusinessError; 
    console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); 
  } 
}

环境信息

IDE:DevEco Studio 4.1.1.300

SDK:HarmoneyOS 4.0.0

分享
微博
QQ
微信
回复
2024-05-23 21:11:15
相关问题
键值数据库是否有做bundleName校验
1508浏览 • 1回复 待解决
多个数据库同步数据
1814浏览 • 1回复 待解决
HarmonyOS 关系数据库批量插入数据
155浏览 • 1回复 待解决
关系数据库使用分享
1020浏览 • 1回复 待解决
数据库操作同步的方法
1729浏览 • 1回复 待解决
分布式键值数据库使用分享
1040浏览 • 1回复 待解决