import { asset } from '@kit.AssetStoreKit';
import util from '@ohos.util';
import { deviceInfo } from '@kit.BasicServicesKit';
function stringToArray(str: string): Uint8Array {
let textEncoder = new util.TextEncoder();
return textEncoder.encodeInto(str);
}
function setAttr(id: string) {
let attr: asset.AssetMap = new Map();
attr.set(asset.Tag.SECRET, stringToArray(id));
attr.set(asset.Tag.ALIAS, stringToArray('demo_device_id'));
attr.set(asset.Tag.IS_PERSISTENT, true);
try {
asset.add(attr).then(() => {
console.info(`Asset added successfully.`);
}).catch(() => {
console.error(`Failed to add Asset.`);
})
} catch (error) {
console.error(`Failed to add Asset.`);
}
}
function arrayToString(arr: Uint8Array): string {
let textDecoder = util.TextDecoder.create("utf-8", { ignoreBOM: true });
let str = textDecoder.decodeWithStream(arr, { stream: false })
return str;
}
async function getAttr(): Promise<string> {
let query: asset.AssetMap = new Map();
query.set(asset.Tag.ALIAS, stringToArray('demo_device_id')); // 指定了关键资产别名,最多查询到一条满足条件的关键资产
query.set(asset.Tag.RETURN_TYPE, asset.ReturnType.ALL); // 此处表示需要返回关键资产的所有信息,即属性+明文
try {
const res: Array<asset.assetmap> = await asset.query(query)
// 解析密钥
let secret: Uint8Array = res[0].get(asset.Tag.SECRET) as Uint8Array;
// 将uint8array解析为字符串
let secretStr: string = arrayToString(secret);
return secretStr;
} catch (error) {
console.error(`Failed to query Asset.`);
return '';
}
}
@Entry
@Component
struct AttrTest {
build() {
Column() {
Button('获取设备ID').onClick(async (event: ClickEvent) => {
let deviceId: string = await getAttr();
if (deviceId === undefined || deviceId === null || deviceId.length === 0) {
deviceId = deviceInfo.ODID;
setAttr(deviceId);
}
console.log('设备ID为:' + deviceId)
})
.height(100)
.width('100%')
}
}
}