鸿蒙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);
  }
}
相关推荐
石山岭18 小时前
自己动手写了一个 Android 虚拟定位 App:GPSSimulate 技术实
android·前端
杉氧20 小时前
副作用 (Side Effects) 全攻略:如何像大师一样掌控 Composable 的生命周期?
android·架构·android jetpack
ONEDAY1 天前
HarmonyOS 深色模式适配实践:从资源、WebView 到网络图统一处理
harmonyos
Kapaseker1 天前
Kotlin Toolchain 0.11 发布:主要是把 Amper 干没了
android·kotlin
三少爷的鞋1 天前
Android 现代架构不需要事件总线进阶篇
android
杉氧2 天前
深入理解 Compose 重组机制:快照系统如何驱动 UI 精准刷新?
android·架构·android jetpack
召钱熏2 天前
状态枚举正确≠渲染正确:一个语音按钮的状态机边界修复实录
android·前端
杉氧2 天前
深度解析:Jetpack Compose 核心架构与底层原理 —— 十年安卓老兵的“破茧重生”
android·架构·android jetpack
通玄2 天前
Jetpack Compose 入门系列(七):ViewModel 与界面状态管理
android
落魄Android在线炒饭2 天前
Android Framework 开发技巧:android.jar 生成与系统快速编译验证
android