鸿蒙next 常用功能封装集合

297 阅读3分钟

整个集合公共方法库

import { promptAction, router } from '@kit.ArkUI';
import { call } from '@kit.TelephonyKit';
import { BusinessError, pasteboard } from '@kit.BasicServicesKit';
import CryptoJS from '@ohos/crypto-js'
import { abilityAccessCtrl, bundleManager, Context } from '@kit.AbilityKit';
import { client_secret, test_public_key } from './until/config';
import { ResponseResult } from './until/api';
import { localStorage } from './until/GlobalContext';
import { buffer, util } from '@kit.ArkTS';

import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { routerParamsType } from './until/type';
import { geoLocationManager } from '@kit.LocationKit';
//统一提示toast
class ShowToast {
  private longToastTime: number = 3000;
  private shortToastTime: number = 1000;
    //自定义弹窗时间,内容
  showToast(message: ResourceStr, duration: number) {
    promptAction.showToast({ message: message, duration: duration, bottom: 200 });
  }
    //一秒短暂弹窗内容
  shortToast(message: ResourceStr) {
    this.showToast(message, this.shortToastTime);
  }
  //3秒长时间弹窗内容
  longToast(message: ResourceStr) {
    this.showToast(message, this.longToastTime);
  }
}

let ShowT = new ShowToast()

//正则验证手机号
function expMobile(phoneNumber: string): boolean {
  // 定义手机号码的正则表达式模式
  const regex = /^1\d{10}$/;
  // 使用正则表达式的 test 方法进行匹配
  const isValid = regex.test(phoneNumber);
  // 输出验证结果
  if (isValid) {
    // console.log("手机号码合规");
    return true
  } else {
    console.log("手机号码不合规");
    return false
  }
}


//拨打电话
function callForAnyone(mobile: string): void {
  if (canIUse("SystemCapability.Applications.Contacts")) {
    call.makeCall(mobile, (err: BusinessError) => {
      if (err) {
        console.error(`makeCall fail, err->${JSON.stringify(err)}`);
      } else {
        console.log(`makeCall success`);
      }
    });
  } else {
    let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, '4009960033');
    pasteboard.getSystemPasteboard().setData(pasteData, (error) => {

      if (error.code) {
        ShowT.shortToast(error.message)
      } else {
        ShowT.shortToast('该设备不支持拨打电话,已帮您复制到剪切板')
      }
    })

  }

}


//正则匹配密码是否包含数字和字母
function checkPassword(password: string) {
  // 正则表达式,要求密码包含至少一个字母和一个数字
  const regex = /^(?=.*[a-zA-Z])(?=.*\d).+$/;
  // 使用正则表达式的 test 方法进行匹配
  return regex.test(password);
}

interface custom_dialog_list_int {
  icon?: Resource | string
  value: string
  id?: number
}

//展示随时的弹窗
@CustomDialog
struct customDialog_Text {
  private controller: CustomDialogController = new CustomDialogController({
    builder: customDialog_Text()
  });
  @Prop showBtn: boolean
  @Prop backgroundC: string | Resource
  @Prop menjin_name: string
  @State c_m_name: string = ''
  private confirm: Function = () => {
  }

  aboutToAppear(): void {
    this.c_m_name = this.menjin_name
  }

  build() {
    Column() {

      Text('编辑门禁名称').margin({ top: 20, bottom: 20 })
      TextInput({ placeholder: '请填写', text: this.c_m_name })
        .placeholderColor('#888')
        .backgroundColor('#fff')
        .width('100%')
        .padding({ left: 0 })
        .margin({ bottom: 20 })
        .fontSize($r('app.float.progress_font'))
        .selectedBackgroundColor('#fff')
        .placeholderFont({ size: $r('app.float.progress_font') })
        .border({
          width: 1,
          color: $r('app.color.gray_color')
        })
        .onChange((val: string) => this.c_m_name = val)

      if (this.showBtn) {
        Row() {
          Button('取消').margin(10).backgroundColor('#fff').fontColor('#000')
            .onClick(() => {
              this.controller.close()
              console.info(JSON.stringify(this.controller.close))
            })
          Button('确定').margin(10).backgroundColor($r('app.color.theme_color'))
            .onClick(() => {
              this.confirm(this.c_m_name)

            })
        }.width('100%').justifyContent(FlexAlign.SpaceBetween)
      }
    }.padding(12).backgroundColor(this.backgroundC || '#fff').width('100%')
  }
}


//随机签名算法
/***
 * params 传参格式为需要加密的字符串,即需要传递到后台的数据,如
 * stringA="application_id=xxxx&body=test&business_uuid=xxxx&device_info=1000&nonce_str=5";
 */
function signInfo(params: string): string {
  // console.log(sortQueryStringByParamName(params) + "&secret=" + client_secret, '排序之后的值,未加密');
  // console.log(CryptoJS.MD5(sortQueryStringByParamName(params) + "&secret=" + client_secret));
  return CryptoJS.MD5(sortQueryStringByParamName(params) + "&secret=" + client_secret).toString().toUpperCase()
}

//排序,除开secret不参与排序
function sortQueryStringByParamName(queryString: string): string {
  // 解析查询字符串,得到键值对数组
  let keyValuePairs: string[]
  keyValuePairs = queryString.split('&');
  // 提取参数名并排序
  const sortedParamNames = keyValuePairs.map(pair => pair.split('=')[0]).sort();
  let list: string[] = [];
  // 根据排序后的参数名重新构建查询字符串
  sortedParamNames.map((name: string) => {
    let new_arr: string = keyValuePairs.filter((item: string) => {
      return item.indexOf(name + '=') != -1
    })[0] || ''
    if (new_arr) {
      list.push(new_arr)
    }
  });
  return list.join('&');
}

//生成随机32位字符串
function generateRandomString(length = 32) {
  const characters: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    result += characters[randomIndex];
  }

  return result.toString().toUpperCase();
}


//返回系统版本信息
function returnBundleInfo(): Promise<bundleManager.BundleInfo> {
  return new Promise((resolve: Function, reject: Function) => {
    bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION).then((bundleInfo) => {

      resolve(bundleInfo)
    }).catch((error: BusinessError) => {
      reject({})
      console.error("get bundleInfo failed,error is " + error)
    })
  })
}

//对字符串进行url 编码
function urlEncode(str: string) {
  // 使用encodeURIComponent()对字符串进行URL编码
  return encodeURIComponent(str)// 将encodeURIComponent()编码后的结果中的'!'、'*'、'('、')'转换为对应的编码形式
    .replace(/[!'()*]/g, (c) => {
      return '%' + c.charCodeAt(0).toString(16).toUpperCase();
    });
}

//登录之后的处理
async function login_to_do(res: ResponseResult) {
  let data = res as ResponseResult
  if (!data.token_type) {

    return
  } else {
    //获取用户信息
    if (typeof res == 'object' && res.access_token) {
      //先保存token
      await localStorage.setItem('token', data.access_token || '');
      await localStorage.setItem('refresh_token', data.refresh_token || '')
      routerClear()
      routerReplace('pages/home/homePage')

    }
  }
}

//执行处理RSA加密
async function encryptRSA(message: string) {

  // 服务器下发RSA公钥字符串(base64编码)

  let pubKeyStr = test_public_key;

  // 初始化Base64工具实例

  let base64Helper = new util.Base64Helper();

  // 公钥转换为Uint8Array,然后包装为DataBlob类型

  let pubKeyBlob: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(pubKeyStr) };

  // 创建RSA key生成器

  let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024');

  // 将公钥包装数据pubKeyBlob转换成密钥对类型KeyPair

  let keyPair = await rsaGenerator.convertKey(pubKeyBlob, null);

  // 创建 Cipher对象

  let cipher = cryptoFramework.createCipher('RSA1024|PKCS1');

  // 初始化加密模式,指定密钥keyPair.pubKey

  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null);

  // 包装要加密的明文

  let plainTextBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) };

  // 传入明文,获取加密后的数据

  let encryptBlob = await cipher.doFinal(plainTextBlob);

  // 返回加密后的字符串

  return base64Helper.encodeToStringSync(encryptBlob.data);

}

//定义路由列表数据项
class routerList {
  public url: string = '';
  public params: routerParamsType = {}

  constructor(url: string, params?: routerParamsType) {
    this.url = url;
    if (params) {
      this.params = params
    }
  }
}

//存路由栈
let r_list: routerList[] = [new routerList('pages/welcome/welcome')]

//页面跳转方式
function pushUrl(url: string, params?: routerParamsType) {
  if (params) {
    // params.prev_page_url = router.getState().path + router.getState().name
  }
  if (r_list.length < 30) {
    r_list.push(new routerList(url, params))
  } else {
    r_list.shift()
    r_list.push(new routerList(url, params))
  }
  router.pushUrl({
    url: url,
    params: params
  })
}

//路由返回,如果有携带参数,则返回上一层,并携带上参数
//路由返回特定地址
function routerBack(url?: string | number, param?: routerParamsType) {
  console.log(JSON.stringify(r_list))
  if (typeof url == 'string') {
    //特定返回格式
    let needChangeIndex = -1;
    let index = r_list.length;
    let r_param: routerParamsType = {}
    r_list.map((v, i) => {
      if (v.url == url) {
        needChangeIndex = i
        r_param = v.params
      }
    })
    r_list.splice(needChangeIndex, index - needChangeIndex);
    r_list.push(new routerList(url, param || r_param))
    router.pushUrl({
      url: url,
      params: param || r_param
    })
  } else if (typeof url == 'number') {
    for (let i = 0; i < url; i++) {
      r_list.pop();
    }
    let index = r_list.length;
    if (index == 0) {
      router.back()
    } else {
      router.back({
        url: r_list[index-1].url,
        params: r_list[index-1].params
      })
    }
  } else {
    r_list.pop();
    let index = r_list.length;
    if (index == 0) {
      router.back()
    } else {
      router.back({
        url: r_list[index-1].url,
        params: r_list[index-1].params
      })
    }
  }

}

//清除所有路由栈
function routerClear() {
  r_list = []
  router.clear()
}

//路由替换
function routerReplace(url: string, params?: routerParamsType) {
  r_list.pop();
  r_list.push(new routerList(url, params))
  router.replaceUrl({
    url: url,
    params: params
  })
}

//判断是否token失效
function missToken(msg: string) {
  let str = false;
  console.log(msg, 'missToken')
  switch (msg) {
    case '无效的color-token':
      str = true;
      break;
    case 'oauth认证失败':
      str = true;
      break;
    case 'The refresh token is invalid.':
      str = true;
      break;
    default:
      break;
  }
  return str
}

//隐藏手机号中间4位
function hidePhoneNumber(phoneNumber: string): string {
  if (phoneNumber.length !== 11) {
    return phoneNumber
  }

  const prefix = phoneNumber.substring(0, 3);
  const suffix = phoneNumber.substring(7);

  return `${prefix}****${suffix}`;
}

//缓存数据请求
async function saveCache(name: string, reload?: boolean): Promise<string> {
  // console.log(name,reload)
  if (reload) {
    return ''
  } else {
    let data: string;
    if (name.indexOf('big') != -1) {
      data = await localStorage.getBigItem(name)
    } else {
      data = await localStorage.getItem(name) as string
    }
    // console.info(data,'data')
    if (data && typeof data == 'string') {
      // console.log(data,'cache')
      return data
    } else {
      return ''
    }
  }
}

//邮箱校验
function validateEmail(email: string) {
  // 正则表达式用来验证邮箱格式
  const re = /\S+@\S+.\S+/;
  return re.test(email);
}

//处理扫码完成之后
function jumpUrl(str: string) {
  if (str.indexOf('http') == -1) {
    ShowT.longToast('请扫描二维码链接')
    // console.log(JSON.stringify(r_list))
    routerBack()
  } else {
    pushUrl('pages/web/webPage', { link: str })
  }
}

//获取定位
function getLocation(context: Context): Promise<geoLocationManager.GeoAddress[]> {
  return new Promise(async (resolve: Function, reject: Function) => {
    let isLocation_flag = await localStorage.getItem('privacy_location')
    // console.log(isLocation_flag + '', String(isLocation_flag))
    if (isLocation_flag && String(isLocation_flag) != 'true') {
      // console.log('请先打开隐私=>通过地理位置搜索到我')
      ShowT.shortToast('请先打开隐私=>通过地理位置搜索到我')
      reject([])
      return
    }
    let atManager = abilityAccessCtrl.createAtManager();
    try {
      atManager.requestPermissionsFromUser(context,
        ['ohos.permission.LOCATION', 'ohos.permission.APPROXIMATELY_LOCATION'])
        .then(async (data) => {
          const requestResponse = async (location: geoLocationManager.Location) => {
            console.info(`enter requestResponse`)
            let reverseGeocodeRequest: geoLocationManager.ReverseGeoCodeRequest = {
              "latitude": location.latitude,
              "longitude": location.longitude,
              "maxItems": 1
            };
            try {
              geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, async (err, data) => {
                if (err) {
                  console.info('getAddressesFromLocation: err=' + JSON.stringify(err));
                  reject([])
                }
                if (data) {
                  let administrativeArea = data[0].administrativeArea as string;
                  if (administrativeArea.length > 4) {
                    if (administrativeArea.length === 6) {
                      administrativeArea = '内蒙古'
                    } else {
                      let arr = administrativeArea.split('')
                      arr.length = 2
                      administrativeArea = arr.join('')
                    }
                  } else {
                    let arr = administrativeArea.split('')
                    arr.length = arr.length - 1
                    administrativeArea = arr.join('')
                  }
                  // this.city = administrativeArea
                  console.info('getAddressesFromLocation: data=' + JSON.stringify(data));
                  resolve(data)
                  await geoLocationManager.off('locationChange')
                }
              });
            } catch (error) {
              reject([])
              console.info(`http request error: ${JSON.stringify(error)}`)
            }
          }
          let requestInfo: geoLocationManager.LocationRequest = {
            'priority': geoLocationManager.LocationRequestPriority.FIRST_FIX,
            'scenario': geoLocationManager.LocationRequestScenario.UNSET,
            'timeInterval': 1,
            'distanceInterval': 0,
            'maxAccuracy': 0
          };
          try {
            geoLocationManager.on('locationChange', requestInfo, async (location: geoLocationManager.Location) => {
              console.log(JSON.stringify(location), 'location')
              await requestResponse(location)
            });
          } catch (err) {
            console.error("errCode:" + (err as BusinessError).code + ",errMessage:" + (err as BusinessError).message);
            reject([])
          }
          console.info(`on locationChange end`)
        })
        .catch((err: BusinessError) => {
          console.warn(`err:APPROXIMATELY_LOCATION ${JSON.stringify(err)}`)
          ShowT.shortToast('您关闭了定位服务,请开启')
        })
    } catch (err) {
      console.warn(`catch errAPPROXIMATELY_LOCATION->${JSON.stringify(err)}`)
      reject([])
    }
  })
}

//时间戳转时间格式
function timestampToTime(params: number, jestDate?: boolean) {
  // 使用 Date 对象将时间戳转换为日期对象
  const date = new Date(params);

  // 使用 Date 对象的方法获取年、月、日等信息
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从 0 开始,所以要加 1
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  // 格式化日期和时间
  let formattedDateTime: string
  if (jestDate) {
    formattedDateTime = `${year}-${month}-${day} `;
  } else {
    formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  }

  return formattedDateTime
}


//通过时间戳返回剩余的年月日
function formatDuration(timestamp: number) {
  const seconds = Math.floor(timestamp / 1000);
  const minutes = Math.floor(seconds / 60);
  const hours = Math.floor(minutes / 60);
  const days = Math.floor(hours / 24);
  const months = Math.floor(days / 30);
  const years = Math.floor(months / 12);

  // 计算剩余的天数、小时数
  const remainingDays = days % 30;
  const remainingHours = hours % 24;

  // 返回最大的时间单位
  if (years > 0) {
    return years + '年';
  } else if (months > 0) {
    return months + '个月';
  } else if (remainingDays > 0) {
    return remainingDays + '天';
  } else {
    return remainingHours + '小时';
  }
}

//输入1234,返回当前时间的7天的当前时间戳和7天之后的时间戳,其他类似
//这里定义最好是作为类导出,因为其他地方调取这个函数时需要通过obj去调取

interface  calculateTimestampType{
  currentTimestamp:number,
  futureTimestamp:number
}
function calculateTimestamp(value: number): calculateTimestampType {
  const now = new Date(); // 当前时间
  let futureDate = new Date();

  // 根据传入的值设置未来日期
  if (value === 1) {
    futureDate.setDate(now.getDate() + 7); // 加7天
  } else if (value === 2) {
    futureDate.setMonth(now.getMonth() + 1); // 加一个月
  } else if (value === 3) {
    futureDate.setMonth(now.getMonth() + 6); // 加6个月
  } else if (value === 4) {
    futureDate.setFullYear(now.getFullYear() + 1); // 加一年
  }

  // 计算时间戳
  const currentTimestamp = now.getTime(); // 当前时间戳
  const futureTimestamp = futureDate.getTime(); // 未来时间戳

  return {
    currentTimestamp: Math.floor(currentTimestamp / 1000),
    futureTimestamp: Math.floor(futureTimestamp / 1000)
  };
}

//网页跳转判断
function gotoWeb(url: string) {
  if (url.indexOf('http') == 0) {
    //网页直接跳转
    pushUrl('pages/web/webPage', { link: url })
  } else if (url.indexOf('pages') != -1) {
    //小程序跳转
    ShowT.shortToast('暂不支持跳转小程序,请等待')
  } else if (url.indexOf('colourlife') == 0) {
    //跳转原生
    ShowT.shortToast('开发中,敬请期待')
  } else {

  }

}

//姓名只展示最后一个
function hideName(name: string): string {
  if (name.length > 1) {
    const hiddenPart = '*'.repeat(name.length - 1);
    return hiddenPart + name.charAt(name.length - 1);
  } else if (name.length === 1) {
    // 如果名字只有一个字,不隐藏
    return name;
  } else {
    return ''
    //throw new Error("姓名不能为空");
  }
}

//校验身份证是否合规
function isValidIDCard(idCard: string): boolean {
  // 检查长度
  if (idCard.length !== 18) {
    return false;
  }

  // 检查前17位是否为数字,第18位是否为数字或X
  const idRegex = /^\d{17}[\dXx]$/;
  if (!idRegex.test(idCard)) {
    return false;
  }

  // 检查出生日期是否合法
  const birthDateStr = idCard.substring(6, 14);
  const year = parseInt(birthDateStr.substring(0, 4), 10);
  const month = parseInt(birthDateStr.substring(4, 6), 10);
  const day = parseInt(birthDateStr.substring(6, 8), 10);
  const birthDate = new Date(year, month - 1, day);

  if (
    birthDate.getFullYear() !== year ||
      birthDate.getMonth() + 1 !== month ||
      birthDate.getDate() !== day
  ) {
    return false;
  }

  // 验证校验码
  const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
  const checkSumChars = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];

  let sum = 0;
  for (let i = 0; i < 17; i++) {
    sum += parseInt(idCard[i], 10) * weightFactors[i];
  }
  const modValue = sum % 11;
  const checkChar = checkSumChars[modValue];

  return checkChar === idCard[17].toUpperCase();
}
//输入年月,输出当前月份的起止时间戳
function getMonthRangeTimestamps(year: number, month: number): [number, number] {
  // Calculate start of the month timestamp
  const startOfMonth = new Date(year, month - 1, 1); // month - 1 because month is zero-indexed in JavaScript Date
  const startTimestamp = startOfMonth.getTime() / 1000; // convert milliseconds to seconds

  // Calculate end of the month timestamp
  let endOfMonth: Date;
  if (month === 12) {
    endOfMonth = new Date(year + 1, 0, 1); // January of next year
  } else {
    endOfMonth = new Date(year, month, 1); // 1st of next month
  }
  const endTimestamp = (endOfMonth.getTime() / 1000) - 1; // end of current month - 1 second

  return [startTimestamp, endTimestamp];
}
//校验密码只包含数字和字母
function isValidPassword(password: string): boolean {
  const hasNumber = /[0-9]/.test(password); // 检查是否包含数字
  const hasLetter = /[a-zA-Z]/.test(password); // 检查是否包含字母(大小写)

  // 检查是否只包含数字和字母,并且长度在6到20之间
  const isAlphanumeric = /^[a-zA-Z0-9]{6,20}$/.test(password);

  return hasNumber && hasLetter && isAlphanumeric;
}


export { ShowT,
  expMobile,
  checkPassword,
  customDialog_Text,
  signInfo,
  returnBundleInfo,
  generateRandomString,
  login_to_do,
  encryptRSA,
  pushUrl,
  routerBack,
  routerClear,
  routerReplace,
  missToken,
  hidePhoneNumber,
  callForAnyone,
  saveCache,
  validateEmail,
  urlEncode,
  jumpUrl,
  getLocation,
  timestampToTime,
  calculateTimestamp,
  gotoWeb,
  hideName,
  isValidIDCard,getMonthRangeTimestamps ,isValidPassword};

其中 引入部分有些字段根据你实际项目决定是否保留,如有需要,则自行补充

config.ts

./until/config.ts

client_secret//你如果有加密,则这个表示你这边的加密字符
test_public_key //同上,加密的公钥

api.ets

./until/api.ets
//统一的数据返回格式,可根据项目做对应调整,这个只是基础模板,每个content需要自行再定义
class ResponseResult {
  /**
   * Code returned by the network request: success, fail.
   */
  code: number;
  /**
   * Message returned by the network request.
   */
  message: string ;
  /**
   * Data returned by the network request.
   */
  content: string | Object | ArrayBuffer;
  contentEncrypt: string
  token_type?: string;
  expires_in?: number;
  access_token?: string;
  refresh_token?: string;
  specialInfo?: string;

  constructor() {
    this.code = -1;
    this.message = '';
    this.content = '';
    this.contentEncrypt = ''
  }
}
export {ResponseResult}

GlobalContext.ets

//./until/GlobalContext.ets

import { distributedKVStore, preferences } from '@kit.ArkData'
import { BusinessError } from '@kit.BasicServicesKit';
import { bundleManager } from '@kit.AbilityKit';

class GlobalContext {
  private constructor() {
  }

  private static instance: GlobalContext;
  private _objects = new Map<string, Object>();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object | undefined {
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}

let that = this

class LocalStorage {
  public getKvStore(): Promise<distributedKVStore.SingleKVStore> {
    let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA;
    let info_: bundleManager.BundleInfo = bundleManager.getBundleInfoForSelfSync(bundleFlags)
    let kvManagerConfig: distributedKVStore.KVManagerConfig = {
      context: getContext(that),
      bundleName: info_.name
    };
    let kvManager: distributedKVStore.KVManager = distributedKVStore.createKVManager(kvManagerConfig)
    return new Promise((resolve: Function, reject: Function) => {
      try {
        const options: distributedKVStore.Options = {
          createIfMissing: true, // 当数据库文件不存在时是否创建数据库,默认创建
          encrypt: false, // 设置数据库文件是否加密,默认不加密
          backup: false, // 设置数据库文件是否备份,默认备份
          kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建的数据库类型,默认为多设备协同数据库
          securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库安全级别
        };
        // storeId为数据库唯一标识符
        kvManager.getKVStore('storeId', options, (err, kvStore: distributedKVStore.SingleKVStore) => {
          if (err) {
            console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`);
            reject('err')
            return;
          }
          console.info('Succeeded in getting KVStore.');

          // 进行相关数据操作
          resolve(kvStore)
        });
      } catch (e) {
        reject('err')
        console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
      }
    })
  }

  getItem(value: string): Promise<string | Object | number | boolean | null | undefined> {
    return new Promise((resolve: Function, reject: Function) => {
      //用户首选项操作
      preferences.getPreferences(getContext(this), 'myStore').then((obj: preferences.Preferences) => {
        obj.has(value).then(async (isExit: Boolean) => {
          // console.info('isExit:' + isExit)
          if (!isExit) {
            resolve('')
          } else {
            let res: preferences.ValueType = await obj.get(value, '');
            // console.log(res+'454545'+value)
            resolve(res)

          }
        }).catch((err: Error) => {
          reject(JSON.stringify(err))
        })
      }).catch((err: Error) => {
        reject(JSON.stringify(err))
      })
    })
  }

  setItem(value: string, data: preferences.ValueType): Promise<null> {
    return new Promise((resolve: Function) => {
      preferences.getPreferences(getContext(this), 'myStore').then((obj: preferences.Preferences) => {
        obj.has(value).then(async (isExit: Boolean) => {
          // console.info('isExit:' + isExit)
          obj.put(value, data)
          obj.flush()
          resolve(null)

        })
      })
    })
  }

  clearItem(): Promise<null> {
    return new Promise((resolve: Function) => {
      preferences.deletePreferences(getContext(this), 'myStore', (err: BusinessError) => {
        if (err) {
          console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message);
          return;
        }
        resolve(null)
        console.info("Succeeded in deleting preferences.");
      })

    })
  }

  //启用键值对数据库处理
  getBigItem(value: string): Promise<string> {
    return new Promise((resolve: Function) => {
      this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {
        try {
          kvStore.get(value, (err, data) => {
            if (err !== undefined) {
              console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
              resolve('')
              return;
            }
            // console.info(`Succeeded in getting data. data:${data}`);
            resolve(data)
          });
        } catch (e) {
          let error = e as BusinessError;
          console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
          resolve('')
        }

      })
    })
  }

  //设置值
  setBigItem(value: string, data: string): Promise<string> {
    return new Promise((resolve: Function) => {
      this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {

        try {
          kvStore.put(value, data, (err) => {
            if (err !== undefined) {
              console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
              resolve('')
              return;
            }
            resolve('success')
            console.info('Succeeded in putting data.');
          });
        } catch (e) {
          let error = e as BusinessError;
          console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
          resolve('')
        }
      })
    })
  }

  //删除
  deleteBigItem(value: string): Promise<string> {
    return new Promise((resolve: Function) => {
      this.getKvStore().then((kvStore: distributedKVStore.SingleKVStore) => {

        kvStore.delete(value, (err) => {
          if (err !== undefined) {
            console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
            resolve('')
            return;
          }
          resolve('success')
          console.info('Succeeded in deleting data.');
        })
      })
    })
  }
}

const localStorage = new LocalStorage()

export {
  GlobalContext, LocalStorage, localStorage, }

type.ets

//./until/type.ets
//我这边的思路是做一个大集合,将所有可能的参数形式都包含进去
interface routerParamsType {
  mobile?: string,
  psw?: string,
  link?: string,
  prev_page_url?: string,
  sms_token?: string,
  hasGesture?:number,
  hasPassword?:number,
  hasOptions?:boolean,
  isCallback?:boolean,
  result?:Array<scanBarcode.ScanResult>,
  uri?:string,
  infoW?:number,
  infoH?:number,
  options?:scanBarcode.ScanOptions,
  identity_id?:number,
  invalid_unit?: getAllCommunityKeyDataListinvalid_unitType[],
  authorization_detail_item?:remoteDoorAuthorizeListApply_listType | remoteDoorAuthorizeListAuthorization_listType,
  title?:string,
  pano?:string,
  mobileInfo?:wallet_getInfoByMobileType,
  amount?:number,
  state?:number,
  token?:string,
  sn?:string,
}
export {routerParamsType}