鸿蒙NEXT开发设备相关工具类(ArkTs)

复制代码
import { vibrator, VibratorStopMode } from '@kit.SensorServiceKit';
import { LogUtil } from './LogUtil';
import { resourceManager, DeviceType, Direction, ScreenDensity } from '@kit.LocalizationKit';
import { StrUtil } from './StrUtil';
import { AssetUtil } from './AssetUtil';
import { PreferencesUtil } from './PreferencesUtil';
import { RandomUtil } from './RandomUtil';
import deviceInfo from '@ohos.deviceInfo';
import { ResUtil } from './ResUtil';
import { identifier } from '@kit.AdsKit';
export const DEVICE_ID_KEY: string = "device_id_cache_harmony_key"; //设备ID的Key
/**
 * 定义移除操作的存储方法接口
 */
interface StorageMethodForRemove {
  removeSync: (key: string) => void;
}

/**
 * 定义获取和添加操作的存储方法接口
 */
interface StorageMethodForGetAdd {
  getSync: (key: string) => string | null;
  addSync: (key: string, value: string) => void;
}

/**
 * 设备相关工具类。
 * 提供设备信息、配置、能力、振动等功能的访问。
 *
 * @author 鸿蒙布道师
 * @since 2025/04/09
 */
export class DeviceUtil {
  private static deviceId: string = ''; // 设备ID
  /**
   * 获取设备ID(卸载APP后依旧不变)。
   * 如果未生成过设备ID,则会自动生成并存储。
   *
   * @param rule 是否包含 `-`,默认为 true。
   * @param generateId 自定义生成的ID(可选)。
   * @returns 返回设备ID。
   */
  static getDeviceId(rule: boolean = true, generateId?: string): string {
    if (StrUtil.isEmpty(DeviceUtil.deviceId)) {
      // 使用定义的接口类型
      const storageMethod: StorageMethodForGetAdd = AssetUtil.canIUse()
        ? AssetUtil
        : PreferencesUtil;

      const storedId: string | null = storageMethod.getSync(DEVICE_ID_KEY);
      let deviceId: string = StrUtil.toStr(storedId);

      if (StrUtil.isEmpty(deviceId)) {
        deviceId = generateId && StrUtil.isNotEmpty(generateId)
          ? generateId
          : RandomUtil.generateRandomUUID(true);

        if (!rule) {
          deviceId = deviceId.replace(/-/g, '');
        }

        storageMethod.addSync(DEVICE_ID_KEY, deviceId);
        !AssetUtil.canIUse() && LogUtil.error('当前设备不支持关键资产存储服务');
      }
      DeviceUtil.deviceId = deviceId;
    }
    return DeviceUtil.deviceId;
  }

  /**
   * 移除设备ID。
   */
  static deleteDeviceId(): void {
    DeviceUtil.deviceId = '';

    // 使用定义的接口类型
    const storageMethod: StorageMethodForRemove = AssetUtil.canIUse()
      ? AssetUtil
      : PreferencesUtil;

    storageMethod.removeSync(DEVICE_ID_KEY);
  }

  /**
   * 获取设备品牌名称。示例:HUAWEI。
   */
  static getBrand(): string {
    return deviceInfo.brand;
  }

  /**
   * 获取认证型号。示例:ALN-AL00。
   */
  static getProductModel(): string {
    return deviceInfo.productModel;
  }

  /**
   * 获取品牌和型号组合。示例:HUAWEI ALN-AL00。
   */
  static getBrandModel(): string {
    return `${deviceInfo.brand} ${deviceInfo.productModel}`;
  }

  /**
   * 获取市场名称。示例:HUAWEI Mate 60 Pro。
   */
  static getMarketName(): string {
    return deviceInfo.marketName;
  }

  /**
   * 获取硬件版本号。示例:HL1CMSM。
   */
  static getHardwareModel(): string {
    return deviceInfo.hardwareModel;
  }

  /**
   * 获取设备厂家名称。示例:HUAWEI。
   */
  static getManufacture(): string {
    return deviceInfo.manufacture;
  }

  /**
   * 获取系统版本。示例:HarmonyOS 5.0.0。
   */
  static getOsFullName(): string {
    return deviceInfo.osFullName;
  }

  /**
   * 获取产品版本。示例:ALN-AL00 5.0.0.1(XXX)。
   */
  static getDisplayVersion(): string {
    return deviceInfo.displayVersion;
  }

  /**
   * 获取系统软件API版本。示例:12。
   */
  static getSdkApiVersion(): number {
    return deviceInfo.sdkApiVersion;
  }

  /**
   * 获取编译构建的版本号。
   */
  static getBuildVersion(): number {
    return deviceInfo.buildVersion;
  }

  /**
   * 获取OS版本号。示例:5.0.0。
   */
  static getOsVersion(): string {
    return `${deviceInfo.majorVersion}.${deviceInfo.seniorVersion}.${deviceInfo.featureVersion}`;
  }

  /**
   * 获取开发者匿名设备标识符。
   */
  static getODID(): string {
    return deviceInfo.ODID;
  }

  /**
   * 获取设备序列号。需要权限:ohos.permission.sec.ACCESS_UDID。
   */
  static getSerial(): string {
    return deviceInfo.serial;
  }

  /**
   * 获取设备UDID。需要权限:ohos.permission.sec.ACCESS_UDID。
   */
  static getUdid(): string {
    return deviceInfo.udid;
  }

  /**
   * 获取开放匿名设备标识符。需要权限:ohos.permission.APP_TRACKING_CONSENT。
   */
  static async getOAID(): Promise<string> {
    return identifier.getOAID();
  }

  /**
   * 获取应用二进制接口(Abi)。示例:arm64-v8a。
   */
  static getAbiList(): string {
    return deviceInfo.abiList;
  }

  /**
   * 获取系统的发布类型。取值为:Canary、Beta、Release。
   */
  static getOsReleaseType(): string {
    return deviceInfo.osReleaseType;
  }

  /**
   * 获取当前设备类型编号。
   */
  static getDeviceType(): number {
    return DeviceUtil.getDeviceCapabilitySync().deviceType;
  }

  /**
   * 获取当前设备类型的字符串描述。
   */
  static getDeviceTypeStr(): string {
    switch (DeviceUtil.getDeviceType()) {
      case DeviceType.DEVICE_TYPE_PHONE:
        return '手机';
      case DeviceType.DEVICE_TYPE_TABLET:
        return '平板';
      case DeviceType.DEVICE_TYPE_PC:
        return '电脑';
      case DeviceType.DEVICE_TYPE_TV:
        return '电视';
      case DeviceType.DEVICE_TYPE_CAR:
        return '汽车';
      case DeviceType.DEVICE_TYPE_WEARABLE:
        return '穿戴';
      case DeviceType.DEVICE_TYPE_2IN1:
        return '2IN1';
      default:
        return '';
    }
  }

  /**
   * 获取设备的Configuration(异步)。
   */
  static async getConfiguration(): Promise<resourceManager.Configuration> {
    return ResUtil.getConfiguration(true);
  }

  /**
   * 获取设备的Configuration(同步)。
   */
  static getConfigurationSync(): resourceManager.Configuration {
    return ResUtil.getConfigurationSync();
  }

  /**
   * 获取当前设备屏幕方向。
   */
  static getDirection(): Direction {
    return DeviceUtil.getConfigurationSync().direction;
  }

  /**
   * 获取设备的DeviceCapability(异步)。
   */
  static async getDeviceCapability(): Promise<resourceManager.DeviceCapability> {
    return ResUtil.getDeviceCapability(true);
  }

  /**
   * 获取设备的DeviceCapability(同步)。
   */
  static getDeviceCapabilitySync(): resourceManager.DeviceCapability {
    return ResUtil.getDeviceCapabilitySync();
  }

  /**
   * 获取当前设备屏幕密度。
   */
  static getScreenDensity(): ScreenDensity {
    return DeviceUtil.getDeviceCapabilitySync().screenDensity;
  }

  /**
   * 开启振动。
   * 需要权限:ohos.permission.VIBRATE。
   *
   * @param duration 振动时长(毫秒),默认为 1000ms。
   * @param usage 振动用途,默认为 'media'。
   */
  static startVibration(duration: number = 1000, usage: vibrator.Usage = 'media'): Promise<void> {
    return vibrator.startVibration({ type: 'time', duration }, { id: 0, usage });
  }

  /**
   * 停止振动。
   * 需要权限:ohos.permission.VIBRATE。
   */
  static stopVibration(): Promise<void> {
    return vibrator.stopVibration(VibratorStopMode.VIBRATOR_STOP_MODE_TIME);
  }
}

代码如下:

TypeScript 复制代码
import { vibrator, VibratorStopMode } from '@kit.SensorServiceKit';
import { LogUtil } from './LogUtil';
import { resourceManager, DeviceType, Direction, ScreenDensity } from '@kit.LocalizationKit';
import { StrUtil } from './StrUtil';
import { AssetUtil } from './AssetUtil';
import { PreferencesUtil } from './PreferencesUtil';
import { RandomUtil } from './RandomUtil';
import deviceInfo from '@ohos.deviceInfo';
import { ResUtil } from './ResUtil';
import { identifier } from '@kit.AdsKit';
export const DEVICE_ID_KEY: string = "device_id_cache_harmony_key"; //设备ID的Key
/**
 * 定义移除操作的存储方法接口
 */
interface StorageMethodForRemove {
  removeSync: (key: string) => void;
}

/**
 * 定义获取和添加操作的存储方法接口
 */
interface StorageMethodForGetAdd {
  getSync: (key: string) => string | null;
  addSync: (key: string, value: string) => void;
}

/**
 * 设备相关工具类。
 * 提供设备信息、配置、能力、振动等功能的访问。
 *
 * @author 鸿蒙布道师
 * @since 2025/04/09
 */
export class DeviceUtil {
  private static deviceId: string = ''; // 设备ID
  /**
   * 获取设备ID(卸载APP后依旧不变)。
   * 如果未生成过设备ID,则会自动生成并存储。
   *
   * @param rule 是否包含 `-`,默认为 true。
   * @param generateId 自定义生成的ID(可选)。
   * @returns 返回设备ID。
   */
  static getDeviceId(rule: boolean = true, generateId?: string): string {
    if (StrUtil.isEmpty(DeviceUtil.deviceId)) {
      // 使用定义的接口类型
      const storageMethod: StorageMethodForGetAdd = AssetUtil.canIUse()
        ? AssetUtil
        : PreferencesUtil;

      const storedId: string | null = storageMethod.getSync(DEVICE_ID_KEY);
      let deviceId: string = StrUtil.toStr(storedId);

      if (StrUtil.isEmpty(deviceId)) {
        deviceId = generateId && StrUtil.isNotEmpty(generateId)
          ? generateId
          : RandomUtil.generateRandomUUID(true);

        if (!rule) {
          deviceId = deviceId.replace(/-/g, '');
        }

        storageMethod.addSync(DEVICE_ID_KEY, deviceId);
        !AssetUtil.canIUse() && LogUtil.error('当前设备不支持关键资产存储服务');
      }
      DeviceUtil.deviceId = deviceId;
    }
    return DeviceUtil.deviceId;
  }

  /**
   * 移除设备ID。
   */
  static deleteDeviceId(): void {
    DeviceUtil.deviceId = '';

    // 使用定义的接口类型
    const storageMethod: StorageMethodForRemove = AssetUtil.canIUse()
      ? AssetUtil
      : PreferencesUtil;

    storageMethod.removeSync(DEVICE_ID_KEY);
  }

  /**
   * 获取设备品牌名称。示例:HUAWEI。
   */
  static getBrand(): string {
    return deviceInfo.brand;
  }

  /**
   * 获取认证型号。示例:ALN-AL00。
   */
  static getProductModel(): string {
    return deviceInfo.productModel;
  }

  /**
   * 获取品牌和型号组合。示例:HUAWEI ALN-AL00。
   */
  static getBrandModel(): string {
    return `${deviceInfo.brand} ${deviceInfo.productModel}`;
  }

  /**
   * 获取市场名称。示例:HUAWEI Mate 60 Pro。
   */
  static getMarketName(): string {
    return deviceInfo.marketName;
  }

  /**
   * 获取硬件版本号。示例:HL1CMSM。
   */
  static getHardwareModel(): string {
    return deviceInfo.hardwareModel;
  }

  /**
   * 获取设备厂家名称。示例:HUAWEI。
   */
  static getManufacture(): string {
    return deviceInfo.manufacture;
  }

  /**
   * 获取系统版本。示例:HarmonyOS 5.0.0。
   */
  static getOsFullName(): string {
    return deviceInfo.osFullName;
  }

  /**
   * 获取产品版本。示例:ALN-AL00 5.0.0.1(XXX)。
   */
  static getDisplayVersion(): string {
    return deviceInfo.displayVersion;
  }

  /**
   * 获取系统软件API版本。示例:12。
   */
  static getSdkApiVersion(): number {
    return deviceInfo.sdkApiVersion;
  }

  /**
   * 获取编译构建的版本号。
   */
  static getBuildVersion(): number {
    return deviceInfo.buildVersion;
  }

  /**
   * 获取OS版本号。示例:5.0.0。
   */
  static getOsVersion(): string {
    return `${deviceInfo.majorVersion}.${deviceInfo.seniorVersion}.${deviceInfo.featureVersion}`;
  }

  /**
   * 获取开发者匿名设备标识符。
   */
  static getODID(): string {
    return deviceInfo.ODID;
  }

  /**
   * 获取设备序列号。需要权限:ohos.permission.sec.ACCESS_UDID。
   */
  static getSerial(): string {
    return deviceInfo.serial;
  }

  /**
   * 获取设备UDID。需要权限:ohos.permission.sec.ACCESS_UDID。
   */
  static getUdid(): string {
    return deviceInfo.udid;
  }

  /**
   * 获取开放匿名设备标识符。需要权限:ohos.permission.APP_TRACKING_CONSENT。
   */
  static async getOAID(): Promise<string> {
    return identifier.getOAID();
  }

  /**
   * 获取应用二进制接口(Abi)。示例:arm64-v8a。
   */
  static getAbiList(): string {
    return deviceInfo.abiList;
  }

  /**
   * 获取系统的发布类型。取值为:Canary、Beta、Release。
   */
  static getOsReleaseType(): string {
    return deviceInfo.osReleaseType;
  }

  /**
   * 获取当前设备类型编号。
   */
  static getDeviceType(): number {
    return DeviceUtil.getDeviceCapabilitySync().deviceType;
  }

  /**
   * 获取当前设备类型的字符串描述。
   */
  static getDeviceTypeStr(): string {
    switch (DeviceUtil.getDeviceType()) {
      case DeviceType.DEVICE_TYPE_PHONE:
        return '手机';
      case DeviceType.DEVICE_TYPE_TABLET:
        return '平板';
      case DeviceType.DEVICE_TYPE_PC:
        return '电脑';
      case DeviceType.DEVICE_TYPE_TV:
        return '电视';
      case DeviceType.DEVICE_TYPE_CAR:
        return '汽车';
      case DeviceType.DEVICE_TYPE_WEARABLE:
        return '穿戴';
      case DeviceType.DEVICE_TYPE_2IN1:
        return '2IN1';
      default:
        return '';
    }
  }

  /**
   * 获取设备的Configuration(异步)。
   */
  static async getConfiguration(): Promise<resourceManager.Configuration> {
    return ResUtil.getConfiguration(true);
  }

  /**
   * 获取设备的Configuration(同步)。
   */
  static getConfigurationSync(): resourceManager.Configuration {
    return ResUtil.getConfigurationSync();
  }

  /**
   * 获取当前设备屏幕方向。
   */
  static getDirection(): Direction {
    return DeviceUtil.getConfigurationSync().direction;
  }

  /**
   * 获取设备的DeviceCapability(异步)。
   */
  static async getDeviceCapability(): Promise<resourceManager.DeviceCapability> {
    return ResUtil.getDeviceCapability(true);
  }

  /**
   * 获取设备的DeviceCapability(同步)。
   */
  static getDeviceCapabilitySync(): resourceManager.DeviceCapability {
    return ResUtil.getDeviceCapabilitySync();
  }

  /**
   * 获取当前设备屏幕密度。
   */
  static getScreenDensity(): ScreenDensity {
    return DeviceUtil.getDeviceCapabilitySync().screenDensity;
  }

  /**
   * 开启振动。
   * 需要权限:ohos.permission.VIBRATE。
   *
   * @param duration 振动时长(毫秒),默认为 1000ms。
   * @param usage 振动用途,默认为 'media'。
   */
  static startVibration(duration: number = 1000, usage: vibrator.Usage = 'media'): Promise<void> {
    return vibrator.startVibration({ type: 'time', duration }, { id: 0, usage });
  }

  /**
   * 停止振动。
   * 需要权限:ohos.permission.VIBRATE。
   */
  static stopVibration(): Promise<void> {
    return vibrator.stopVibration(VibratorStopMode.VIBRATOR_STOP_MODE_TIME);
  }
}
相关推荐
re1ife4 小时前
Android Studio开发知识:从基础到进阶
android·java·开发语言·android studio
寒雪谷4 小时前
小试牛刀-抽奖程序
开发语言·harmonyos·鸿蒙
吴同学是个程序员4 小时前
【Android】Android Studio 配置国内镜像源
android·ide·gradle·android studio·hosts
SuperHeroWu76 小时前
【HarmonyOS 5】使用openCustomDialog如何禁止手势关闭的方案
华为·harmonyos·open·customdialog·手势关闭
SuperHeroWu76 小时前
【HarmonyOS 5】鸿蒙的装饰器原理和自定义装饰器
华为·harmonyos·鸿蒙·装饰器·原理·自定义装饰器
脱脱克克6 小时前
2025.4.9 华为机考 第1题-补丁版本升级
python·算法·华为
jiet_h9 小时前
使用 Ktor 构建现代 Android 应用的后端服务
android
returnShitBoy11 小时前
iOS 上的内存管理是如何处理的?
macos·ios·cocoa
深漂阿碉11 小时前
Android studio2024的第一个安卓项目
android