AssetStore.ets 存取可能存在问题。建议自行排查一下。参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/asset-store-api-V5Index.etsimport { HttpHeaderInfo } from '../data/HttpHeaderInfo'; import { AssetStore } from './AssetStore'; import hilog from '@ohos.hilog'; import util from '@ohos.util'; import { Save, Query } from './Save'; @Entry @Component struct GuideHelloPage { private static deviceIdCacheKey = "device_id_cache_key" private static deviceId = "" // private userModel: UserModel = UserModel.getInstance(); @Prop widthSize: number = 167; @Prop heightSize: number = 53; // @StorageProp(EnvironmentUtils.key_colorMode) colorMode: ColorMode = ColorMode.LIGHT static async getDeviceId() { let deviceId = GuideHelloPage.deviceId //如果内存缓存为空,则从AssetStore中读取 if (!deviceId) { // deviceId = `${(await AssetStore.get(GuideHelloPage.deviceIdCacheKey)).data}` deviceId = await Query.query1(GuideHelloPage.deviceIdCacheKey) hilog.info(0x0000, 'testTag', '%{public}s', `get oaid failed, deviceId: ${deviceId}`); } //如果AssetStore中未读取到,则随机生成32位随机码,然后缓存到AssetStore中 if (!deviceId || deviceId === "undefined") { deviceId = util.generateRandomUUID(true).replace('-', '') // AssetStore.set(GuideHelloPage.deviceIdCacheKey, deviceId) Save.save(GuideHelloPage.deviceIdCacheKey,deviceId) hilog.info(0x0000, 'testTag', '%{public}s', `get 22, deviceId: ${deviceId}`); } GuideHelloPage.deviceId = deviceId hilog.info(0x0000, 'testTag', '%{public}s', `get 33, deviceId: ${deviceId}`); return deviceId } build() { Row() { Column() { Text("添加") .fontWeight(FontWeight.Bold) .fontColor("#ff09181f") .fontStyle(FontStyle.Italic) .onClick(() => { Save.save('a', '2') }) Text("查询") .fontWeight(FontWeight.Bold) .fontColor("#ff09181f") .fontStyle(FontStyle.Italic) .onClick(async () => { let a :string = await Query.query1('a') console.info('--------------:' + a) }) Text("Hi") .fontSize(23) .fontWeight(FontWeight.Bold) .fontColor("#ff09181f") .fontStyle(FontStyle.Italic) Text("我是Moo") .grayTextStyle() Text("初来乍到") .grayTextStyle() Text("要给我讲讲你的故事吗") .grayTextStyle() Text("…") .fontSize(17) .margin({ top: 10 }) .fontWeight(FontWeight.Normal) .fontColor("#ff09181f") .fontStyle(FontStyle.Italic) Button("打开我的日记") .fontSize(16) .size({ width: this.widthSize, height: this.heightSize }) .fontColor(Color.Red) .margin({ top: 10 }) .backgroundColor("#36D") .onClick(async (event: ClickEvent) => { let res:string = await GuideHelloPage.getDeviceId() console.info(`设备id: ${res}`) }) Button("登录个人账号") .fontSize(16) .size({ width: this.widthSize, height: this.heightSize }) .fontColor(Color.Red) .margin({ top: 10 }) .borderColor("#36D") .backgroundColor("#fffff") .borderWidth(1.67) } .width('100%') } .height('100%') } } @Extend(Text) function grayTextStyle() { .fontSize(17) .fontColor("#ff09181f") .margin({ top: 10 }) .fontWeight(FontWeight.Bold) .fontStyle(FontStyle.Italic) }Save.etsimport { asset } from '@kit.AssetStoreKit'; import { util } from '@kit.ArkTS'; import { BusinessError } from '@kit.BasicServicesKit'; function stringToArray(str: string): Uint8Array { let textEncoder = new util.TextEncoder(); return textEncoder.encodeInto(str); } function arrayToString(arr: Uint8Array): string { let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true }); let str = textDecoder.decodeWithStream(arr, { stream: false }) return str; } export class Save { static save(key: string, value: string) { let attr: asset.AssetMap = new Map(); // 关键资产别名,每条关键资产的唯一索引。 // 类型为Uint8Array,长度为1-256字节。 attr.set(asset.Tag.ALIAS, stringToArray(key)); // 关键资产明文。 // 类型为Uint8Array,长度为1-1024字节 attr.set(asset.Tag.SECRET, stringToArray(value)); // 关键资产同步类型>THIS_DEVICE只在本设备进行同步,如仅在本设备还原的备份场景。 // attr.set(asset.Tag.SYNC_TYPE, asset.SyncType.THIS_DEVICE); //枚举,新增关键资产时的冲突(如:别名相同)处理策略。OVERWRITE》抛出异常,由业务进行后续处理。 // attr.set(asset.Tag.CONFLICT_RESOLUTION, asset.ConflictResolution.THROW_ERROR) // 在应用卸载时是否需要保留关键资产。 // 需要权限: ohos.permission.STORE_PERSISTENT_DATA。 // 类型为bool。 // if (true) { // attr.set(asset.Tag.IS_PERSISTENT, true); // } try { asset.add(attr).then(() => { console.info(`Asset added successfully.`); }).catch((err: BusinessError) => { console.error(`Failed to add Asset. Code is ${err.code}, message is ${err.message}`); }) } catch (error) { let err = error as BusinessError; console.error(`Failed to add Asset. Code is ${err.code}, message is ${err.message}`); } } } export class Query { static value: string = '' static async query1(key: string): Promise<string> { let query: asset.AssetMap = new Map(); query.set(asset.Tag.ALIAS, stringToArray(key)); // 指定了关键资产别名,最多查询到一条满足条件的关键资产 query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL); // 此处表示需要返回关键资产的所有信息,即属性+明文 try { await asset.query(query).then((res: Array<asset.AssetMap>) => { for (let i = 0; i < res.length; i++) { // parse the secret. let secret: Uint8Array = res[i].get(asset.Tag.SECRET) as Uint8Array; // parse uint8array to string let secretStr: string = arrayToString(secret); Query.value = secretStr console.info(secretStr) } }).catch((err: BusinessError) => { console.error(`Failed to query Asset. Code is ${err.code}, message is ${err.message}`); }); } catch (error) { let err = error as BusinessError; console.error(`Failed to query Asset. Code is ${err.code}, message is ${err.message}`); } return Query.value } }
AssetStore.ets 存取可能存在问题。建议自行排查一下。
参考链接:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/asset-store-api-V5
Index.ets
Save.ets