
鸿蒙操作系统(HarmonyOS)是华为开发的全场景分布式操作系统,旨在为不同设备提供统一的用户体验。它采用微内核设计,支持多设备协同工作,具有以下 核心特点:
# 从华为开发者官网下载
https://developer.harmonyos.com/cn/develop/deveco-studio# 安装Node.js(推荐16.x版本)
npm install -g @ohos/hvigor-cli
# 配置SDK
# 在DevEco Studio中配置HarmonyOS SDK路径// 项目配置文件 - build-profile.json5
{
"app": {
"signingConfigs": [],
"products": [
{
"name": "default",
"signingConfig": "default",
"compatibleSdkVersion": "4.0.0(10)",
"runtimeOS": "HarmonyOS"
}
],
"buildModeSet": [
{
"name": "debug"
},
{
"name": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}ArkTS是TypeScript的超集,提供了鸿蒙应用开发所需的特性:
// 基础组件示例
@Entry
@Component
struct HelloPage {
@State message: string = 'Hello HarmonyOS!'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.margin({ top: 20 })
Button('点击我')
.onClick(() => {
this.message = '欢迎学习鸿蒙开发!'
})
.margin({ top: 20 })
}
.width('100%')
}
.height('100%')
.backgroundColor('#f0f0f0')
}
}@Component
struct CounterComponent {
@State count: number = 0
@Prop title: string = '计数器'
build() {
Column() {
Text(`${this.title}: ${this.count}`)
.fontSize(24)
Row() {
Button('-')
.onClick(() => this.count--)
Button('+')
.onClick(() => this.count++)
}
.margin({ top: 10 })
}
}
}@Entry
@Component
struct LifecyclePage {
aboutToAppear() {
console.log('页面即将出现')
// 初始化操作
}
aboutToDisappear() {
console.log('页面即将消失')
// 清理资源
}
onPageShow() {
console.log('页面显示')
}
onPageHide() {
console.log('页面隐藏')
}
build() {
// 页面布局
}
}@Entry
@Component
struct LayoutDemo {
build() {
Column() {
// Flex布局
Flex({ direction: FlexDirection.Row, wrap: FlexWrap.Wrap }) {
Text('项目1')
.backgroundColor('#ff0000')
.width(100)
.height(50)
Text('项目2')
.backgroundColor('#00ff00')
.width(100)
.height(50)
Text('项目3')
.backgroundColor('#0000ff')
.width(100)
.height(50)
}
.padding(10)
// Grid布局
Grid() {
ForEach([1, 2, 3, 4, 5, 6], (item) => {
GridItem() {
Text(`项目${item}`)
.backgroundColor('#e0e0e0')
.width('100%')
.height('100%')
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.rowsTemplate('1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.width('100%')
.height(200)
}
}
}@Entry
@Component
struct ListDemo {
@State data: string[] = [
'苹果', '香蕉', '橙子', '葡萄', '草莓',
'芒果', '猕猴桃', '西瓜', '菠萝', '樱桃'
]
build() {
Column() {
List({ space: 10 }) {
ForEach(this.data, (item: string, index: number) => {
ListItem() {
Row() {
Text(`${index + 1}. ${item}`)
.fontSize(16)
Blank()
Button('删除')
.onClick(() => {
this.data.splice(index, 1)
})
}
.width('100%')
.padding(15)
.backgroundColor('#ffffff')
.borderRadius(8)
.shadow({ radius: 4, color: '#cccccc' })
}
})
}
.width('90%')
.layoutWeight(1)
}
.width('100%')
.height('100%')
.backgroundColor('#f5f5f5')
}
}@Entry
@Component
struct NavigationDemo {
@State currentIndex: number = 0
build() {
Tabs({ barPosition: BarPosition.End }) {
TabContent() {
Column() {
Text('首页')
.fontSize(24)
.margin({ top: 50 })
}
}
.tabBar('首页')
TabContent() {
Column() {
Text('发现')
.fontSize(24)
.margin({ top: 50 })
}
}
.tabBar('发现')
TabContent() {
Column() {
Text('我的')
.fontSize(24)
.margin({ top: 50 })
}
}
.tabBar('我的')
}
.onChange((index: number) => {
this.currentIndex = index
})
}
}import dataStorage from '@ohos.data.storage'
@Component
struct StorageDemo {
@State savedText: string = ''
async saveData() {
const storage = await dataStorage.getStorage('user_preferences')
await storage.putSync('user_name', this.savedText)
await storage.flushSync()
}
async loadData() {
const storage = await dataStorage.getStorage('user_preferences')
this.savedText = storage.getSync('user_name', '默认值')
}
build() {
Column() {
TextInput({ placeholder: '输入要保存的内容' })
.onChange((value: string) => {
this.savedText = value
})
.margin({ bottom: 10 })
Row() {
Button('保存')
.onClick(() => this.saveData())
Button('读取')
.onClick(() => this.loadData())
}
Text(`已保存: ${this.savedText}`)
.margin({ top: 20 })
}
.padding(20)
}
}import http from '@ohos.net.http'
@Component
struct NetworkDemo {
@State response: string = ''
@State loading: boolean = false
async makeRequest() {
this.loading = true
try {
const httpRequest = http.createHttp()
const result = await httpRequest.request(
'https://api.example.com/data',
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
}
}
)
this.response = result.result.toString()
} catch (error) {
this.response = `请求失败: ${error.message}`
} finally {
this.loading = false
}
}
build() {
Column() {
Button('发起网络请求')
.onClick(() => this.makeRequest())
.enabled(!this.loading)
if (this.loading) {
LoadingProgress()
.width(50)
.height(50)
.margin({ top: 20 })
}
Text(this.response)
.fontSize(14)
.margin({ top: 20 })
.maxLines(10)
}
.padding(20)
}
}import camera from '@ohos.multimedia.camera'
@Component
struct CameraDemo {
@State imageUri: string = ''
async capturePhoto() {
try {
const cameraManager = camera.getCameraManager()
const cameras = await cameraManager.getSupportedCameras()
if (cameras.length > 0) {
const cameraInput = cameraManager.createCameraInput(cameras[0])
await cameraInput.open()
// 拍照逻辑
// this.imageUri = photoUri
}
} catch (error) {
console.error('相机操作失败:', error)
}
}
build() {
Column() {
if (this.imageUri) {
Image(this.imageUri)
.width(300)
.height(200)
.objectFit(ImageFit.Cover)
.margin({ bottom: 20 })
} else {
Divider()
.width(300)
.height(200)
.margin({ bottom: 20 })
}
Button('拍照')
.onClick(() => this.capturePhoto())
}
}
}import geolocation from '@ohos.geolocation'
@Component
struct LocationDemo {
@State location: string = '未获取位置'
@State latitude: number = 0
@State longitude: number = 0
async getCurrentLocation() {
try {
const requestInfo = {
'priority': 1,
'timeout': 30000
}
const locationInfo = await geolocation.getCurrentLocation(requestInfo)
this.latitude = locationInfo.latitude
this.longitude = locationInfo.longitude
this.location = `纬度: ${this.latitude}, 经度: ${this.longitude}`
} catch (error) {
this.location = `获取位置失败: ${error.message}`
}
}
build() {
Column() {
Text('位置信息')
.fontSize(18)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
Text(this.location)
.fontSize(14)
.margin({ bottom: 20 })
Button('获取当前位置')
.onClick(() => this.getCurrentLocation())
}
.padding(20)
}
}import distributedData from '@ohos.data.distributedData'
@Component
struct DistributedDataDemo {
@State sharedData: string = ''
@State deviceList: string[] = []
async createDistributedData() {
const kvManager = distributedData.createKVManager({
context: getContext(),
userId: 'default',
bundleName: 'com.example.app'
})
const kvStore = await kvManager.getKVStore('distributed_store', {
createIfMissing: true
})
// 保存数据到分布式存储
await kvStore.put('shared_key', '共享数据')
// 监听数据变化
kvStore.on('dataChange', (data) => {
this.sharedData = data.shared_key
})
}
async getConnectedDevices() {
const deviceManager = distributedData.createDeviceManager('com.example.app')
const devices = await deviceManager.getTrustedDeviceList()
this.deviceList = devices.map(device => device.deviceName)
}
build() {
Column() {
Text('分布式数据管理')
.fontSize(18)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
Text(`共享数据: ${this.sharedData}`)
.fontSize(14)
.margin({ bottom: 10 })
Text('已连接设备:')
.fontSize(14)
.margin({ top: 20, bottom: 10 })
ForEach(this.deviceList, (device: string) => {
Text(device)
.fontSize(12)
.margin({ bottom: 5 })
})
Row() {
Button('创建分布式存储')
.onClick(() => this.createDistributedData())
Button('获取设备列表')
.onClick(() => this.getConnectedDevices())
}
.margin({ top: 20 })
}
.padding(20)
}
}@Component
struct LazyLoadingDemo {
@State loadedItems: number[] = []
private totalCount: number = 1000
loadMoreItems() {
const currentLength = this.loadedItems.length
const newItems = []
for (let i = currentLength; i < Math.min(currentLength + 20, this.totalCount); i++) {
newItems.push(i)
}
this.loadedItems = [...this.loadedItems, ...newItems]
}
build() {
Column() {
List() {
ForEach(this.loadedItems, (item: number) => {
ListItem() {
ItemComponent({ item: item })
}
})
}
.width('100%')
.height('80%')
.onScrollEnd(() => {
if (this.loadedItems.length < this.totalCount) {
this.loadMoreItems()
}
})
if (this.loadedItems.length >= this.totalCount) {
Text('已加载全部内容')
.fontSize(14)
.margin({ top: 10 })
}
}
}
aboutToAppear() {
this.loadMoreItems()
}
}
@Component
struct ItemComponent {
@Prop item: number
build() {
Row() {
Text(`项目 ${this.item}`)
.fontSize(16)
}
.width('100%')
.height(60)
.backgroundColor('#ffffff')
.margin({ bottom: 1 })
.padding({ left: 15, right: 15 })
}
}@Component
struct MemoryManagementDemo {
@State images: string[] = []
private imageCache: Map<string, ImageBitmap> = new Map()
// 清理缓存
clearCache() {
this.imageCache.clear()
}
// 加载图片
loadImage(url: string) {
if (!this.imageCache.has(url)) {
// 异步加载图片并缓存
// this.imageCache.set(url, loadedImage)
}
return this.imageCache.get(url)
}
aboutToDisappear() {
// 组件销毁时清理资源
this.clearCache()
}
build() {
Column() {
Text('内存管理示例')
.fontSize(18)
.margin({ bottom: 20 })
Button('清理缓存')
.onClick(() => this.clearCache())
.margin({ bottom: 20 })
Text(`缓存图片数量: ${this.imageCache.size}`)
.fontSize(14)
}
}
}// 测试文件 - calculator.test.ts
import { describe, expect, it } from '@ohos/hypium'
export default function testsuite() {
describe('Calculator Tests', () => {
it('should add two numbers correctly', () => {
const calculator = new Calculator()
const result = calculator.add(2, 3)
expect(result).assertEqual(5)
})
it('should handle division by zero', () => {
const calculator = new Calculator()
expect(() => calculator.divide(5, 0)).assertThrows(Error)
})
})
}
// 被测试的类
export class Calculator {
add(a: number, b: number): number {
return a + b
}
divide(a: number, b: number): number {
if (b === 0) {
throw new Error('Division by zero')
}
return a / b
}
}@Component
struct PerformanceDemo {
@State renderTime: number = 0
build() {
Column() {
Text(`渲染时间: ${this.renderTime}ms`)
.fontSize(14)
.margin({ bottom: 20 })
Button('性能测试')
.onClick(() => this.measurePerformance())
}
.padding(20)
}
measurePerformance() {
const startTime = Date.now()
// 模拟复杂操作
this.complexCalculation()
const endTime = Date.now()
this.renderTime = endTime - startTime
}
complexCalculation() {
let result = 0
for (let i = 0; i < 1000000; i++) {
result += Math.sqrt(i)
}
return result
}
}// 签名配置 - signing-configs.json
{
"app": {
"signingConfigs": [
{
"name": "default",
"type": "HarmonyOS",
"material": {
"certpath": "path/to/certificate.cer",
"storePassword": "your_store_password",
"keyAlias": "your_key_alias",
"keyPassword": "your_key_password",
"profile": "path/to/profile.p7b",
"signAlg": "SHA256withECDSA"
}
}
]
}
}// build-profile.json5
{
"app": {
"products": [
{
"name": "default",
"signingConfig": "default",
"compileSdkVersion": 9,
"compatibleSdkVersion": 9,
"runtimeOS": "HarmonyOS",
"buildMode": "release"
}
]
},
"modules": [
{
"name": "entry",
"srcPath": "./entry",
"targets": [
{
"name": "default",
"applyToProducts": [
"default"
]
}
]
}
]
}// 使用TypeScript类型注解
interface User {
id: number
name: string
email: string
}
// 使用枚举定义常量
enum Theme {
LIGHT = 'light',
DARK = 'dark',
AUTO = 'auto'
}
// 组件命名规范
@Component
export struct UserProfile {
@Prop user: User
build() {
// 使用语义化的变量名
const userAvatar = this.user.avatar
const userName = this.user.name
Row() {
Image(userAvatar)
.width(50)
.height(50)
.borderRadius(25)
Column() {
Text(userName)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Text(this.user.email)
.fontSize(12)
.fontColor('#666666')
}
.alignItems(HorizontalAlign.Start)
.margin({ left: 10 })
}
.padding(15)
}
}@Component
struct ErrorHandlingDemo {
@State errorMessage: string = ''
async handleAsyncOperation() {
try {
const result = await this.asyncFunction()
console.log('操作成功:', result)
} catch (error) {
this.errorMessage = `操作失败: ${error.message}`
console.error('异步操作错误:', error)
}
}
asyncFunction(): Promise<string> {
return new Promise((resolve, reject) => {
// 模拟异步操作
setTimeout(() => {
if (Math.random() > 0.5) {
resolve('成功')
} else {
reject(new Error('网络超时'))
}
}, 1000)
})
}
build() {
Column() {
if (this.errorMessage) {
Text(this.errorMessage)
.fontSize(14)
.fontColor('#ff0000')
.margin({ bottom: 20 })
}
Button('执行异步操作')
.onClick(() => this.handleAsyncOperation())
}
.padding(20)
}
}鸿蒙OS开发提供了强大的跨平台能力和丰富的开发工具。通过学习本指南,你应该能够:
鸿蒙OS生态系统正在快速发展,持续关注官方更新和社区动态,不断学习新技术,将帮助你在鸿蒙开发领域取得成功。