HarmonyOS鸿蒙Next中如何获取设备信息 (型号、API版本)

HarmonyOS鸿蒙Next中如何获取设备信息 (型号、API版本) 问题描述:如何获取当前设备的API版本和品牌信息?

4 回复

导入包名:

import { deviceInfo } from '@kit.BasicServicesKit'

使用:
deviceInfo.xxx

更多关于HarmonyOS鸿蒙Next中如何获取设备信息 (型号、API版本)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


回答内容:使用@ohos.bundle.bundleManager获取自身应用信息,或@ohos.deviceInfo(需注意权限)。

示例代码:

/**
 * @author J.query
 * @date 2025/12/23 11:17
 * @email j-query@foxmail.com
 * Description:
 */
import bundle from '@ohos.bundle.bundleManager';

@Entry
@Component
struct DeviceInfoPage {
  @State appInfo: string = ''

  async getMyAppInfo() {
    try {
      let bundleInfo = await bundle.getBundleInfoForSelf(bundle.BundleFlag.GET_BUNDLE_INFO_DEFAULT);
      this.appInfo = `应用: ${bundleInfo.name}, 版本: ${bundleInfo.versionName}, API: ${bundleInfo.versionCode}`;
    } catch (err) {
      this.appInfo = '获取失败';
    }
  }

  build() {
    Column() {
      Text(this.appInfo)
        .fontSize(16)
        .margin(20)
      Button('获取应用信息')
        .onClick(() => this.getMyAppInfo())
    }
  }
}

cke_743.png

在HarmonyOS Next中,获取设备信息主要使用@ohos.deviceInfo模块。通过deviceInfo.brand可获取设备品牌,deviceInfo.manufacturer获取制造商,deviceInfo.marketName获取设备型号。API版本通过@ohos.application.AbilityConstant中的AbilityConstant.VERSION获取。需在module.json5中声明ohos.permission.GET_SYSTEM_INFO权限。

在HarmonyOS Next中,获取设备信息(如型号、API版本)主要通过deviceInfo模块实现。以下是具体方法:

1. 获取设备型号和品牌

使用deviceInfo.getModel()deviceInfo.getBrand()获取设备型号和品牌信息。

import { deviceInfo } from '@kit.DeviceInfoKit';

// 获取设备型号
let model: string = deviceInfo.getModel();

// 获取设备品牌
let brand: string = deviceInfo.getBrand();

2. 获取API版本

通过BundleManager获取应用的API版本,或使用deviceInfo获取系统版本信息。

import { bundleManager } from '@kit.AbilityKit';

// 获取当前应用的API版本
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION;
bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => {
  let apiVersion = data.applicationInfo.apiVersion;
}).catch((err) => {
  console.error('Failed to get bundle info. Code: ' + err.code + ', message: ' + err.message);
});

// 获取系统版本信息(如软件版本号)
let systemVersion: string = deviceInfo.getSoftwareVersion();

注意事项

  • 需要在module.json5中声明权限:
    {
      "module": {
        "requestPermissions": [
          {
            "name": "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED"
          }
        ]
      }
    }
    
  • 获取设备信息时需确保应用具有相应权限,并遵循隐私规范。

以上方法可准确获取HarmonyOS Next的设备型号、品牌及API版本信息。

回到顶部