HarmonyOS鸿蒙Next中如何在 uni-app 中判断当前运行环境是否为鸿蒙?
HarmonyOS鸿蒙Next中如何在 uni-app 中判断当前运行环境是否为鸿蒙? 在 uni-app 中判断运行环境可以使用条件编译、系统信息 API 等方式,本文介绍多种判断方法及其适用场景。
更多关于HarmonyOS鸿蒙Next中如何在 uni-app 中判断当前运行环境是否为鸿蒙?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
方法一:条件编译(推荐)
// #ifdef APP-HARMONY
console.log('当前是鸿蒙环境')
// 鸿蒙专属代码
// #endif
// #ifndef APP-HARMONY
console.log('非鸿蒙环境')
// #endif
方法二:运行时判断
// 通过系统信息判断
const systemInfo = uni.getSystemInfoSync()
// 判断是否鸿蒙
const isHarmony = systemInfo.osName === ‘harmonyos’ ||
systemInfo.platform === ‘harmony’ ||
(systemInfo.system && systemInfo.system.toLowerCase().includes(‘harmony’))
console.log(‘是否鸿蒙:’, isHarmony)
方法三:封装工具函数
// utils/platform.js
export function isHarmonyOS() { // #ifdef APP-HARMONY return true // #endif
// #ifndef APP-HARMONY
try {
const sys = uni.getSystemInfoSync()
return sys.osName === 'harmonyos' ||
(sys.system || '').toLowerCase().includes('harmony')
} catch (e) {
return false
}
// #endif
}
// 使用
import { isHarmonyOS } from ‘@/utils/platform.js’
if (isHarmonyOS()) { // 鸿蒙特定逻辑 }
养生源项目中的应用
你的 App.vue 已经有平台判断逻辑:
// App.vue
initSystemInfo() {
const systemInfo = uni.getSystemInfoSync()
console.log('[App] 平台:', systemInfo.platform, '系统:', systemInfo.system)
// 可以加上鸿蒙判断
const isHarmony = systemInfo.system?.toLowerCase().includes('harmony')
if (isHarmony) {
console.log('[App] 运行在鸿蒙系统')
}
}
通知模块也可以加上鸿蒙适配:
// utils/notification.js
// #ifdef APP-HARMONY
// 鸿蒙专属通知API
// #endif
// #ifdef APP-PLUS
// 其他平台通知API
// #endif
在uni-app中判断当前运行环境是否为鸿蒙,可以使用uni.getSystemInfoSync()获取系统信息。通过检查platform字段或osName字段的值。若platform为’harmony’或osName包含’HarmonyOS’,即可判定为鸿蒙环境。
在HarmonyOS Next中,uni-app项目判断当前运行环境是否为鸿蒙,核心方法是使用条件编译和系统信息API。
1. 条件编译(推荐)
在代码中使用 #ifdef HARMONY 或 #ifdef APP-HARMONY 进行平台判断:
// 页面逻辑判断
#ifdef HARMONY
console.log('当前运行在鸿蒙平台');
// 执行鸿蒙专用代码
#endif
// API调用判断
#ifdef APP-HARMONY
const systemInfo = uni.getSystemInfoSync();
#endif
2. 运行时环境判断
通过 uni.getSystemInfoSync() 获取平台信息:
const systemInfo = uni.getSystemInfoSync();
if (systemInfo.platform === 'harmony') {
// 鸿蒙平台特定逻辑
}
3. 编译时环境变量
在 package.json 中配置条件编译:
{
"uni-app": {
"scripts": {
"harmony": {
"title": "鸿蒙版",
"env": {
"UNI_PLATFORM": "app-harmony"
}
}
}
}
}
4. 多端兼容写法
// 通用判断函数
export function isHarmony() {
#ifdef APP-HARMONY
return true;
#endif
#ifndef APP-HARMONY
return false;
#endif
}
// 使用示例
if (isHarmony()) {
// 鸿蒙专有功能
}
注意事项:
- 条件编译在编译阶段生效,鸿蒙平台的代码不会打包到其他平台
- 运行时判断适用于需要动态适配的场景
- 鸿蒙Next环境下,部分API可能与Android/iOS存在差异,建议结合条件编译使用
- 使用
uni-app 3.9.0+版本对鸿蒙Next支持更完善
这些方法可根据实际开发需求选择使用,条件编译能减少包体积,运行时判断更灵活。

