HarmonyOS 鸿蒙Next 有办法可以取到固定的deviceId吗
HarmonyOS 鸿蒙Next 有办法可以取到固定的deviceId吗
目前取不到deviceId,所以随机生成一个,保存在沙箱路径内的txt文件内,但是APP卸载后,该txt文件也没了,或者有办法可以在沙箱路径外进行文件操作的话也是可以把deviceId存在文件里
3 回复
获取deviceId 参考demo如下,参考文档链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V13/js-apis-distributeddevicemanager-V13#getlocaldeviceid
import { BusinessError } from '@ohos.base';
import deviceManager from '@ohos.distributedDeviceManager';
import common from '@ohos.app.ability.common';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
@Entry
@Component
struct Device {
@State message: string = 'Hello World';
aboutToAppear(): void {
let context = getContext(this) as common.UIAbilityContext;
let atManager = abilityAccessCtrl.createAtManager();
try {
atManager.requestPermissionsFromUser(context, ['ohos.permission.DISTRIBUTED_DATASYNC']).then((data) => {
console.log('data: ' + JSON.stringify(data));
}).catch((err: object) => {
console.log('err: ' + JSON.stringify(err));
})
} catch (err) {
console.log('catch err->' + JSON.stringify(err));
}
}
build() {
Column() {
Text(this.message)
.id('HelloWorld')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.onClick(() => {
// const context = getContext(this) as common.UIAbilityContext.log(`bundleName: ${context.abilityInfo.bundleName}`)
try {
// 需要看一下自己的
let dmInstance = deviceManager.createDeviceManager('xxxxxx');
let deviceId: string = dmInstance.getLocalDeviceId();
console.log('local device id: ' + JSON.stringify(deviceId));
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error('getLocalDeviceId errCode:' + e.code + ',errMessage:' + e.message);
}
})
}
.height('100%')
.width('100%')
}
}
参考以下demo,存在缓存文件夹里:
import { fileIo, storageStatistics } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
import fs from '@ohos.file.fs';
import { AAID } from '@kit.PushKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { Lifecycle, MState, Observer } from '@ohos/liveeventbus';
import { abilityAccessCtrl, common, Permissions } from '@kit.AbilityKit';
import { distributedDeviceManager } from '@kit.DistributedServiceKit';
let dmInstance = distributedDeviceManager.createDeviceManager('com.applicationTest.liuyao');
let deviceId: string = dmInstance.getLocalDeviceId();
const permissions: Array<Permissions> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
function reqPermissionsFromUser(permissions: Array<Permissions>, context: common.UIAbilityContext): void {
let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager();
// requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
let grantStatus: Array<number> = data.authResults;
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] === 0) {
// 用户授权,可以继续访问目标操作
} else {
// 用户拒绝授权,提示用户必须授权才能访问当前页面的功能,并引导用户到系统设置中打开相应的权限
return;
}
}
// 授权成功
}).catch((err: BusinessError) => {
console.error(`Failed to request permissions from user. Code is ${err.code}, message is ${err.message}`);
})
}
@Entry
@Component
struct ClearCache {
// 在缓存中创建一个文件
aboutToAppear(): void {
const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
reqPermissionsFromUser(permissions, context);
}
writeFile() {
let filePath = getContext(this).cacheDir + '/test.txt';
let fileStream = fileIo.createStreamSync(filePath, 'w+');
fileStream.writeSync(deviceId);
fileStream.close();
}
// 获取应用数据空间大小
getCache() {
storageStatistics.getCurrentBundleStats((error: BusinessError, bundleStats: storageStatistics.BundleStats) => {
if (error) {
console.error('getCurrentBundleStats failed with error:' + JSON.stringify(error));
} else {
console.info('getCurrentBundleStats successfully:' + JSON.stringify(bundleStats));
console.info('appsize :' + bundleStats.appSize);
console.info('cacheSize :' + bundleStats.cacheSize);
console.info('dataSize :' + bundleStats.dataSize);
let cacheSizeTmp = (bundleStats.cacheSize / 1024 / 1024).toFixed(2)
let cacheSize = parseInt(cacheSizeTmp) < 1 ? parseInt(cacheSizeTmp) * 1024 + " KB" : cacheSizeTmp + "M";
console.info(cacheSize)
}
});
}
// 清理缓存
clearCache() {
let cacheDir = getContext(this).cacheDir;
console.info(cacheDir);
fileIo.listFile(cacheDir).then((filenames) => {
for (let i = 0; i < filenames.length; i++) {
let dirPath = cacheDir + '/' + filenames[i];
console.log(dirPath);
// 判断是否为文件夹
let isDirectory: boolean = false;
try {
isDirectory = fileIo.statSync(dirPath).isDirectory();
} catch (e) {
console.error(JSON.stringify(e));
}
if (isDirectory) {
fileIo.rmdirSync(dirPath);
} else {
fileIo.unlink(dirPath).then(() => {
console.info('remove file succeed');
}).catch((err: Error) => {
console.error('remove file failed with error message: ' + err.message);
});
}
}
})
this.getCache()
}
build() {
Column() {
Button('向缓存写入数据')
.onClick(() => {
this.writeFile();
})
Button('获取系统缓存大小')
.onClick(() => {
this.getCache();
})
Button('点击清理缓存')
.onClick(() => {
this.clearCache();
})
}
}
}
用第三方工具[@pura](/user/pura)/harmony-utils DeviceUtil.getDeviceId(),具体原理也是生成一个id,但是用了
关键资产存储服务,卸载也不会删除。
在HarmonyOS 鸿蒙Next系统中,获取固定的deviceId存在一定复杂性,因为系统出于隐私保护原则,限制了对硬件标识符的直接访问。以下是一些获取设备标识的方法,但需注意它们的适用性和限制:
- UDID:设备的唯一识别码,但仅限系统应用使用,一般开发者无法直接获取。
- AAID(Android Advertising ID):用于应用推送,但卸载APP或恢复设备出厂设置后,AAID会发生变化。
- OAID(Open Anonymous ID):广告标识符,同一台设备上不同的App获取到的OAID值一样,但用户关闭跟踪开关后,应用仅能获取到全0的OAID,且需要申请广告跟踪权限。
- 利用关键资产存储服务:通过@ohos.security.asset API的IS_PERSISTENT特性,在应用卸载时保留关键资产,如随机生成的UUID,但这并非真正的deviceId。
综上所述,HarmonyOS 鸿蒙Next系统没有直接提供获取固定deviceId的公开方法。如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html 。