create-pageability.md 2.4 KB
Newer Older
Z
zengyawen 已提交
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
# 创建PageAbility


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

```ts
export default {
  onCreate() {
    console.info('Application onCreate')
  },
  onDestroy() {
    console.info('Application onDestroy')
  },
  onShow() {
    console.info('Application onShow')
  },
  onHide() {
    console.info('Application onHide')
  },
  onActive() {
    console.info('Application onActive')
  },
  onInactive() {
    console.info('Application onInactive')
  },
  onNewWant() {
    console.info('Application onNewWant')
  },
}
```


33
PageAbility创建成功后,其abilities相关的配置项在config.json中体现,一个名字为EntryAbility的config.json配置文件示例如下:
Z
zengyawen 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

```json
{
  "abilities": [
    {
      "skills": [
        {
          "entities": [
            "entity.system.home"
          ],
          "actions": [
            "action.system.home"
          ]
        }
      ],
      "orientation": "unspecified",
      "visible": true,
51 52
      "srcPath": "EntryAbility",
      "name": ".EntryAbility",
Z
zengyawen 已提交
53 54
      "srcLanguage": "ets",
      "icon": "$media:icon",
55
      "description": "$string:EntryAbility_desc",
Z
zengyawen 已提交
56
      "formsEnabled": false,
57
      "label": "$string:EntryAbility_label",
Z
zengyawen 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
      "type": "page",
      "launchType": "singleton"
    }
  ]
}
```


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


  **表1** featureAbility接口说明

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


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

```ts
U
unknown 已提交
79 80
import featureAbility from '@ohos.ability.featureAbility';
import fs from '@ohos.file.fs';
Z
zengyawen 已提交
81 82

(async () => {
U
unknown 已提交
83
  let dir: string;
Z
zengyawen 已提交
84
  try {
U
unknown 已提交
85 86
    console.info('Begin to getOrCreateDistributedDir');
    dir = await featureAbility.getContext().getOrCreateDistributedDir();
Z
zengyawen 已提交
87 88
    console.info('distribute dir is ' + dir)
  } catch (error) {
U
unknown 已提交
89
    console.error('getOrCreateDistributedDir failed with ' + error);
Z
zengyawen 已提交
90 91 92 93
  }

  let fd: number;
  let path = dir + "/a.txt";
U
unknown 已提交
94 95
  fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd;
  fs.close(fd);
Z
zengyawen 已提交
96 97
})()
```