js-apis-ability-particleAbility.md 16.1 KB
Newer Older
Z
zengyawen 已提交
1
# @ohos.ability.particleAbility (ParticleAbility模块)
M
m00512953 已提交
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 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 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 273 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 329 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 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394

particleAbility模块提供了Service类型Ability的能力,包括启动、停止指定的particleAbility,获取dataAbilityHelper,连接、断开当前Ability与指定ServiceAbility等。

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

## 使用限制

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

## 导入模块

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

## particleAbility.startAbility

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

使用此方法启动指定的particleAbility(callback形式)。

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

**参数:**

| 参数名      | 类型                                            | 必填 | 说明              |
| --------- | ----------------------------------------------- | ---- | ----------------- |
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 是   | 指示启动的ability |
| callback  | AsyncCallback\<void>                            | 是   | 被指定的回调方法  |

**示例:**

```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>;

使用此方法启动指定的particleAbility(Promise形式)。

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

**参数:**

| 参数名      | 类型                                            | 必填 | 说明              |
| --------- | ----------------------------------------------- | ---- | ----------------- |
| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | 是   | 指示启动的ability |

**返回值:**

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

**示例:**

```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

终止particleAbility(callback形式)。

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

**参数:**

| 参数名     | 类型                 | 必填 | 说明                 |
| -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback\<void> | 是   | 表示被指定的回调方法 |

**示例:**

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

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

## particleAbility.terminateSelf

terminateSelf(): Promise\<void>

终止particleAbility(Promise形式)。

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

**返回值:**

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

**示例:**

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

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



## particleAbility.acquireDataAbilityHelper

acquireDataAbilityHelper(uri: string): DataAbilityHelper

获取dataAbilityHelper。

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

**参数:**

| 参数名 | 类型   | 必填 | 说明                     |
| :--- | ------ | ---- | ------------------------ |
| uri  | string | 是   | 指示要打开的文件的路径。 |

**返回值:**

| 类型              | 说明                                         |
| ----------------- | -------------------------------------------- |
| DataAbilityHelper | 用来协助其他Ability访问DataAbility的工具类。 |

**示例:**

```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) | 是 | 通知参数,用于显示通知栏的信息 |

**返回值:**

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

**示例**

```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

 **参数:**

  | 参数名 | 类型 | 必填 | 说明 |
  | -------- | -------- | -------- | -------- |
  | callback | AsyncCallback&lt;void&gt; | 是 | callback形式返回启动长时任务的结果 |

 **示例**

```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

**返回值:**

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

 **示例**

```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

将当前ability连接到指定ServiceAbility(callback形式)。

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

**参数:**

| 参数名    | 类型           | 必填 | 说明                         |
| ------- | -------------- | ---- | ---------------------------- |
| request | [Want](js-apis-application-want.md)           | 是   | 表示被连接的ServiceAbility。 |
| options | ConnectOptions | 是   | 被指定的回调方法。           |


**ConnectOptions类型说明:**

**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core

D
merge  
donglin 已提交
395 396 397 398 399
| 名称           | 类型       | 必填   | 说明                        |
| ------------ | -------- | ---- | ------------------------- |
| onConnect    | function | 是    | 连接成功时的回调函数。               |
| onDisconnect | function | 是    | 连接失败时的回调函数。               |
| onFailed     | function | 是    | ConnectAbility调用失败时的回调函数。 |
M
m00512953 已提交
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 432 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 482 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 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556

**示例**

```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;

将功能与服务功能断开连接。

**系统能力**: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>;

将功能与服务功能断开连接。

**系统能力**: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

获取错误代码。

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

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