设备信息
HarmonyOS 提供丰富的设备信息查询能力,包括设备基本信息、系统信息、屏幕信息、电池信息、网络信息等,帮助应用适配不同设备和场景。
API 列表
| API | 说明 | 起始版本 |
|---|---|---|
deviceInfo.osFullName | 系统完整名称 | API 6 |
deviceInfo.brand | 设备品牌 | API 6 |
deviceInfo.marketName | 设备型号 | API 6 |
deviceInfo.productSeries | 产品系列 | API 6 |
deviceInfo.displayVersion | 系统版本号 | API 6 |
deviceInfo.sdkApiVersion | SDK API 版本 | API 6 |
deviceInfo.hardwareModel | 硬件型号 | API 9 |
deviceInfo.hardwareProfile | 硬件 profile | API 9 |
deviceInfo.serial | 设备序列号(需权限) | API 6 |
deviceInfo.udid | 设备唯一标识(需权限) | API 6 |
设备基本信息
获取设备信息
typescript
import { deviceInfo } from '@kit.BasicServicesKit'
function getDeviceBasicInfo(): void {
console.info('设备品牌:', deviceInfo.brand)
console.info('设备型号:', deviceInfo.marketName)
console.info('产品系列:', deviceInfo.productSeries)
console.info('系统名称:', deviceInfo.osFullName)
console.info('系统版本:', deviceInfo.displayVersion)
console.info('SDK API 版本:', deviceInfo.sdkApiVersion)
console.info('硬件型号:', deviceInfo.hardwareModel)
console.info('硬件 Profile:', deviceInfo.hardwareProfile)
}设备信息字段说明
| 字段 | 示例值 | 说明 |
|---|---|---|
osFullName | "HarmonyOS NEXT 5.0.0" | 系统完整名称和版本 |
brand | "HUAWEI" | 设备品牌 |
marketName | "Mate 60 Pro" | 市场宣传型号 |
productSeries | "Mate" | 产品系列 |
displayVersion | "5.0.0.100" | 系统显示版本号 |
sdkApiVersion | 12 | SDK API 版本号 |
hardwareModel | "ALN-AL00" | 硬件型号 |
hardwareProfile | "phone" | 硬件类型:phone/tablet/tv/watch/car 等 |
应用信息
获取应用基本信息
typescript
import { bundleManager } from '@kit.AbilityKit'
function getAppInfo(): void {
try {
const info = bundleManager.getBundleInfoForSelfSync(
bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT
)
console.info('应用名称:', info.name)
console.info('应用版本名:', info.versionName)
console.info('应用版本号:', info.versionCode)
console.info('应用包名:', info.name)
} catch (error) {
console.error('获取应用信息失败:', JSON.stringify(error))
}
}获取应用签名信息
typescript
import { bundleManager } from '@kit.AbilityKit'
function getAppSignatureInfo(): void {
try {
const info = bundleManager.getBundleInfoForSelfSync(
bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO
)
if (info.signatureInfo) {
console.info('应用 ID:', info.signatureInfo.appId)
console.info('指纹:', info.signatureInfo.fingerprint)
}
} catch (error) {
console.error('获取签名信息失败:', JSON.stringify(error))
}
}屏幕信息
获取屏幕参数
typescript
import { display } from '@kit.ArkUI'
function getScreenInfo(): void {
try {
const displayInfo = display.getDefaultDisplaySync()
console.info('屏幕宽度:', displayInfo.width)
console.info('屏幕高度:', displayInfo.height)
console.info('屏幕密度:', displayInfo.densityPixels)
console.info('屏幕 DPI:', displayInfo.densityDPI)
console.info('刷新率:', displayInfo.refreshRate)
console.info('屏幕方向:', displayInfo.orientation)
} catch (error) {
console.error('获取屏幕信息失败:', JSON.stringify(error))
}
}监听屏幕方向变化
typescript
import { display } from '@kit.ArkUI'
class ScreenOrientationMonitor {
private callback: display.Callback | null = null
startMonitoring(onChange: (orientation: display.Orientation) => void): void {
this.callback = {
onCreate: () => {},
onDestroy: () => {},
onChange: (data) => {
onChange(data.orientation)
}
}
display.on('change', this.callback)
}
stopMonitoring(): void {
if (this.callback) {
display.off('change', this.callback)
this.callback = null
}
}
}
// 使用示例
const monitor = new ScreenOrientationMonitor()
monitor.startMonitoring((orientation) => {
console.info('屏幕方向变化:', orientation)
if (orientation === display.Orientation.PORTRAIT) {
console.info('竖屏')
} else if (orientation === display.Orientation.LANDSCAPE) {
console.info('横屏')
}
})电池信息
获取电池状态
typescript
import { batteryInfo } from '@kit.BasicServicesKit'
function getBatteryInfo(): void {
console.info('电池电量:', batteryInfo.batterySOC, '%')
console.info('充电状态:', batteryInfo.chargingStatus)
console.info('健康状态:', batteryInfo.healthStatus)
console.info('电池温度:', batteryInfo.batteryTemperature, '0.1摄氏度')
console.info('电池电压:', batteryInfo.batteryVoltage, 'mV')
console.info('电池技术:', batteryInfo.batteryTechnology)
}电池状态枚举
| 充电状态 | 说明 |
|---|---|
CHARGING_STATE_NONE | 未充电 |
CHARGING_STATE_ENABLE | 充电中 |
CHARGING_STATE_FULL | 已充满 |
CHARGING_STATE_DISABLE | 充电禁用 |
CHARGING_STATE_UNKNOWN | 未知状态 |
| 健康状态 | 说明 |
|---|---|
BATTERY_HEALTH_UNKNOWN | 未知 |
BATTERY_HEALTH_GOOD | 良好 |
BATTERY_HEALTH_OVERHEAT | 过热 |
BATTERY_HEALTH_OVERVOLTAGE | 过压 |
BATTERY_HEALTH_COLD | 过冷 |
BATTERY_HEALTH_DEAD | 电池损坏 |
监听电池变化
typescript
import { batteryInfo } from '@kit.BasicServicesKit'
function listenBatteryChanges(): void {
batteryInfo.on('batteryChanged', (data) => {
console.info('电量变化:', data.batterySOC, '%')
console.info('充电状态:', data.chargingStatus)
})
}
function stopListenBattery(): void {
batteryInfo.off('batteryChanged')
}网络信息
获取网络连接信息
typescript
import { connection } from '@kit.NetworkKit'
function getNetworkInfo(): void {
try {
const netHandle = connection.getDefaultNetSync()
if (netHandle.netId === 0) {
console.info('当前无网络连接')
return
}
const capabilities = connection.getNetCapabilitiesSync(netHandle)
console.info('网络承载类型:', capabilities.bearerTypes)
console.info('网络能力:', capabilities.networkCap)
const properties = connection.getConnectionPropertiesSync(netHandle)
console.info('链路地址:', properties.linkAddress)
console.info('路由信息:', properties.routes)
} catch (error) {
console.error('获取网络信息失败:', JSON.stringify(error))
}
}判断网络类型
typescript
import { connection } from '@kit.NetworkKit'
enum NetworkType {
NONE = 'none',
WIFI = 'wifi',
CELLULAR = 'cellular',
ETHERNET = 'ethernet',
BLUETOOTH = 'bluetooth',
UNKNOWN = 'unknown'
}
function getNetworkType(): NetworkType {
try {
const netHandle = connection.getDefaultNetSync()
if (netHandle.netId === 0) {
return NetworkType.NONE
}
const capabilities = connection.getNetCapabilitiesSync(netHandle)
const bearerTypes = capabilities.bearerTypes
if (bearerTypes.includes(connection.NetBearType.BEARER_WIFI)) {
return NetworkType.WIFI
}
if (bearerTypes.includes(connection.NetBearType.BEARER_CELLULAR)) {
return NetworkType.CELLULAR
}
if (bearerTypes.includes(connection.NetBearType.BEARER_ETHERNET)) {
return NetworkType.ETHERNET
}
if (bearerTypes.includes(connection.NetBearType.BEARER_BLUETOOTH)) {
return NetworkType.BLUETOOTH
}
return NetworkType.UNKNOWN
} catch {
return NetworkType.NONE
}
}系统能力查询
判断设备类型
typescript
import { deviceInfo } from '@kit.BasicServicesKit'
enum DeviceType {
PHONE = 'phone',
TABLET = 'tablet',
TV = 'tv',
WATCH = 'watch',
CAR = 'car',
UNKNOWN = 'unknown'
}
function getDeviceType(): DeviceType {
const profile = deviceInfo.hardwareProfile
if (profile.includes('phone')) {
return DeviceType.PHONE
}
if (profile.includes('tablet')) {
return DeviceType.TABLET
}
if (profile.includes('tv')) {
return DeviceType.TV
}
if (profile.includes('watch')) {
return DeviceType.WATCH
}
if (profile.includes('car')) {
return DeviceType.CAR
}
return DeviceType.UNKNOWN
}
// 使用示例
const deviceType = getDeviceType()
console.info('设备类型:', deviceType)判断系统版本
typescript
import { deviceInfo } from '@kit.BasicServicesKit'
function isApiVersionAtLeast(version: number): boolean {
return deviceInfo.sdkApiVersion >= version
}
function isHarmonyOSNext(): boolean {
return deviceInfo.osFullName.includes('HarmonyOS NEXT')
}
// 使用示例
if (isApiVersionAtLeast(12)) {
console.info('支持 API 12+ 的新特性')
}
if (isHarmonyOSNext()) {
console.info('运行在 HarmonyOS NEXT 上')
}完整封装示例
typescript
import { deviceInfo } from '@kit.BasicServicesKit'
import { bundleManager } from '@kit.AbilityKit'
import { display } from '@kit.ArkUI'
import { batteryInfo } from '@kit.BasicServicesKit'
import { connection } from '@kit.NetworkKit'
interface DeviceFullInfo {
// 设备信息
brand: string
model: string
productSeries: string
osName: string
osVersion: string
sdkVersion: number
deviceType: string
// 应用信息
appName: string
appVersion: string
appVersionCode: number
// 屏幕信息
screenWidth: number
screenHeight: number
screenDensity: number
screenDPI: number
// 电池信息
batteryLevel: number
isCharging: boolean
batteryHealth: string
}
class DeviceManager {
private static instance: DeviceManager
static getInstance(): DeviceManager {
if (!DeviceManager.instance) {
DeviceManager.instance = new DeviceManager()
}
return DeviceManager.instance
}
// 获取完整设备信息
getDeviceInfo(): DeviceFullInfo {
const appInfo = bundleManager.getBundleInfoForSelfSync(
bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT
)
const displayInfo = display.getDefaultDisplaySync()
return {
brand: deviceInfo.brand,
model: deviceInfo.marketName,
productSeries: deviceInfo.productSeries,
osName: deviceInfo.osFullName,
osVersion: deviceInfo.displayVersion,
sdkVersion: deviceInfo.sdkApiVersion,
deviceType: deviceInfo.hardwareProfile,
appName: appInfo.name,
appVersion: appInfo.versionName,
appVersionCode: appInfo.versionCode,
screenWidth: displayInfo.width,
screenHeight: displayInfo.height,
screenDensity: displayInfo.densityPixels,
screenDPI: displayInfo.densityDPI,
batteryLevel: batteryInfo.batterySOC,
isCharging: batteryInfo.chargingStatus === batteryInfo.ChargingState.CHARGING_STATE_ENABLE,
batteryHealth: this.getBatteryHealthText(batteryInfo.healthStatus)
}
}
// 获取设备类型
getDeviceType(): string {
const profile = deviceInfo.hardwareProfile
if (profile.includes('phone')) return 'phone'
if (profile.includes('tablet')) return 'tablet'
if (profile.includes('tv')) return 'tv'
if (profile.includes('watch')) return 'watch'
if (profile.includes('car')) return 'car'
return 'unknown'
}
// 判断是否为手机
isPhone(): boolean {
return this.getDeviceType() === 'phone'
}
// 判断是否为平板
isTablet(): boolean {
return this.getDeviceType() === 'tablet'
}
// 判断是否为手表
isWatch(): boolean {
return this.getDeviceType() === 'watch'
}
// 判断 API 版本
isApiVersionAtLeast(version: number): boolean {
return deviceInfo.sdkApiVersion >= version
}
// 获取网络类型
getNetworkType(): string {
try {
const netHandle = connection.getDefaultNetSync()
if (netHandle.netId === 0) {
return 'none'
}
const capabilities = connection.getNetCapabilitiesSync(netHandle)
const bearerTypes = capabilities.bearerTypes
if (bearerTypes.includes(connection.NetBearType.BEARER_WIFI)) {
return 'wifi'
}
if (bearerTypes.includes(connection.NetBearType.BEARER_CELLULAR)) {
return 'cellular'
}
if (bearerTypes.includes(connection.NetBearType.BEARER_ETHERNET)) {
return 'ethernet'
}
return 'unknown'
} catch {
return 'none'
}
}
// 是否有网络连接
isNetworkAvailable(): boolean {
return this.getNetworkType() !== 'none'
}
// 是否使用 WiFi
isWifiConnected(): boolean {
return this.getNetworkType() === 'wifi'
}
// 获取电池健康状态文本
private getBatteryHealthText(health: batteryInfo.BatteryHealth): string {
switch (health) {
case batteryInfo.BatteryHealth.BATTERY_HEALTH_GOOD:
return '良好'
case batteryInfo.BatteryHealth.BATTERY_HEALTH_OVERHEAT:
return '过热'
case batteryInfo.BatteryHealth.BATTERY_HEALTH_OVERVOLTAGE:
return '过压'
case batteryInfo.BatteryHealth.BATTERY_HEALTH_COLD:
return '过冷'
case batteryInfo.BatteryHealth.BATTERY_HEALTH_DEAD:
return '损坏'
default:
return '未知'
}
}
}
export const deviceManager = DeviceManager.getInstance()设备信息展示页面
typescript
import { deviceManager } from '../utils/DeviceManager'
@Entry
@Component
struct DeviceInfoPage {
@State deviceInfo: DeviceFullInfo | null = null
aboutToAppear() {
this.deviceInfo = deviceManager.getDeviceInfo()
}
build() {
Column() {
Text('设备信息')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
if (this.deviceInfo) {
List() {
ListItem() { InfoSection('设备', [
{ label: '品牌', value: this.deviceInfo.brand },
{ label: '型号', value: this.deviceInfo.model },
{ label: '类型', value: this.deviceInfo.deviceType },
{ label: '系列', value: this.deviceInfo.productSeries }
]) }
ListItem() { InfoSection('系统', [
{ label: '系统名称', value: this.deviceInfo.osName },
{ label: '系统版本', value: this.deviceInfo.osVersion },
{ label: 'SDK 版本', value: this.deviceInfo.sdkVersion.toString() }
]) }
ListItem() { InfoSection('应用', [
{ label: '应用名称', value: this.deviceInfo.appName },
{ label: '应用版本', value: this.deviceInfo.appVersion },
{ label: '版本号', value: this.deviceInfo.appVersionCode.toString() }
]) }
ListItem() { InfoSection('屏幕', [
{ label: '宽度', value: `${this.deviceInfo.screenWidth}px` },
{ label: '高度', value: `${this.deviceInfo.screenHeight}px` },
{ label: '密度', value: this.deviceInfo.screenDensity.toFixed(2) },
{ label: 'DPI', value: this.deviceInfo.screenDPI.toString() }
]) }
ListItem() { InfoSection('电池', [
{ label: '电量', value: `${this.deviceInfo.batteryLevel}%` },
{ label: '充电状态', value: this.deviceInfo.isCharging ? '充电中' : '未充电' },
{ label: '健康状态', value: this.deviceInfo.batteryHealth }
]) }
ListItem() { InfoSection('网络', [
{ label: '网络类型', value: deviceManager.getNetworkType() },
{ label: '网络可用', value: deviceManager.isNetworkAvailable() ? '是' : '否' }
]) }
}
.width('100%')
.layoutWeight(1)
}
}
.width('100%')
.height('100%')
.padding(16)
}
}
interface InfoItem {
label: string
value: string
}
@Component
struct InfoSection {
@Prop title: string = ''
@Prop items: InfoItem[] = []
build() {
Column({ space: 8 }) {
Text(this.title)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.fontColor('#1890ff')
Column({ space: 4 }) {
ForEach(this.items, (item: InfoItem) => {
Row() {
Text(item.label)
.fontSize(14)
.fontColor('#666')
.width(80)
Text(item.value)
.fontSize(14)
.layoutWeight(1)
}
.width('100%')
.height(32)
})
}
}
.width('100%')
.padding(12)
.backgroundColor('#f5f5f5')
.borderRadius(8)
.margin({ bottom: 12 })
}
}最佳实践
- 设备适配:根据设备类型(phone/tablet/watch)调整 UI 布局和功能
- 版本兼容:使用
sdkApiVersion判断 API 可用性,做好版本兼容 - 权限注意:获取设备序列号、UDID 等敏感信息需要特殊权限
- 性能考虑:设备信息一般不会变化,可以缓存避免重复获取
- 隐私合规:收集设备信息需遵守隐私政策,明确告知用户用途
- 网络判断:执行网络操作前检查网络状态,提供离线提示
- 电量优化:低电量时减少后台任务和动画效果