从零构建 OpenHarmony 5.0 跨设备桌面应用:一位开源开发者的完整实战手册
从零构建 OpenHarmony 5.0 跨设备桌面应用:一位开源开发者的完整实战手册
从零构建 OpenHarmony 5.0 跨设备桌面应用:一位开源开发者的完整实战手册
引言:为什么选择 OpenHarmony 做桌面应用?
随着 OpenHarmony 5.0 正式发布,其对 x86_64 架构 PC 设备的支持已进入稳定阶段。社区涌现出如 Raspberry Pi 4B + 显示器、国产 x86 笔记本、ARM 平板 等多种可运行 OpenHarmony 的硬件平台。
作为开源开发者,我们不再需要等待厂商适配,而是可以:
- 自行编译 OpenHarmony 镜像
- 在标准 PC 模拟器或真机上运行
- 开发真正跨设备的原生应用
本文将带你从 环境搭建 → 项目创建 → 功能实现 → 多端适配 → 编译分发 全流程,打造一个名为 “OH Note” 的 Markdown 笔记应用,并确保它在 PC、平板、大屏设备 上均有良好体验。
✅ 所有代码、配置、命令均基于 OpenHarmony 5.0 LTS(API Version 10)
✅ 不使用任何华为 HMS Core、AppGallery 或闭源服务
一、开发环境准备:纯开源工具链
1.1 系统要求
- 操作系统:Ubuntu 22.04 LTS(推荐)
- 内存:≥16GB
- 磁盘:≥200GB(用于源码编译)
1.2 安装 DevEco Studio for OpenHarmony
⚠️ 注意:必须使用 OpenHarmony 定制版 DevEco Studio,而非华为官网版本。
下载地址:
https://gitee.com/openharmony/applications_app_samples/blob/master/zh-cn/device-dev/quick-start/Deveco-Studio-for-OpenHarmony.md
安装后,在 Settings > SDK Manager 中选择:
- OpenHarmony SDK API 10
- Toolchains: ohos-sdk-full
1.3 配置本地模拟器(可选)
OpenHarmony 提供 PC 模拟器镜像(x86_64):
# 下载模拟器镜像(来自 OpenHarmony 官方 CI)
wget https://ci.openharmony.cn/artifacts/.../pc_x86_64.img
# 启动 QEMU(需安装 qemu-system-x86)
qemu-system-x86_64 \
-m 4096 \
-smp 4 \
-drive file=pc_x86_64.img,format=raw \
-netdev user,id=net0 -device e1000,netdev=net0
💡 更简单方式:在 DevEco 中直接选择 “Local Emulator (PC)” 运行。
二、创建 OpenHarmony 应用项目
2.1 新建工程
在 DevEco Studio 中:
- 选择 File > New > Create Project
- 模板:Application > Empty Ability (Stage)
- 设备类型:勾选 PC、Tablet、Smart Vision
- 语言:ArkTS
- SDK:OpenHarmony API 10
项目结构如下:
oh-note/
├── entry/
│ ├── src/
│ │ └── main/
│ │ ├── ets/
│ │ │ ├── MainAbility.ts
│ │ │ └── pages/
│ │ │ └── EditorPage.ets
│ │ └── resources/
│ └── oh-package.json5
├── build-profile.json5
└── hvigorfile.ts
2.2 验证项目可运行
点击 Run > Run ‘entry’,若模拟器弹出空白页面,说明环境配置成功。
三、核心功能开发:Markdown 编辑器
3.1 编辑区实现
使用 TextArea 组件(OpenHarmony 标准组件):
// pages/EditorPage.ets
@Entry
@Component
struct EditorPage {
@State content: string = '# Welcome to OH Note\nWrite your note here...';
build() {
Column() {
TextArea({
placeholder: 'Start typing...',
text: this.content
})
.onChange((value) => {
this.content = value;
})
.width('100%')
.height('100%')
.fontFamily('Monospace')
}
.width('100%')
.height('100%')
.padding(10)
}
}
3.2 实时预览(无 WebView)
OpenHarmony 的 RichText 支持基础 HTML,我们编写简易 Markdown 解析器:
// utils/mdParser.ts
export function parseMarkdown(md: string): string {
return md
.replace(/\*\*(.*?)\*\*/g, '<b>$1</b>')
.replace(/`(.*?)`/g, '<code style="background:#f0f0f0;padding:2px;border-radius:3px;">$1</code>')
.replace(/^(#{1,3})\s+(.*)$/gm, (_, hashes, title) => {
const level = hashes.length;
return `<h${level}>${title}</h${level}>`;
})
.replace(/\n/g, '<br>');
}
预览组件:
// components/PreviewPane.ets
import { parseMarkdown } from '../utils/mdParser';
@Component
export struct PreviewPane {
private raw: string = '';
build() {
Scroll() {
RichText({ text: parseMarkdown(this.raw) })
.width('100%')
}
.width('100%')
.height('100%')
}
update(content: string) {
this.raw = content;
}
}
3.3 双栏布局(PC 专属)
利用 OpenHarmony 的 响应式布局能力:
// EditorPage.ets(增强版)
private previewRef: PreviewPane = new PreviewPane();
build() {
// 判断是否为宽屏设备(PC)
if (windowClass.window.width() > 1000) {
Row() {
TextArea({ text: this.content })
.onChange(v => {
this.content = v;
this.previewRef.update(v);
})
.width('50%')
this.previewRef
.width('50%')
}
} else {
// 平板/手机:单栏切换
Column() {
if (this.showEditor) {
TextArea({ text: this.content })
.onChange(v => this.content = v)
} else {
this.previewRef
}
ToggleButton()
}
}
}
📏 使用
windowClass.window.width()获取屏幕宽度,实现自适应。
四、文件系统集成:使用 OpenHarmony 标准 API
4.1 保存到应用沙箱
OpenHarmony 提供 @ohos.file.fs(开源标准模块):
// services/fileService.ts
import fs from '@ohos.file.fs';
import context from '@ohos.app.ability.UIAbilityContext';
export async function saveNote(ctx: UIAbilityContext, content: string, name: string): Promise<boolean> {
try {
const path = `${ctx.cacheDir}/notes/${name}.md`;
await fs.mkdir(`${ctx.cacheDir}/notes`, true);
await fs.writeFile(path, content, { encoding: 'utf-8' });
return true;
} catch (err) {
console.error('Save failed:', err);
return false;
}
}
🔒 所有文件操作均在应用沙箱内,符合 OpenHarmony 安全规范。
4.2 读取已有笔记
export async function listNotes(ctx: UIAbilityContext): Promise<string[]> {
const dir = `${ctx.cacheDir}/notes`;
const files = await fs.readDir(dir);
return files.map(f => f.name.replace('.md', ''));
}
五、多设备适配:一套代码,三种体验
OpenHarmony 的 deviceType 能力可精准识别设备类型:
import deviceInfo from '@ohos.deviceInfo';
build() {
const device = deviceInfo.deviceType;
if (device === '2-in-1') {
// PC 模式:双栏
} else if (device === 'tablet') {
// 平板:横屏双栏,竖屏单栏
} else if (device === 'smartVision') {
// 智慧屏:大字体、语音控制入口
}
}
📱 设备类型常量定义见:
@ohos.deviceInfo.DeviceType
六、编译与分发:生成 HAP 包
6.1 构建命令
在项目根目录执行:
# 安装 ohpm 依赖
ohpm install
# 构建 debug 包
hvigorw assembleHap --mode debug
输出路径:./entry/build/default/outputs/default/entry-default-signed.hap
6.2 安装到真机或模拟器
# 连接设备(通过 hdc)
hdc install entry-default-signed.hap
📦 此 HAP 包可在任何运行 OpenHarmony 5.0 的设备上安装,无需签名认证(开发模式)。
七、开源生态支持:依赖管理与扩展
7.1 使用 ohpm 安装社区库
例如,使用 @ohos/markdown(假设存在):
ohpm install @ohos/markdown
但目前多数功能需自行实现,建议:
- 将通用组件提交到 OpenHarmony Samples 仓库
- 参与 SIG UI 或 SIG Application 社区
7.2 贡献你的应用
将 “OH Note” 开源:
git init
git remote add origin https://gitee.com/yourname/oh-note.git
git push -u origin main
并申请加入 OpenHarmony App Gallery(社区版)。
八、性能与安全:OpenHarmony 原生优势
| 维度 | 优势 |
|---|---|
| 启动速度 | AOT 编译,冷启动 < 1s |
| 内存占用 | 纯 ArkUI,无 Chromium 开销 |
| 安全性 | 沙箱隔离、权限最小化 |
| 跨设备 | 分布式软总线(需设备在同一网络) |
🔐 所有 API 均来自 OpenHarmony 开源代码,无后门风险。
结语:开源鸿蒙,属于每一位开发者
通过这个实战项目,我们可以看到:
OpenHarmony 不是一个“华为的操作系统”,而是一个由全球开发者共建的开源分布式操作系统。
你不需要是大厂工程师,只需一台普通 PC,就能:
- 编译系统镜像
- 开发跨设备应用
- 贡献代码到社区
这,才是开源的真正魅力。
附录:常用命令速查
# 初始化 OpenHarmony 项目
deveco new-project --template empty-stage --api 10
# 查看设备列表
hdc list targets
# 查看日志
hilog | grep "OHNote"
# 清理构建缓存
hvigorw clean
更多推荐



所有评论(0)