js-apis-ability-particleAbility.md 15.8 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 26 27 28 29 30 31

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

**参数:**

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

**示例:**

```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 已提交
65
启动指定的particleAbility(Promise形式)。
M
m00512953 已提交
66 67 68 69 70 71 72

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

**参数:**

| 参数名      | 类型                                            | 必填 | 说明              |
| --------- | ----------------------------------------------- | ---- | ----------------- |
M
m00512953 已提交
73
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 是   | 表示启动的ability |
M
m00512953 已提交
74 75 76 77 78

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
79
| Promise\<void> | Promise形式返回启动Ability的结果。 |
M
m00512953 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109

**示例:**

```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 已提交
110
销毁当前particleAbility(callback形式)。
M
m00512953 已提交
111 112 113 114 115 116 117

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

**参数:**

| 参数名     | 类型                 | 必填 | 说明                 |
| -------- | -------------------- | ---- | -------------------- |
M
m00512953 已提交
118
| callback | AsyncCallback\<void> | 是   | 以callback的形式返回停止当前Ability结果 |
M
m00512953 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

**示例:**

```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 已提交
136
销毁当前particleAbility(Promise形式)。
M
m00512953 已提交
137 138 139 140 141 142 143

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

**返回值:**

| 类型           | 说明                      |
| -------------- | ------------------------- |
M
m00512953 已提交
144
| Promise\<void> | 使用Promise形式返回停止当前Ability结果。 |
M
m00512953 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161

**示例:**

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

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



## particleAbility.acquireDataAbilityHelper

acquireDataAbilityHelper(uri: string): DataAbilityHelper

M
m00512953 已提交
162
获取dataAbilityHelper对象。
M
m00512953 已提交
163 164 165 166 167 168 169

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

**参数:**

| 参数名 | 类型   | 必填 | 说明                     |
| :--- | ------ | ---- | ------------------------ |
M
m00512953 已提交
170
| uri  | string | 是   | 表示要打开的文件的路径。 |
M
m00512953 已提交
171 172 173 174 175

**返回值:**

| 类型              | 说明                                         |
| ----------------- | -------------------------------------------- |
M
m00512953 已提交
176
| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | 用来协助其他Ability访问DataAbility的工具类。 |
M
m00512953 已提交
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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

**示例:**

```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 已提交
273
| Promise\<void> | 使用Promise形式返回启动长时任务的结果。 |
M
m00512953 已提交
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 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

**示例**

```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 已提交
329
  | callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回取消长时任务的结果 |
M
m00512953 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359

 **示例**

```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 已提交
360
| Promise\<void> | 使用Promise形式返回取消长时任务的结果。 |
M
m00512953 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

 **示例**

```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 已提交
379
将当前ability与指定的ServiceAbility进行连接(callback形式)。
M
m00512953 已提交
380 381 382 383 384 385 386 387

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

**参数:**

| 参数名    | 类型           | 必填 | 说明                         |
| ------- | -------------- | ---- | ---------------------------- |
| request | [Want](js-apis-application-want.md)           | 是   | 表示被连接的ServiceAbility。 |
M
m00512953 已提交
388
| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | 是   | 连接回调方法。           |
M
m00512953 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431


**示例**

```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 已提交
432
断开当前ability与指定ServiceAbility的连接(callback形式)。
M
m00512953 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 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

**系统能力**: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 已提交
482
断开当前ability与指定ServiceAbility的连接(Promise形式)。
M
m00512953 已提交
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 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

**系统能力**: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 已提交
531
表示错误码。
M
m00512953 已提交
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

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

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