fa-pageability.md 9.3 KB
Newer Older
1
# PageAbility开发指导
Z
zhaoyuan 已提交
2

G
guyuanzhang 已提交
3 4
## 概述
### 功能简介
R
RayShih 已提交
5
PageAbility是具备ArkUI实现的Ability,是开发者具体可见并可以交互的Ability实例,开发者通过IDE创建Ability时,IDE会自动创建相关模板代码。PageAbility相关能力通过单例featureAbility暴露,生命周期相关回调通过app.js/app.ets中回调函数暴露。
Z
zhaoyuan 已提交
6

G
guyuanzhang 已提交
7
### PageAbility的生命周期
Z
zhaoyuan 已提交
8

R
RayShih 已提交
9
**Ability生命周期介绍**(Ability Life Cycle):
Z
zhaoyuan 已提交
10

R
RayShih 已提交
11
Ability生命周期是Ability被调度到INACTIVE、ACTIVE、BACKGROUND等各个状态的统称。PageAbility生命周期流转如下图所示:
Z
zhaoyuan 已提交
12 13 14 15 16 17 18 19 20 21

![PageAbility-Lifecycle](figures/page-ability-lifecycle.png)


**Ability生命周期状态说明:**

  - **UNINITIALIZED**:未初始状态,为临时状态,Ability被创建后会由UNINITIALIZED状态进入INITIAL状态。

  - **INITIAL**:初始化状态,也表示停止状态,表示当前Ability未运行,Ability被启动后由INITIAL态进入INACTIVE状态。

G
guyuanzhang 已提交
22
  - **INACTIVE**:失去焦点状态,表示当前窗口已显示但是无焦点状态。
Z
zhaoyuan 已提交
23

G
guyuanzhang 已提交
24
  - **ACTIVE**:前台激活状态,表示当前窗口已显示,并获取焦点。
Z
zhaoyuan 已提交
25

R
RayShih 已提交
26
  - **BACKGROUND**:后台状态,表示当前Ability退到后台,Ability在被销毁后由BACKGROUND状态进入INITIAL状态,或者重新被激活后由BACKGROUND状态进入ACTIVE状态。
Z
zhaoyuan 已提交
27

R
RayShih 已提交
28
**PageAbility生命周期回调与生命周期状态的关系如下图所示:**
Z
zhaoyuan 已提交
29

Z
zengyawen 已提交
30
![fa-pageAbility-lifecycle](figures/fa-pageAbility-lifecycle.png)
Z
zhaoyuan 已提交
31

G
guyuanzhang 已提交
32
PageAbility提供命周期回调,开发者可以在`app.js/app.ets`中重写生命周期相关回调函数 。目前`app.js`环境中仅支持onCreate和onDestroy回调,`app.ets`环境支持全量生命周期回调。
G
guyuanzhang 已提交
33

G
guyuanzhang 已提交
34 35
## 开发指导
### featureAbility接口说明
G
guyuanzhang 已提交
36

G
guyuanzhang 已提交
37
**表1** featureAbility接口介绍
G
guyuanzhang 已提交
38

G
guyuanzhang 已提交
39 40 41 42 43 44
| 接口名                                              | 描述            |
| --------------------------------------------------- | --------------- |
| void startAbility(parameter: StartAbilityParameter) | 启动Ability     |
| Context getContext():                               | 获取应用Context |
| void terminateSelf()                                | 结束Ability     |
| bool hasWindowFocus()                               | 是否获取焦点    |
G
guyuanzhang 已提交
45

Z
zhaoyuan 已提交
46

G
guyuanzhang 已提交
47
### 启动本地PageAbility
Z
zhaoyuan 已提交
48

R
RayShih 已提交
49
**导入模块**
Z
zhaoyuan 已提交
50

R
RayShih 已提交
51 52
```js
  import featureAbility from '@ohos.ability.featureAbility'
Z
zhaoyuan 已提交
53
```
R
RayShih 已提交
54 55

**示例**
Z
zhaoyuan 已提交
56 57

```javascript
R
RayShih 已提交
58 59
  import featureAbility from '@ohos.ability.featureAbility'
  featureAbility.startAbility({
Z
zengyawen 已提交
60 61 62 63 64 65
  want:
  {
    action: "",
    entities: [""],
    type: "",
    options: {
R
RayShih 已提交
66
      // Grant the permission to perform read operations on the URI.
Z
zengyawen 已提交
67
      authReadUriPermission: true,
R
RayShih 已提交
68
      // Grant the permission to perform write operations on the URI.
Z
zengyawen 已提交
69
      authWriteUriPermission: true,
R
RayShih 已提交
70
      // support forwarding the intent result to the ability.
Z
zengyawen 已提交
71
      abilityForwardResult: true,
R
RayShih 已提交
72
      // Enable abiligy continuation.
Z
zengyawen 已提交
73
      abilityContinuation: true,
R
RayShih 已提交
74
      // Specify that a component does not belong to ohos.
Z
zengyawen 已提交
75
      notOhosComponent: true,
R
RayShih 已提交
76
      // Specify that an ability is started.
Z
zengyawen 已提交
77
      abilityFormEnabled: true,
R
RayShih 已提交
78
      // Grant the permission for possible persisting on the URI.
Z
zengyawen 已提交
79
      authPersistableUriPermission: true,
R
RayShih 已提交
80
      // Grant the permission for possible persisting on the prefix URI.
Z
zengyawen 已提交
81
      authPrefixUriPermission: true,
R
RayShih 已提交
82
      // Support distributed scheduling system startup on multiple devices.
Z
zengyawen 已提交
83
      abilitySliceMultiDevice: true,
R
RayShih 已提交
84
      // A service ability is started regardless of whether the host application has been started.
Z
zengyawen 已提交
85
      startForegroundAbility: true,
R
RayShih 已提交
86
      // Install the specified ability if it is not installed.
Z
zengyawen 已提交
87
      installOnDemand: true,
R
RayShih 已提交
88
      // Return the result to the ability slice.
Z
zengyawen 已提交
89
      abilitySliceForwardResult: true,
R
RayShih 已提交
90
      // Install the specified ability with background mode if it is not installed.
Z
zengyawen 已提交
91
      installWithBackgroundMode: true
Z
zhaoyuan 已提交
92
    },
Z
zengyawen 已提交
93 94 95 96 97
    deviceId: "",
    bundleName: "com.example.startability",
    abilityName: "com.example.startability.MainAbility",
    uri: ""
  },
R
RayShih 已提交
98 99
  },
  );
Z
zengyawen 已提交
100
```
R
RayShih 已提交
101 102 103 104

`want`参数也可以使用parameters参数,使用key-value的方式输入。
**示例**

Z
zengyawen 已提交
105
```javascript
R
RayShih 已提交
106 107
  import featureAbility from '@ohos.ability.featureAbility'
  featureAbility.startAbility({
Z
zengyawen 已提交
108 109 110 111 112 113 114 115
    want:
    {
        bundleName: "com.example.startability",
        uri: "",
        parameters: {
            abilityName: "com.example.startability.MainAbility"
        }
    },
R
RayShih 已提交
116 117
  },
  );
Z
zhaoyuan 已提交
118
```
119
### 启动远程PageAbility(当前仅对系统应用开放)
120
>说明:由于DeviceManager的getTrustedDeviceListSync接口仅对系统应用开放,当前启动远程PageAbility仅支持系统应用
Z
zhaoyuan 已提交
121

R
RayShih 已提交
122
**导入模块**
Z
zhaoyuan 已提交
123 124

```
R
RayShih 已提交
125 126
  import featureAbility from '@ohos.ability.featureAbility'
  import deviceManager from '@ohos.distributedHardware.deviceManager';
Z
zhaoyuan 已提交
127 128
```

R
RayShih 已提交
129
**示例**
130
```ts
R
RayShih 已提交
131
  function onStartRemoteAbility() {
132
  console.info('onStartRemoteAbility begin');
133
  let params;
134
  let wantValue = {
135 136 137 138 139 140 141 142 143 144 145 146
    bundleName: 'ohos.samples.etsDemo',
    abilityName: 'ohos.samples.etsDemo.RemoteAbility',
    deviceId: getRemoteDeviceId(),
    parameters: params
  };
  console.info('onStartRemoteAbility want=' + JSON.stringify(wantValue));
  featureAbility.startAbility({
    want: wantValue
  }).then((data) => {
    console.info('onStartRemoteAbility finished, ' + JSON.stringify(data));
  });
  console.info('onStartRemoteAbility end');
R
RayShih 已提交
147
  }
148
```
R
RayShih 已提交
149 150

从DeviceManager获取`deviceId`,具体示例代码如下:
151
```ts
R
RayShih 已提交
152
  import deviceManager from '@ohos.distributedHardware.deviceManager';
153
  let dmClass;
R
RayShih 已提交
154
  function getRemoteDeviceId() {
155
    if (typeof dmClass === 'object' && dmClass != null) {
156
        let list = dmClass.getTrustedDeviceListSync();
157 158 159 160 161 162 163 164 165
        if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
            console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
            return;
        }
        console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
        return list[0].deviceId;
    } else {
        console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null");
    }
R
RayShih 已提交
166
  }
167
```
R
RayShih 已提交
168

169
在跨设备场景下,需要向用户申请数据同步的权限。具体示例代码如下:
170
```ts
171
  import abilityAccessCtrl from "@ohos.abilityAccessCtrl";
R
RayShih 已提交
172 173
  import bundle from '@ohos.bundle';
  async function RequestPermission() {
174
  console.info('RequestPermission begin');
175
  let array: Array<string> = ["ohos.permission.DISTRIBUTED_DATASYNC"];
176 177 178 179
  let bundleFlag = 0;
  let tokenID = undefined;
  let userID = 100;
  let  appInfo = await bundle.getApplicationInfo('ohos.samples.etsDemo', bundleFlag, userID);
180
  tokenID = appInfo.accessTokenId;
181
  let atManager = abilityAccessCtrl.createAtManager();
182 183
  let requestPermissions: Array<string> = [];
  for (let i = 0;i < array.length; i++) {
184
    let result = await atManager.verifyAccessToken(tokenID, array[i]);
185
    console.info("verifyAccessToken result:" + JSON.stringify(result));
186 187 188 189 190
    if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
    } else {
      requestPermissions.push(array[i]);
    }
  }
191
  console.info("requestPermissions:" + JSON.stringify(requestPermissions));
192 193 194 195 196
  if (requestPermissions.length == 0 || requestPermissions == []) {
    return;
  }
  let context = featureAbility.getContext();
  context.requestPermissionsFromUser(requestPermissions, 1, (data)=>{
197 198 199 200
    console.info("data:" + JSON.stringify(data));
    console.info("data requestCode:" + data.requestCode);
    console.info("data permissions:" + data.permissions);
    console.info("data authResults:" + data.authResults);
201
  });
202
  console.info('RequestPermission end');
R
RayShih 已提交
203
  }
G
guyuanzhang 已提交
204
```
R
RayShih 已提交
205

G
guyuanzhang 已提交
206 207 208 209 210
### 生命周期接口说明
**表2** 生命周期回调函数介绍

| 接口名       | 描述                                                         |
| ------------ | ------------------------------------------------------------ |
211 212
| onShow()     | Ability由后台不可见状态切换到前台可见状态调用onShow方法,此时用户在屏幕可以看到该Ability |
| onHide()     | Ability由前台切换到后台不可见状态时调用onHide方法,此时用户在屏幕看不到该Ability。 |
G
guyuanzhang 已提交
213 214 215 216 217
| onDestroy()  | 应用退出,销毁Ability对象前调用onDestroy方法,开发者可以在该方法里做一些回收资源、清空缓存等应用退出前的准备工作。 |
| onCreate()   | Ability第一次启动创建Ability时调用onCreate方法,开发者可以在该方法里做一些应用初始化工作。 |
| onInactive() | Ability失去焦点时调用onInactive方法,Ability在进入后台状态时会先失去焦点,再进入后台。 |
| onActive()   | Ability切换到前台,并且已经获取焦点时调用onActive方法。      |

R
RayShih 已提交
218 219 220
**示例**
开发者需要重写`app.js/app.ets`中相关生命周期回调函数,IDE模板默认生成`onCreate()``onDestroy()`方法,其他方法需要开发者自行实现。

G
guyuanzhang 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
```javascript
export default {
  onCreate() {
    console.info('Application onCreate')
  },
  onDestroy() {
    console.info('Application onDestroy')
  },
  onShow(){
    console.info('Application onShow')
  },
  onHide(){
    console.info('Application onHide')
  },
  onInactive(){
    console.info('Application onInactive')
  },
  onActive(){
    console.info('Application onActive')
  },
}
```
### 开发实例
G
guyuanzhang 已提交
244 245
针对pageAbility开发,有以下示例工程可供参考:

R
RayShih 已提交
246
[DMS](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
G
guyuanzhang 已提交
247 248

在本示例中完整展示了启动本地Ability、启动远程Ability的使用方法。