代码如下:
import { util } from '@kit.ArkTS';
import { asset } from '@kit.AssetStoreKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Index {
build() {
Column() {
Button('setAssetData').onClick(() => {
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.SECRET, stringToArray('demo_pwd11'));
attr.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
attr.set(asset.Tag.ACCESSIBILITY, asset.Accessibility.DEVICE_FIRST_UNLOCKED);
attr.set(asset.Tag.DATA_LABEL_NORMAL_1, stringToArray('demo_label'));
try {
asset.addSync(attr);
console.error(`Suc to add Asset.`)
} catch (error) {
let err = error as BusinessError;
console.error(`Failed to add Asset. Code is ${err.code}, message is ${err.message}`);
}
})
Button('getAssetData').onClick(() => {
let query: asset.AssetMap = new Map();
query.set(asset.Tag.ALIAS, stringToArray('demo_alias'));
try {
let res: Array<asset.AssetMap> = asset.querySync(query);
for (let i = 0; i < res.length; i++) {
if (res[i] != null) {
const bs = res[i].get(asset.Tag.SECRET) as Uint8Array;
if (bs) {
console.error(`Suc to query is ${arrayToString(bs)}`);
} else {
console.error(`fail to query bs undefind!`);
}
}
}
} catch (error) {
let err = error as BusinessError;
console.error(`Failed to query Asset. Code is ${err.code}, message is ${err.message}`);
}
})
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
}
}
function stringToArray(str: string): Uint8Array {
let textEncoder = new util.TextEncoder();
return textEncoder.encodeInto(str);
}
function arrayToString(bs: Uint8Array): string {
let textDecoder = util.TextDecoder.create()
return textDecoder.decodeToString(bs)
}
示例参考如下: