基于@ohos.data.unifiedDataChannel实现数据共享

场景描述:

​本模块为统一数据管理框架(Unified Data Management Framework,UDMF)的组成部分,针对多对多跨应用数据共享的不同业务场景提供了标准化的数据通路,提供了标准化的数据接入与读取接口。同时对文本、图片等数据类型提供了标准化定义,方便不同应用间进行数据交互,减少数据类型适配的工作量。

常见场景:

1、考虑到会存在一台手机同时安装多个app的场景,需要有同一个用户账号登录信息。

2、期望公司内部的应用可以使用同一个唯一标识符用于识别同一用户。

场景实现:

场景一:

同一公司不同App间的账号共享

效果图:

方案:

一、应用A创建用户id并插入到UDMF的公共数据通路中。

​ 1、在ui界面定义了两个文本输入框(用于输入用户名和密码)

​ 2、声明一个 options 变量,并指定了要插入数据的数据通路枚举类型为 DATA_HUB。

​ 3、调用 insertData 函数,尝试将数据插入到指定的数据通路中

​ 4、进行异常处理

import { unifiedDataChannel, uniformTypeDescriptor } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
 
@Entry
@Component
struct Index {
  @State username: string = '';
  @State passwd: string = '';
 
  insert() {
    //创建一个新的 PlainText 实例。
    let plainText = new unifiedDataChannel.PlainText();
    plainText.textContent = this.username;
    //创建一个 UnifiedData 实例,传入之前创建的 PlainText 实例作为参数
    let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
    // 声明一个 options 变量,并指定了要插入数据的数据通路枚举类型为 DATA_HUB。
    let options: unifiedDataChannel.Options = {
      intention: unifiedDataChannel.Intention.DATA_HUB
    }
    //异常处理
    try {
      //调用 insertData 函数,尝试将数据插入到指定的数据通路中。
      // (err,data)回调函数,用于处理 insertData 函数执行过程中可能出现的错误信息和插入成功后返回的数据信息。
      unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
        if (err === undefined) {
          console.info(`Succeeded in inserting data. key = ${plainText.textContent}`);
        } else {
          console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
        }
      });
    } catch (e) {
      //将捕获的异常 e 强制转换为 BusinessError 类型,并赋值给 error 变量。
      let error: BusinessError = e as BusinessError;
      console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
    }
  }
 
  build() {
    Column() {
      //定义了两个文本输入框(用于输入用户名和密码)
      TextInput({ placeholder: 'input your username',text: this.username })
        .margin({ top: 20 })
        .onSubmit((EnterKeyType)=>{
          console.info(EnterKeyType+'输入法回车键的类型值')
        })
        .onChange((value: string) => {
          this.username = value;
        })
      TextInput({ placeholder: 'input your password',text: this.passwd })
        .type(InputType.Password).margin({ top: 20 })
        .onSubmit((EnterKeyType)=>{
          console.info(EnterKeyType+'输入法回车键的类型值')
        })
 
      //触发按钮
      Button('insert')
        .width(150)
        .margin({ top: 20 })
        .onClick(() => this.insert());
 
  }
 
}

二、应用B查询存储在UDMF公共数据通路中的用户id。

​ 1、创建 PlainText 实例和UnifiedData 实例。

​ 2、声明一个 options 变量,并指定了要查询数据的数据通路枚举类型为 DATA_HUB。

​ 3、调用 queryData 方法发起数据查询,然后输入到文本框

​ 4、进行异常处理

核心代码:

import { unifiedDataChannel, uniformTypeDescriptor } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
 
@Entry
@Component
struct Index {
  @State username: string = '';
  @State passwd: string = '';
  onPageShow() {
    this.doWork();
  }
  build() {
    Column() {
      //定义了两个文本输入框(用于输入用户名和密码)
      TextInput({ placeholder: 'input your username',text: this.username })
        .margin({ top: 20 })
        .onSubmit((EnterKeyType)=>{
          console.info(EnterKeyType+'输入法回车键的类型值')
        })
      TextInput({ placeholder: 'input your password',text: this.passwd })
        .type(InputType.Password).margin({ top: 20 })
        .onSubmit((EnterKeyType)=>{
          console.info(EnterKeyType+'输入法回车键的类型值')
        })
 
      //按钮
      Button('Sign in')
        .width(150)
        .margin({ top: 20 })
    }
  }
 
  private doWork() {
    let options: unifiedDataChannel.Options = {
      intention: unifiedDataChannel.Intention.DATA_HUB
    };
    try {
      //调用 unifiedDataChannel.queryData 方法发起数据查询
      unifiedDataChannel.queryData(options, (err, data) => {
        //如果 err 为 undefined,表示查询成功,代码将遍历查询结果并输出
        if (err === undefined) {
          console.info(`Succeeded in querying data. size = ${data.length}`);
          for (let i = 0; i < data.length; i++) {
            let records = data[i].getRecords();
            for (let j = 0; j < records.length; j++) {
              if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
                let text = records[j] as unifiedDataChannel.PlainText;
                this.username = text.textContent;
              }
            }
          }
        } else {
          console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
        }
      });
    } catch (e) {
      let error: BusinessError = e as BusinessError;
      console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
    }
  }
}

场景二:

同一公司不同应用间共享唯一标识符用于识别同一用户

效果图:

方案:

一、应用A生成唯一标识符并插入到UDMF的公共数据通路中。

​ 1、创建 PlainText 实例和UnifiedData 实例。

​ 2、声明一个 options 变量,并指定了要插入数据的数据通路枚举类型为 DATA_HUB。

​ 3、调用 insertData 函数,将数据插入到指定的数据通路中

​ 4、进行插入操作异常处理

​ 5、创建一个删除按钮,调用deleteData函数,将数据通路中的数据全部删除

​ 6、进行删除操作的异常处理。如果options中填入的是key,则删除key对应的数据并返回该数据。 如果options中填入的是intention,则删除intention下所有数据并返回删除的数据。

import { BusinessError } from '@ohos.base';
import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
 
 
@Entry
@Component
struct Index {
  @State message: string = 'insert';
 
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            //创建一个新的 PlainText 实例。
            let plainText = new unifiedDataChannel.PlainText();
             plainText.textContent ='550e8400-e29b-41d4-a716-446655440000';
            //创建一个 UnifiedData 实例,传入之前创建的 PlainText 实例作为参数
            let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
            // 声明一个 options 变量,并指定了要插入数据的数据通路枚举类型为 DATA_HUB。
            let options: unifiedDataChannel.Options = {
              intention: unifiedDataChannel.Intention.DATA_HUB
            }
            //异常处理
            try {
              //调用 insertData 函数,尝试将数据插入到指定的数据通路中。
              // (err,data)回调函数,用于处理 insertData 函数执行过程中可能出现的错误信息和插入成功后返回的数据信息。
              unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
                if (err === undefined) {
                  console.info(`Succeeded in inserting data. key = ${data}`);
                } else {
                  console.error(`Failed to insert data. code is ${err.code},message is ${err.message} `);
                }
              });
            } catch (e) {
              //将捕获的异常 e 强制转换为 BusinessError 类型,并赋值给 error 变量。
              let error: BusinessError = e as BusinessError;
              console.error(`Insert data throws an exception. code is ${error.code},message is ${error.message} `);
            }
          })
          .height(100)
        Text("delete")
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            // 声明一个 options 变量,并指定了要删除数据的数据通路枚举类型为 DATA_HUB
            let options: unifiedDataChannel.Options = {
              intention: unifiedDataChannel.Intention.DATA_HUB
            };
 
            try {
              //调用unifiedDataChannel.deleteData方法,传入选项对象options以及一个回调函数。回调函数接收两个参数,err表示可能出现的错误,data表示删除操作的数据结果。如果options中填入的是key,则删除key对应的数据并返回该数据。  如果options中填入的是intention,则删除intention下所有数据并返回删除的数据。
              unifiedDataChannel.deleteData(options, (err, data) => {
                //检查是否有错误发生,如果err为undefined,表示没有错误。
                if (err === undefined) {
                  console.info(`Succeeded in deleting data. size = ${data.length}`);
                  //开始遍历删除的数据,循环遍历每个数据项。
                  for(let i = 0; i < data.length; i++) {
                    //获取当前数据项的记录(records)数组
                    let records = data[i].getRecords();
                    for (let j = 0; j < records.length; j++) {
                      //检查当前记录的类型是否为纯文本类型。
                      if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
                        //将当前记录强制转换为纯文本类型。
                        let text = records[j] as unifiedDataChannel.PlainText;
                       // 输出当前纯文本记录的内容
                        console.info(`${i + 1}.${text.textContent}`);
                      }
                    }
                  }
                } else {
                  console.error(`Failed to delete data. code is ${err.code},message is ${err.message} `);
                }
              });
            } catch (e) {
              let error: BusinessError = e as BusinessError;
              console.error(`Delete data throws an exception. code is ${error.code},message is ${error.message} `);
            }
          })
 
      }
      .width('100%')
    }
    .height('100%')
  }
}

二、应用B查询应用A生成的唯一标识符

​ 1、创建 PlainText 实例和UnifiedData 实例。

​ 2、声明一个 options 变量,并指定了要查询数据的数据通路枚举类型为 DATA_HUB。

​ 3、调用 queryData 方法发起数据查询

​ 4、进行异常处理

import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
import { BusinessError } from '@ohos.base';
 
@Entry
@Component
struct Index {
  @State message: string = '查询';
 
  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            let options: unifiedDataChannel.Options = {
              intention: unifiedDataChannel.Intention.DATA_HUB
            };
            try {
              调用 unifiedDataChannel.queryData 方法发起数据查询
              unifiedDataChannel.queryData(options, (err, data) => {
                // //如果 err 为 undefined,表示查询成功,代码将遍历查询结果并输出
                if (err === undefined) {
                  console.info(`Succeeded in querying data. size = ${data.length}`);
                  for (let i = 0; i < data.length; i++) {
                    let records = data[i].getRecords();
                    for (let j = 0; j < records.length; j++) {
                      if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
                        let text = records[j] as unifiedDataChannel.PlainText;
                        console.info(`${i + 1}.${text.textContent}`);
                      }
 
                    }
                  }
                } else {
                  console.error(`Failed to query data. code is ${err.code},message is ${err.message} `);
                }
              });
            } catch(e) {
              let error: BusinessError = e as BusinessError;
              console.error(`Query data throws an exception. code is ${error.code},message is ${error.message} `);
            }
 
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值