AI 摘要

文章聚焦 HarmonyOS 4.0 应用开发核心技能:先讲解 ATM 权限模型,区分 system_grant 与 user_grant,演示在 module.json5 中声明网络权限;随后用 @ohos.net.http 实现一键发请求并刷新 UI;接着详解 router.pushUrl、replaceUrl、back 及参数传递,完成页面间导航;最后梳理 UIAbility 与组件生命周期回调,助开发者掌握从权限、网络、路由到生命周期的完整入门路径。

应用权限

ATM

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/accesstoken-overview-0000001544703857-V2#ZH-CN_TOPIC_0000001574088913__%E6%9D%83%E9%99%90%E7%B1%BB%E5%9E%8B%E8%AF%B4%E6%98%8E

ATM(AccessTokenManage)是 HarmonyOS 上基于 AccessToken 构建的统一的应用权限管理能力。

应用权限保护的对象可以分为:

  • 数据:包含了个人数据(如照片、通讯录、日历、位置等)、设备数据(如设备标识、相机、麦克风等)、应用数据。
  • 功能:包括了设备功能(如打电话、发短信、联网等)、应用功能(如弹出悬浮框、创建快捷方式等)等。

根据授权方式的不同,权限类型可分为:

  • system_grant:即系统授权,应用被允许访问的数据不会涉及到用户或设备的敏感信息。
  • user_grant:即用户授权,应用被允许访问的数据将会涉及到用户或设备的敏感信息。

配置权限

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/accesstoken-guidelines-0000001493744016-V2

比如:应用需要访问网络图片或发送 HTTP 请求,需要在工程配置文件(src/main/module.json5)中授予网络访问权限。


示例:配置权限

工程配置文件(src/main/module.json5):

{
  "module": {
    // ...
    "requestPermissions": [
      {
        "name": "ohos.permission.INTERNET"
      }
    ]
  }
}

HTTP 请求

@ohos.net.http

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V2/js-apis-http-0000001478061929-V2

@ohos.net.http 模块提供HTTP数据请求能力。应用可以通过 HTTP 发起一个数据请求,支持常见的 GET、POST、PUT、DELETE 等方法。


示例:发送 HTTP 请求

Index组件(src/main/ets/pages/Index.ets):

import http from '@ohos.net.http'

@Entry
@Component
struct Index {
  @State
  data: string = ''

  build() {
    Column({space: 16}) {
      Button('send request')
        .onClick(() => {
          // 创建 HTTP 请求对象
          http.createHttp().request('http://duoapi.fjisp.com/saying.random')
            .then((response) => {
              console.log('response:' + response)

              // 获取服务器返回的数据
              this.data = response.result.toString()
            })
            .catch((err) => {
              // 请求失败查看错误信息
              console.log('request error:' + err.message)
            })
        })

      Text('随机一言:' + this.data)

    }
    .padding(20)
    .width('100%')
  }
}

示例效果:


路由

路由 API

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-routing-0000001503325125-V2

常见的路由 API:

  • router.pushUrl:跳转到应用内的指定页面。
  • router.replaceUrl:用应用内的某个页面替换当前页面,并销毁被替换的页面,并且无法返回到当前页。
  • router.back:返回上一页面或指定的页面。
  • router.clear:页面栈的最大容量为 32 个页面,如果超过这个限制,可以调用该方法清空历史页面栈,释放内存空间。

示例:路由 API

Index组件(src/main/ets/pages/Index.ets):

import router from '@ohos.router'

@Entry
@Component
struct Index {
  build() {
    Column({space: 16}) {
      Text('Index')

      Button('Router pushUrl Other')
        .onClick(() => {
          // 路由跳转到pages/Other,有浏览记录
          router.pushUrl({url:'pages/Other'})
        })

      Button('Router replaceUrl Other')
        .onClick(() => {
          // 路由跳转(替换)到pages/Other,无浏览记录
          router.replaceUrl({url: 'pages/Other'})
        })
    }
    .padding(20)
    .width('100%')
  }
}

Other组件(src/main/ets/pages/Other.ets):

import router from '@ohos.router'

@Entry
@Component
struct Other {
  build() {
    Column({space: 16}) {
      Text('Other')

      Button('返回上一页')
        .onClick(() => {
          // 路由返回到上一页
          router.back()
        })
    }
    .padding(20)
    .width('100%')
  }
}

示例效果:


路由参数传递

如果需要在跳转时传递一些数据给目标页,则可以在调用 Router 模块的方法时,添加一个 params 属性,并指定一个对象作为参数。

在目标页中,可以通过调用 Router 模块的 getParams 方法来获取传递过来的参数。


示例:路由参数传递

Index组件(src/main/ets/pages/Index.ets):

import router from '@ohos.router'

@Entry
@Component
struct Index {
  build() {
    Column({space: 16}) {
      Button('Router pushUrl Other')
        .onClick(() => {
          // 路由跳转到pages/Other,有浏览记录
          router.pushUrl({
            url:'pages/Other',
            // 传递参数
            params: {
              id: 1,
              message: 'Hello HarmonyOS'
            }
          })
        })
    }
    .padding(20)
    .width('100%')
  }
}

Other组件(src/main/ets/pages/Other.ets):

import router from '@ohos.router'

// 获取参数对象
const params = router.getParams()

@Entry
@Component
struct Other {
  build() {
    Column({space: 16}) {
      // 获取参数
      Text('接收到的id参数为:' + params['id'])
      Text('接收到的message参数为:' + params['message'])
    }
    .padding(20)
    .width('100%')
  }
}

示例效果:


生命周期

UIAbility 生命周期

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/uiability-lifecycle-0000001427902208-V2

当用户打开、切换和返回到对应应用时,应用中的 UIAbility 实例会在其生命周期的不同状态之间转换。

  • onCreate:在 Ability 创建时回调,执行初始化业务逻辑操作。
  • onWindowStageCreate:当 WindowStage 创建后调用。
  • onForeground:当应用从后台转到前台时触发。
  • onBackground:当应用从前台转到后台时触发。
  • onDestroy:在 Ability 销毁时回调。

UIAbility 生命周期示例图:


示例:UIAbility 生命周期

EntryAbility(src/main/ets/pages/entryability.ts):

import UIAbility from '@ohos.app.ability.UIAbility';
import hilog from '@ohos.hilog';
import window from '@ohos.window';

export default class EntryAbility extends UIAbility {

  // UIAbility实例创建完成后调用
  onCreate(want, launchParam) {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
  }

  // UIAbility实例销毁时调用
  onDestroy() {
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  // WindowStage创建完成后调用
  onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err, data) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
    });
  }

  // WindowStage销毁后调用
  onWindowStageDestroy() {
    // Main window is destroyed, release UI related resources
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  // 应用从后台转到前台时触发
  onForeground() {
    // Ability has brought to foreground
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onForeground');
  }

  // 应用从前台转到后台时触发
  onBackground() {
    // Ability has back to background
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onBackground');
  }
}

组件生命周期

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V2/arkts-page-custom-components-lifecycle-0000001524296665-V2

页面生命周期,即被 @Entry 装饰的组件生命周期:

  • onPageShow:页面每次显示时触发一次,包括路由过程、应用进入前台等场景。
  • onPageHide:页面每次隐藏时触发一次,包括路由过程、应用进入后台等场景。
  • onBackPress:当用户点击返回按钮时触发。

组件生命周期,即用 @Component 装饰的自定义组件的生命周期。

  • aboutToAppear:组件即将出现时回调该接口,具体时机为在创建自定义组件的新实例后,在执行其 build() 函数之前执行。
  • aboutToDisappear:在自定义组件销毁之前执行。

示例:页面和组件生命周期

Index组件(src/main/ets/pages/Index.ets):

import promptAction from '@ohos.promptAction'

@Entry
@Component
struct Index {
  aboutToAppear() {
    promptAction.showToast({message: 'Index aboutToAppear'})
  }

  onPageShow() {
    promptAction.showToast({message: 'Index onPageShow'})
  }

  onPageHide() {
    promptAction.showToast({message: 'Index onPageHide'})
  }

  build() {
    Column({space: 16}) {
      Text('首页')
    }
    .padding(20)
    .width('100%')
  }
}