首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

HarmonyOS Next开发学习手册——创建PageAbility

  • 25-02-22 06:41
  • 4810
  • 9200
blog.csdn.net

通过DevEco Studio开发平台创建PageAbility时,DevEco Studio会在app.js/app.ets中默认生成onCreate()和onDestroy()方法,其他方法需要开发者自行实现。接口说明参见前述章节,创建PageAbility示例如下:

import featureAbility from '@ohos.ability.featureAbility';
import Logger from '../utils/Logger';

const TAG: string = 'MainAbility';

class MainAbility {
  onCreate() {
    // 获取context并调用相关方法
    let context = featureAbility.getContext();
    context.getBundleName((data, bundleName) => {
      Logger.info(TAG, 'ability bundleName:' + bundleName);
    });
    Logger.info(TAG, 'Application onCreate');
  }

  onDestroy() {
    Logger.info(TAG, 'Application onDestroy');
  }

  onShow(): void {
    Logger.info(TAG, 'Application onShow');
  }

  onHide(): void {
    Logger.info(TAG, 'Application onHide');
  }

  onActive(): void {
    Logger.info(TAG, 'Application onActive');
  }

  onInactive(): void {
    Logger.info(TAG, 'Application onInactive');
  }

  onNewWant() {
    Logger.info(TAG, 'Application onNewWant');
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39

export default new MainAbility();
PageAbility创建成功后,其abilities相关的配置项在config.json中体现,一个名字为EntryAbility的config.json配置文件示例如下:

{
  ...
  "module": {
    ...
    "abilities": [
      {
        "skills": [
          {
            "entities": [
              "entity.system.home"
            ],
            "actions": [
              "action.system.home"
            ]
          }
        ],
        "orientation": "unspecified",
        "formsEnabled": false,
        "name": ".MainAbility",
        "srcLanguage": "ets",
        "srcPath": "MainAbility",
        "icon": "$media:icon",
        "description": "$string:MainAbility_desc",
        "label": "$string:MainAbility_label",
        "type": "page",
        "visible": true,
        "launchType": "singleton"
      },
      ...
    ]
    ...
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

FA模型中,可以通过featureAbility的getContext接口获取应用上下文,进而使用上下文提供的能力。

表1 featureAbility接口说明

接口名接口描述
getContext()获取应用上下文。

通过getContext获取应用上下文并获取分布式目录的示例如下:

import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs';
import promptAction from '@ohos.promptAction';
import Logger from '../../utils/Logger';

const TAG: string = 'PagePageAbilityFirst';
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

(async (): Promise => {
  let dir: string;
  try {
    Logger.info(TAG, 'Begin to getOrCreateDistributedDir');
    dir = await featureAbility.getContext().getOrCreateDistributedDir();
    promptAction.showToast({
      message: dir
    });
    Logger.info(TAG, 'distribute dir is ' + dir);
    let fd: number;
    let path = dir + '/a.txt';
    fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd;
    fs.close(fd);
  } catch (error) {
    Logger.error(TAG, `getOrCreateDistributedDir failed with : ${error}`);
  }
})()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

启动本地PageAbility

PageAbility相关的能力通过featureAbility提供,启动本地Ability通过featureAbility中的startAbility接口实现。

表1 featureAbility接口说明

接口名接口描述
startAbility(parameter: StartAbilityParameter)启动Ability。
startAbilityForResult(parameter: StartAbilityParameter)启动Ability,并在该Ability被销毁时返回执行结果。

如下示例通过startAbility显式启动PageAbility。启动Ability的参数包含want,关于want的说明详见 对象间信息传递载体Want ,相应的,隐式启动与显式启动也不在此赘述。

import featureAbility from '@ohos.ability.featureAbility'
import Want from '@ohos.app.ability.Want';
import Logger from '../../utils/Logger';

const TAG: string = 'PagePageAbilityFirst';
  • 1
  • 2
  • 3
  • 4
  • 5

  try {
    Logger.info(TAG, 'Begin to start ability');
    let want: Want = {
      bundleName: 'com.samples.famodelabilitydevelop',
      moduleName: 'entry',
      abilityName: 'com.samples.famodelabilitydevelop.PageAbilitySingleton'
    };
    await featureAbility.startAbility({ want: want });
    Logger.info(TAG, `Start ability succeed`);
  }
  catch (error) {
    Logger.error(TAG, 'Start ability failed with ' + error);
  }
})()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

停止PageAbility

停止PageAbility通过featureAbility中的terminateSelf接口实现。

表1 featureAbility接口说明

| 接口名 | 接口描述 |
| terminateSelf() | 停止Ability。|
| terminateSelfWithResult(parameter: AbilityResult) | 设置该PageAbility停止时返回给调用者的结果及数据并停止Ability。|

如下示例展示了停止Ability的方法。

import featureAbility from '@ohos.ability.featureAbility';
import Logger from '../../utils/Logger';

const TAG: string = 'PagePageAbilityFirst';
  • 1
  • 2
  • 3
  • 4

(async (): Promise => {
  try {
    Logger.info(TAG, 'Begin to terminateSelf');
    await featureAbility.terminateSelf();
    Logger.info(TAG, 'terminateSelf succeed');
  } catch (error) {
    Logger.error(TAG, 'terminateSelf failed with ' + error);
  }
})()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

启动指定页面

当PageAbility的启动模式设置为单例时(具体设置方法和典型场景示例见 PageAbility的启动模式 ,缺省情况下是单实例模式),若PageAbility已被拉起,再次启动PageAbility会触发onNewWant回调(即非首次拉起)。应用开发者可以通过want传递启动参数,例如开发者希望指定页面启动PageAbility,可以通过want中的parameters参数传递pages信息,具体示例代码如下:

调用方PageAbility的app.ets中或者page中,使用startAbility再次拉起PageAbility,通过want中的uri参数传递页面信息:

import featureAbility from '@ohos.ability.featureAbility';
import Want from '@ohos.app.ability.Want';
import Logger from '../../utils/Logger';

const TAG: string = 'PagePageAbilityFirst';
  • 1
  • 2
  • 3
  • 4
  • 5

(async (): Promise => {
  let wantInfo: Want = {
    bundleName: 'com.samples.famodelabilitydevelop',
    abilityName: 'com.samples.famodelabilitydevelop.PageAbilitySingleton',
    parameters: { page: 'pages/second' }
  };
  featureAbility.startAbility({ want: wantInfo }).then((data) => {
    Logger.debug(TAG, `restartAbility success : ${data}`);
  });
})()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在目标端PageAbility的onNewWant回调中获取包含页面信息的want参数:

// GlobalContext.ts 构造单例对象
export class GlobalContext {
  private constructor() {
  }

  private static instance: GlobalContext;
  private _objects = new Map();

  public static getContext(): GlobalContext {
    if (!GlobalContext.instance) {
      GlobalContext.instance = new GlobalContext();
    }
    return GlobalContext.instance;
  }

  getObject(value: string): Object | undefined {
    return this._objects.get(value);
  }

  setObject(key: string, objectClass: Object): void {
    this._objects.set(key, objectClass);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

import Want from '@ohos.app.ability.Want';
import featureAbility from '@ohos.ability.featureAbility';
import { GlobalContext } from '../utils/GlobalContext';

class PageAbilitySingleton {
  onNewWant(want: Want) {
    featureAbility.getWant().then((want) => {
      GlobalContext.getContext().setObject('newWant', want);
    })
  }
}

export default new PageAbilitySingleton();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在目标端页面的自定义组件中获取包含页面信息的want参数并根据uri做路由处理:

import Want from '@ohos.app.ability.Want';
import router from '@ohos.router';
import { GlobalContext } from '../../utils/GlobalContext';

@Entry
@Component
struct First {
  onPageShow() {
    let newWant = GlobalContext.getContext().getObject('newWant') as Want;
    if (newWant) {
      if (newWant.parameters) {
        if (newWant.parameters.page) {
          router.pushUrl({ url: newWant.parameters.page as string});
          GlobalContext.getContext().setObject("newWant", undefined)
        }
      }
    }
  }

  build() {
    Column() {
      Row() {
        Text($r('app.string.singleton_first_title'))
          .fontSize(24)
          .fontWeight(FontWeight.Bold)
          .textAlign(TextAlign.Start)
          .margin({ top: 12, bottom: 11, right: 24, left: 24 })
      }
      .width('100%')
      .height(56)
      .justifyContent(FlexAlign.Start)

      Image($r('app.media.pic_empty'))
        .width(120)
        .height(120)
        .margin({ top: 224 })

      Text($r('app.string.no_content'))
        .fontSize(14)
        .margin({ top: 8, bottom: 317, right: 152, left: 152 })
        .fontColor($r('app.color.text_color'))
        .opacity(0.4)
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.backGrounding'))
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48

当PageAbility的启动模式设置为多实例模式或为首次启动单例模式的PageAbility时(具体设置方法和典型场景示例见 PageAbility的启动模式 ),在调用方PageAbility中,通过want中的parameters参数传递要启动的指定页面的pages信息,调用startAbility()方法启动PageAbility。被调用方可以在onCreate中使用featureAbility的getWant方法获取want,再通过调用router.pushUrl实现启动指定页面。

调用方的页面中实现按钮点击触发startAbility方法启动目标端PageAbility,startAbility方法的入参want中携带指定页面信息,示例代码如下:

import featureAbility from '@ohos.ability.featureAbility';
import Want from '@ohos.app.ability.Want';
import { BusinessError } from '@ohos.base';
import fs from '@ohos.file.fs';
import promptAction from '@ohos.promptAction';
import worker from '@ohos.worker';
import Logger from '../../utils/Logger';

const TAG: string = 'PagePageAbilityFirst';

@Entry
@Component
struct PagePageAbilityFirst {
  build() {
    Column() {
      Row() {
        Flex({ justifyContent: FlexAlign.Start, alignContent: FlexAlign.Center }) {
          Text($r('app.string.pageAbility_first_button'))
            .fontSize(24)
            .fontWeight(FontWeight.Bold)
            .textAlign(TextAlign.Start)
            .margin({ top: 12, bottom: 11, right: 24, left: 24 })
        }
      }
      .width('100%')
      .height(56)
      .justifyContent(FlexAlign.Start)
      .backgroundColor($r('app.color.backGrounding'))

      List({ initialIndex: 0 }) {
        ...
        ListItem() {
          Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) {
            Text($r('app.string.start_standard_first_button'))
              .textAlign(TextAlign.Start)
              .fontWeight(FontWeight.Medium)
              .margin({ top: 17, bottom: 17, left: 12, right: 92 })
              .fontSize(16)
              .width(232)
              .height(22)
              .fontColor($r('app.color.text_color'))
          }
          .onClick(() => {
            let want: Want = {
              bundleName: 'com.samples.famodelabilitydevelop',
              abilityName: 'com.samples.famodelabilitydevelop.PageAbilityStandard',
              parameters: { page: 'pages/first' }
            };
            featureAbility.startAbility({ want: want }).then((data) => {
              Logger.info(TAG, `startAbility finish:${data}`);
            }).catch((err: BusinessError) => {
              Logger.info(TAG, `startAbility failed errcode:${err.code}`);
            })
          })
        }
        .height(56)
        .backgroundColor($r('app.color.start_window_background'))
        .borderRadius(24)
        .margin({ top: 12, right: 12, left: 12 })

        ListItem() {
          Flex({ justifyContent: FlexAlign.SpaceBetween, alignContent: FlexAlign.Center }) {
            Text($r('app.string.start_standard_second_button'))
              .textAlign(TextAlign.Start)
              .fontWeight(FontWeight.Medium)
              .margin({ top: 17, bottom: 17, left: 12, right: 92 })
              .fontSize(16)
              .width(232)
              .height(22)
              .fontColor($r('app.color.text_color'))
          }
          .onClick(() => {
            let want: Want = {
              bundleName: 'com.samples.famodelabilitydevelop',
              abilityName: 'com.samples.famodelabilitydevelop.PageAbilityStandard',
              parameters: { page: 'pages/second' }
            };
            featureAbility.startAbility({ want: want }).then((data) => {
              Logger.info(TAG, `startAbility finish:${data}`);
            }).catch((err: BusinessError) => {
              Logger.info(TAG, `startAbility failed errcode:${err.code}`);
            })
          })
        }
        .height(56)
        .backgroundColor($r('app.color.start_window_background'))
        .borderRadius(24)
        .margin({ top: 12, right: 12, left: 12 })
        ...
      }
      .height('100%')
      .backgroundColor($r('app.color.backGrounding'))
    }
    .width('100%')
    .margin({ top: 8 })
    .backgroundColor($r('app.color.backGrounding'))
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98

目标端PageAbility的onCreate生命周期回调中通过featureAbility的getWant方法获取want,并对参数进行解析,实现指定页面拉起:

import featureAbility from '@ohos.ability.featureAbility';
import router from '@ohos.router';

class PageAbilityStandard {
  onCreate() {
    featureAbility.getWant().then((want) => {
      if (want.parameters) {
        if (want.parameters.page) {
          router.pushUrl({ url: want.parameters.page as string });
        }
      }
    })
  }
}

export default new PageAbilityStandard();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

鸿蒙全栈开发全新学习指南

为了积极培养鸿蒙生态人才,让大家都能学习到鸿蒙开发最新的技术,针对一些在职人员、0基础小白、应届生/计算机专业、鸿蒙爱好者等人群,整理了一套纯血版鸿蒙(HarmonyOS Next)全栈开发技术的学习路线【包含了大厂APP实战项目开发】。

本路线共分为四个阶段:

第一阶段:鸿蒙初中级开发必备技能

在这里插入图片描述

第二阶段:鸿蒙南北双向高工技能基础:gitee.com/MNxiaona/733GH

第三阶段:应用开发中高级就业技术

第四阶段:全网首发-工业级南向设备开发就业技术:gitee.com/MNxiaona/733GH

鸿蒙开发面试真题(含参考答案):gitee.com/MNxiaona/733GH

写在最后

  • 如果你觉得这篇内容对你还蛮有帮助,我想邀请你帮我三个小忙:
  • 点赞,转发,有你们的 『点赞和评论』,才是我创造的动力。
  • 关注小编,同时可以期待后续文章ing?,不定期分享原创知识。
  • 想要获取更多完整鸿蒙最新学习资源,请移步前往小编:gitee.com/MNxiaona/733GH

文章知识点与官方知识档案匹配,可进一步学习相关知识
Python入门技能树首页概览450702 人正在系统学习中
鸿蒙开发学习资料领取!!!
微信名片
注:本文转载自blog.csdn.net的OpenHarmony_小贾的文章"https://blog.csdn.net/maniuT/article/details/139970544"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2491) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top