HarmonyOS APP开发入门指南详细解说

HarmonyOS是华为推出的分布式操作系统,支持多种设备类型。开发HarmonyOS APP需要掌握基础概念和工具链,以下从环境搭建到代码实现逐步解析。

开发环境配置

安装DevEco Studio,官方推荐的集成开发环境。下载地址为华为开发者联盟官网,支持Windows和macOS。安装完成后配置SDK路径,确保包含HarmonyOS最新版本的开发工具包。

配置Node.js环境,HarmonyOS应用开发依赖JS/TS语言支持。建议安装LTS版本的Node.js,通过命令行验证安装是否成功:

node -v
npm -v

创建新项目时选择"Application"模板,设备类型选择"Phone"。项目结构包含关键目录:

  • entry/src/main:主代码目录
  • resources:资源文件存放处
  • config.json:应用配置文件
基础UI开发

Ability是HarmonyOS应用的基本组成单元,UIAbility包含界面元素。以下示例展示页面布局定义,在resources/base/layout中创建XML文件:

<DirectionalLayout
    xmlns:ohos="http://schemas.huawei.com/res/ohos"
    ohos:width="match_parent"
    ohos:height="match_parent"
    ohos:orientation="vertical">

    <Text
        ohos:id="$+id:text_hello"
        ohos:width="match_content"
        ohos:height="match_content"
        ohos:text="Hello HarmonyOS"
        ohos:text_size="40vp"/>
</DirectionalLayout>

在JS/TS中通过代码控制UI元素,创建entry/src/main/ets/pages/index.ets

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Column() {
      Text(this.message)
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
      
      Button('Click Me')
        .onClick(() => {
          this.message = 'Button Clicked!'
        })
    }
    .width('100%')
    .height('100%')
  }
}

页面导航实现

使用页面路由管理导航,需要在config.json中声明路由信息:

"pages": [
  "pages/Index",
  "pages/Second"
]

添加按钮跳转逻辑:

import router from '@ohos.router'

Button('Go to Second')
  .onClick(() => {
    router.push({
      url: 'pages/Second'
    })
  })

目标页面需要添加返回功能:

Button('Back')
  .onClick(() => {
    router.back()
  })

数据持久化存储

使用轻量级存储实现数据持久化,在entry/src/main/ets/pages中创建数据处理文件:

import dataStorage from '@ohos.data.storage'

let storage = dataStorage.getStorageSync('/data/storage/el2/base')

// 存储数据
function saveData(key: string, value: string) {
  storage.putSync(key, value)
  storage.flushSync()
}

// 读取数据
function loadData(key: string): string {
  return storage.getSync(key, 'default')
}

在UI中调用存储方法:

@State storedValue: string = ''

Button('Save Data')
  .onClick(() => {
    saveData('sample_key', 'test_value')
    this.storedValue = loadData('sample_key')
  })

网络请求示例

配置网络权限后实现HTTP请求,修改config.json

"reqPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

实现GET请求:

import http from '@ohos.net.http'

let httpRequest = http.createHttp()
httpRequest.request(
  "https://api.example.com/data",
  {
    method: 'GET',
    header: {
      'Content-Type': 'application/json'
    }
  }, (err, data) => {
    if (!err) {
      console.log(JSON.stringify(data.result))
    } else {
      console.error(JSON.stringify(err))
    }
  }
)

设备能力调用

访问设备传感器需要声明权限,以获取地理位置为例:

"reqPermissions": [
  {
    "name": "ohos.permission.LOCATION"
  }
]

实现定位功能:

import geolocation from '@ohos.geolocation'

function getLocation() {
  geolocation.getCurrentLocation(
    { priority: geolocation.LocationPriority.HIGH_ACCURACY },
    (err, data) => {
      if (err) {
        console.error('location error: ' + JSON.stringify(err))
      } else {
        console.log('location: ' + JSON.stringify(data))
      }
    }
  )
}

调试与发布

使用DevEco Studio的调试功能,连接真机或模拟器运行应用。在File > Project Structure中配置签名信息,生成发布证书。构建APK时选择Build > Generate Key and CSR创建密钥文件。

通过华为应用市场发布流程需要:

  1. 注册开发者账号
  2. 提交应用审核
  3. 配置应用元数据
  4. 上传签名后的HAP包
常见问题解决

UI不更新时检查@State装饰器是否正确使用。网络请求失败时验证权限声明和URL有效性。存储数据异常时确认路径权限。设备功能调用需确保在真机测试,部分模拟器可能不支持特定硬件功能。

通过以上步骤可完成基础HarmonyOS应用开发。实际项目中需结合具体需求扩展功能模块,官方文档提供完整的API参考和示例代码库。分布式能力开发需要进一步学习设备协同和任务迁移相关接口。

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐