js-apis-ability-particleAbility.md 17.5 KB
Newer Older
Z
zengyawen 已提交
1
# @ohos.ability.particleAbility (ParticleAbility模块)
M
m00512953 已提交
2

M
m00512953 已提交
3
particleAbility模块提供了操作Service类型的Ability的能力,包括启动、停止指定的particleAbility,获取dataAbilityHelper,连接、断连指定的ServiceAbility等。
M
m00512953 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

> **说明:**
> 
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。  
> 本模块接口仅可在FA模型下使用。

## 使用限制

particleAbility模块用来对Data和Service类型的Ability进行操作。

## 导入模块

```ts
import particleAbility from '@ohos.ability.particleAbility'
```

## particleAbility.startAbility

startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<void>): void

M
m00512953 已提交
24
启动指定的particleAbility(callback形式)。
M
m00512953 已提交
25

M
m00512953 已提交
26 27
使用规则:
 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
M
m00512953 已提交
28
 - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
M
m00512953 已提交
29 30
 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md)

M
m00512953 已提交
31 32 33 34 35 36
**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

| 参数名      | 类型                                            | 必填 | 说明              |
| --------- | ----------------------------------------------- | ---- | ----------------- |
M
m00512953 已提交
37 38
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 是   | 表示启动的ability |
| callback  | AsyncCallback\<void>                            | 是   | 以callback的形式返回启动Ability的结果  |
M
m00512953 已提交
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

**示例:**

```ts
import particleAbility from '@ohos.ability.particleAbility'
import wantConstant from '@ohos.ability.wantConstant'

particleAbility.startAbility(
    {
        want:
        {
            action: "action.system.home",
            entities: ["entity.system.home"],
            type: "MIMETYPE",
            flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
            deviceId: "",
            bundleName: "com.example.Data",
            abilityName: "com.example.Data.MainAbility",
            uri: ""
        },
    },
    (error, result) => {
        console.log('particleAbility startAbility errCode:' + error + 'result:' + result)
    },
)
```

## particleAbility.startAbility

startAbility(parameter: StartAbilityParameter): Promise\<void>;

M
m00512953 已提交
70
启动指定的particleAbility(Promise形式)。
M
m00512953 已提交
71

M
m00512953 已提交
72 73
使用规则:
 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
M
m00512953 已提交
74
 - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
M
m00512953 已提交
75 76
 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md)

M
m00512953 已提交
77 78 79 80 81 82
**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

| 参数名      | 类型                                            | 必填 | 说明              |
| --------- | ----------------------------------------------- | ---- | ----------------- |
M
m00512953 已提交
83
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 是   | 表示启动的ability |
M
m00512953 已提交
84 85 86 87 88

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
89
| Promise\<void> | Promise形式返回启动Ability的结果。 |
M
m00512953 已提交
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

**示例:**

```ts
import particleAbility from '@ohos.ability.particleAbility'
import wantConstant from '@ohos.ability.wantConstant'

particleAbility.startAbility(
    {
        want:
        {
            action: "action.system.home",
            entities: ["entity.system.home"],
            type: "MIMETYPE",
            flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
            deviceId: "",
            bundleName: "com.example.Data",
            abilityName: "com.example. Data.MainAbility",
            uri: ""
        },
    },
).then((data) => {
    console.info("particleAbility startAbility");
});
```

## particleAbility.terminateSelf

terminateSelf(callback: AsyncCallback\<void>): void

M
m00512953 已提交
120
销毁当前particleAbility(callback形式)。
M
m00512953 已提交
121 122 123 124 125 126 127

**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

| 参数名     | 类型                 | 必填 | 说明                 |
| -------- | -------------------- | ---- | -------------------- |
M
m00512953 已提交
128
| callback | AsyncCallback\<void> | 是   | 以callback的形式返回停止当前Ability结果 |
M
m00512953 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145

**示例:**

```ts
import particleAbility from '@ohos.ability.particleAbility'

particleAbility.terminateSelf(
    (error, result) => {
        console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result)
    }
)
```

## particleAbility.terminateSelf

terminateSelf(): Promise\<void>

M
m00512953 已提交
146
销毁当前particleAbility(Promise形式)。
M
m00512953 已提交
147 148 149 150 151 152 153

**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
154
| Promise\<void> | 使用Promise形式返回停止当前Ability结果。 |
M
m00512953 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171

**示例:**

```ts
import particleAbility from '@ohos.ability.particleAbility'

particleAbility.terminateSelf().then((data) => {
	console.info("particleAbility terminateSelf");
});
```



## particleAbility.acquireDataAbilityHelper

acquireDataAbilityHelper(uri: string): DataAbilityHelper

M
m00512953 已提交
172
获取dataAbilityHelper对象。
M
m00512953 已提交
173

M
m00512953 已提交
174 175 176
使用规则:
 - 跨应用访问dataAbility,对端应用需配置关联启动
 - 调用方应用位于后台时,使用该接口访问dataAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
M
m00512953 已提交
177
 - 跨应用场景下,目标dataAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
M
m00512953 已提交
178 179
 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md)

M
m00512953 已提交
180 181 182 183 184 185
**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

| 参数名 | 类型   | 必填 | 说明                     |
| :--- | ------ | ---- | ------------------------ |
M
m00512953 已提交
186
| uri  | string | 是   | 表示要打开的文件的路径。 |
M
m00512953 已提交
187 188 189 190 191

**返回值:**

| 类型              | 说明                                         |
| ----------------- | -------------------------------------------- |
M
m00512953 已提交
192
| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | 用来协助其他Ability访问DataAbility的工具类。 |
M
m00512953 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

**示例:**

```ts
import particleAbility from '@ohos.ability.particleAbility'

var uri = "";
particleAbility.acquireDataAbilityHelper(uri)
```


## particleAbility.startBackgroundRunning

startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void;

向系统申请长时任务,使用callback形式返回结果,建议使用新接口[backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8)

**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING

**系统能力**:SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

**参数:**

  | 参数名 | 类型 | 必填 | 说明 |
  | -------- | -------- | -------- | -------- |
  | id | number | 是 | 长时任务通知id号 |
  | request | [NotificationRequest](js-apis-notification.md#notificationrequest) | 是 | 通知参数,用于显示通知栏的信息 |
  | callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动长时任务的结果 |

 **示例**

```ts
import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent';

function callback(err, data) {
    if (err) {
        console.error("Operation failed cause: " + JSON.stringify(err));
    } else {
        console.info("Operation succeeded");
    }
}

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    let basicContent = {
        title: "title",
        text: "text"
    };
    let notificationContent = {
        contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: basicContent
    };
    let request = {
        content: notificationContent,
        wantAgent: wantAgentObj
    };
    let id = 1;
    particleAbility.startBackgroundRunning(id, request, callback);
});

```

## particleAbility.startBackgroundRunning

startBackgroundRunning(id: number, request: NotificationRequest): Promise&lt;void&gt;

**需要权限:** ohos.permission.KEEP_BACKGROUND_RUNNING

**系统能力**:SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

向系统申请长时任务,使用promise形式返回结果,建议使用新接口[backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8-1)

**参数:**

| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| id | number | 是 | 长时任务通知id号 |
| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | 是 | 通知参数,用于显示通知栏的信息 |

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
289
| Promise\<void> | 使用Promise形式返回启动长时任务的结果。 |
M
m00512953 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344

**示例**

```ts
import notification from '@ohos.notification';
import particleAbility from '@ohos.ability.particleAbility';
import wantAgent from '@ohos.wantAgent';

let wantAgentInfo = {
    wants: [
        {
            bundleName: "com.example.myapplication",
            abilityName: "com.example.myapplication.MainAbility"
        }
    ],
    operationType: wantAgent.OperationType.START_ABILITY,
    requestCode: 0,
    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};

wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
    let basicContent = {
        title: "title",
        text: "text"
    };
    let notificationContent = {
        contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: basicContent
    };
    let request = {
        content: notificationContent,
        wantAgent: wantAgentObj
    };
    let id = 1;
    particleAbility.startBackgroundRunning(id, request).then(() => {
        console.info("Operation succeeded");
    }).catch((err) => {
        console.error("Operation failed cause: " + JSON.stringify(err));
    });
});

```

## particleAbility.cancelBackgroundRunning

cancelBackgroundRunning(callback: AsyncCallback&lt;void&gt;): void;

向系统申请取消长时任务,使用callback形式返回结果,建议使用新接口[backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8)

**系统能力**:SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

 **参数:**

  | 参数名 | 类型 | 必填 | 说明 |
  | -------- | -------- | -------- | -------- |
M
m00512953 已提交
345
  | callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回取消长时任务的结果 |
M
m00512953 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

 **示例**

```ts
import particleAbility from '@ohos.ability.particleAbility';

function callback(err, data) {
    if (err) {
        console.error("Operation failed cause: " + JSON.stringify(err));
    } else {
        console.info("Operation succeeded");
    }
}

particleAbility.cancelBackgroundRunning(callback);

```

## particleAbility.cancelBackgroundRunning

cancelBackgroundRunning(): Promise&lt;void&gt;;

向系统申请取消长时任务,使用promise形式返回结果,建议使用新接口[backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1)

**系统能力**:SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
376
| Promise\<void> | 使用Promise形式返回取消长时任务的结果。 |
M
m00512953 已提交
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

 **示例**

```ts
import particleAbility from '@ohos.ability.particleAbility';

particleAbility.cancelBackgroundRunning().then(() => {
    console.info("Operation succeeded");
}).catch((err) => {
    console.error("Operation failed cause: " + JSON.stringify(err));
});

```

## particleAbility.connectAbility

connectAbility(request: Want, options:ConnectOptions): number

M
m00512953 已提交
395
将当前ability与指定的ServiceAbility进行连接(callback形式)。
M
m00512953 已提交
396

M
m00512953 已提交
397 398 399
使用规则:
 - 跨应用连接serviceAbility,对端应用需配置关联启动
 - 调用方应用位于后台时,使用该接口连接serviceAbility需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
M
m00512953 已提交
400
 - 跨应用场景下,目标serviceAbility的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
M
m00512953 已提交
401 402
 - 组件启动规则详见:[组件启动规则(FA模型)](../../application-models/component-startup-rules-fa.md)

M
m00512953 已提交
403 404 405 406 407 408 409
**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

| 参数名    | 类型           | 必填 | 说明                         |
| ------- | -------------- | ---- | ---------------------------- |
| request | [Want](js-apis-application-want.md)           | 是   | 表示被连接的ServiceAbility。 |
M
m00512953 已提交
410
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是   | 连接回调方法。           |
M
m00512953 已提交
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453


**示例**

```ts
import rpc from '@ohos.rpc'

function onConnectCallback(element, remote) {
    console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}

function onDisconnectCallback(element) {
    console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}

function onFailedCallback(code) {
    console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
}

var connId = particleAbility.connectAbility(
    {
        bundleName: "com.ix.ServiceAbility",
        abilityName: "ServiceAbilityA",
    },
    {
        onConnect: onConnectCallback,
        onDisconnect: onDisconnectCallback,
        onFailed: onFailedCallback,
    },
);

particleAbility.disconnectAbility(connId).then((data) => {
    console.log(" data: " + data);
}).catch((error) => {
    console.log('particleAbilityTest result errCode : ' + error.code)
});
    
```

## particleAbility.disconnectAbility

disconnectAbility(connection: number, callback:AsyncCallback\<void>): void;

M
m00512953 已提交
454
断开当前ability与指定ServiceAbility的连接(callback形式)。
M
m00512953 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503

**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**参数:**

  | 参数名 | 类型 | 必填 | 说明 |
  | -------- | -------- | -------- | -------- |
  | callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回断开连接的结果 |

**示例**

```ts
import rpc from '@ohos.rpc'

function onConnectCallback(element, remote) {
    console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}

function onDisconnectCallback(element) {
    console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}

function onFailedCallback(code) {
    console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
}

var connId = particleAbility.connectAbility(
    {
        bundleName: "com.ix.ServiceAbility",
        abilityName: "ServiceAbilityA",
    },
    {
        onConnect: onConnectCallback,
        onDisconnect: onDisconnectCallback,
        onFailed: onFailedCallback,
    },
);
var result = particleAbility.disconnectAbility(connId).then((data) => {
    console.log(" data: " + data);
}).catch((error) => {
    console.log('particleAbilityTest result errCode : ' + error.code)
});
```


## particleAbility.disconnectAbility

disconnectAbility(connection: number): Promise\<void>;

M
m00512953 已提交
504
断开当前ability与指定ServiceAbility的连接(Promise形式)。
M
m00512953 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
| Promise\<void> | 使用Promise形式返回结果。 |

**示例**

```ts
import rpc from '@ohos.rpc'

function onConnectCallback(element, remote) {
    console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy));
}

function onDisconnectCallback(element) {
    console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId)
}

function onFailedCallback(code) {
    console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code)
}

var connId = particleAbility.connectAbility(
    {
        bundleName: "com.ix.ServiceAbility",
        abilityName: "ServiceAbilityA",
    },
    {
        onConnect: onConnectCallback,
        onDisconnect: onDisconnectCallback,
        onFailed: onFailedCallback,
    },
);

particleAbility.disconnectAbility(connId).then((data) => {
    console.log(" data: " + data);
}).catch((error) => {
    console.log('particleAbilityTest result errCode : ' + error.code)
});

```

## ErrorCode

M
m00512953 已提交
553
表示错误码。
M
m00512953 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568

**系统能力**:SystemCapability.Ability.AbilityRuntime.FAModel

| 名称                          | 值   | 说明                                                         |
| ----------------------------- | ---- | ------------------------------------------------------------ |
| INVALID_PARAMETER         | -1    | 无效的参数。 |