• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.ability.particleAbility (ParticleAbility)
2
3The **particleAbility** module provides APIs for operating a DataAbility and ServiceAbility. You can use the APIs to start and terminate a ParticleAbility, obtain a **dataAbilityHelper** object, and connect to or disconnect from a ServiceAbility.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> The APIs of this module can be used only in the FA model. In the stage model, use the APIs provided by the [ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) and [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) modules instead.
9
10## Constraints
11
12The ParticleAbility module is used to perform operations on abilities of the Data and Service types.
13
14## Modules to Import
15
16```ts
17import particleAbility from '@ohos.ability.particleAbility';
18```
19
20## particleAbility.startAbility
21
22startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<void>): void
23
24Starts a ParticleAbility. This API uses an asynchronous callback to return the result.
25
26Observe the following when using this API:
27 - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
28 - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
29 - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
30
31**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
32
33**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.startAbility](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability) instead.
34
35**Parameters**
36
37| Name     | Type                                           | Mandatory| Description             |
38| --------- | ----------------------------------------------- | ---- | ----------------- |
39| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes  | Ability to start.|
40| callback  | AsyncCallback\<void>                            | Yes  | Callback used to return the result. |
41
42**Example**
43
44```ts
45import particleAbility from '@ohos.ability.particleAbility';
46import wantConstant from '@ohos.app.ability.wantConstant';
47
48particleAbility.startAbility(
49    {
50        want:
51        {
52            action: 'ohos.want.action.home',
53            entities: ['entity.system.home'],
54            type: 'MIMETYPE',
55            flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
56            deviceId: '',
57            bundleName: 'com.example.Data',
58            abilityName: 'com.example.Data.EntryAbility',
59            uri: ''
60        },
61    },
62    (error, data) => {
63        if (error && error.code !== 0) {
64            console.error(`startAbility fail, error: ${JSON.stringify(error)}`);
65        } else {
66            console.log(`startAbility success, data: ${JSON.stringify(data)}`);
67        }
68    },
69);
70```
71
72## particleAbility.startAbility
73
74startAbility(parameter: StartAbilityParameter): Promise\<void>
75
76Starts a ParticleAbility. This API uses a promise to return the result.
77
78Observe the following when using this API:
79 - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
80 - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
81 - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
82
83**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
84
85**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.startAbility](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartability-1) instead.
86
87**Parameters**
88
89| Name     | Type                                           | Mandatory| Description             |
90| --------- | ----------------------------------------------- | ---- | ----------------- |
91| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes  | Ability to start.|
92
93**Return value**
94
95| Type          | Description                     |
96| -------------- | ------------------------- |
97| Promise\<void> | Promise used to return the result. Promise that returns no value.|
98
99**Example**
100
101```ts
102import particleAbility from '@ohos.ability.particleAbility';
103import wantConstant from '@ohos.app.ability.wantConstant';
104
105particleAbility.startAbility(
106    {
107        want:
108        {
109            action: 'ohos.want.action.home',
110            entities: ['entity.system.home'],
111            type: 'MIMETYPE',
112            flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION,
113            deviceId: '',
114            bundleName: 'com.example.Data',
115            abilityName: 'com.example.Data.EntryAbility',
116            uri: ''
117        },
118    },
119).then(() => {
120    console.info('particleAbility startAbility');
121});
122```
123
124## particleAbility.terminateSelf
125
126terminateSelf(callback: AsyncCallback\<void>): void
127
128Terminates this ParticleAbility. This API uses an asynchronous callback to return the result.
129
130**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
131
132**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.terminateSelf](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself) instead.
133
134**Parameters**
135
136| Name    | Type                | Mandatory| Description                |
137| -------- | -------------------- | ---- | -------------------- |
138| callback | AsyncCallback\<void> | Yes  | Callback used to return the result.|
139
140**Example**
141
142```ts
143import particleAbility from '@ohos.ability.particleAbility';
144
145particleAbility.terminateSelf(
146    (error) => {
147        if (error && error.code !== 0) {
148            console.error(`terminateSelf fail, error: ${JSON.stringify(error)}`);
149        }
150    }
151);
152```
153
154## particleAbility.terminateSelf
155
156terminateSelf(): Promise\<void>
157
158Terminates this ParticleAbility. This API uses a promise to return the result.
159
160**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
161
162**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.terminateSelf](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself-1) instead.
163
164**Return value**
165
166| Type          | Description                     |
167| -------------- | ------------------------- |
168| Promise\<void> | Promise used to return the result. Promise that returns no value.|
169
170**Example**
171
172```ts
173import particleAbility from '@ohos.ability.particleAbility';
174
175particleAbility.terminateSelf().then(() => {
176	console.info('particleAbility terminateSelf');
177});
178```
179
180
181
182## particleAbility.acquireDataAbilityHelper
183
184acquireDataAbilityHelper(uri: string): DataAbilityHelper
185
186Obtains a **dataAbilityHelper** object.
187
188Observe the following when using this API:
189 - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).
190 - If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. (Applications developed using the SDK of API version 8 or earlier are not restricted by this restriction when accessing the DataAbility.)
191 - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
192 - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
193
194**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
195
196**Note**: This API can be used only in the FA model. In the stage model, use [dataShare.createDataShareHelper](js-apis-data-dataShare.md#datasharecreatedatasharehelper) instead.
197
198**Parameters**
199
200| Name| Type  | Mandatory| Description                    |
201| :--- | ------ | ---- | ------------------------ |
202| uri  | string | Yes  | URI of the file to open.|
203
204**Return value**
205
206| Type             | Description                                        |
207| ----------------- | -------------------------------------------- |
208| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access a DataAbility.|
209
210**Example**
211
212```ts
213import particleAbility from '@ohos.ability.particleAbility';
214
215let uri = '';
216particleAbility.acquireDataAbilityHelper(uri);
217```
218
219
220## particleAbility.startBackgroundRunning<sup>(deprecated)</sup>
221
222startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback&lt;void&gt;): void
223
224Requests a continuous task from the system. This API uses an asynchronous callback to return the result.
225
226**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
227
228**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
229
230**Note**: This API can be used only in the FA model. In the stage model, use [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8) instead.
231
232**Parameters**
233
234| Name| Type| Mandatory| Description|
235| -------- | -------- | -------- | -------- |
236| id | number | Yes| Notification ID of a continuous task.|
237| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | Yes| Notification parameter, which is used to display information in the notification bar.|
238| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
239
240 **Example**
241
242```ts
243import notification from '@ohos.notificationManager';
244import particleAbility from '@ohos.ability.particleAbility';
245import wantAgent from '@ohos.app.ability.wantAgent';
246import { BusinessError } from '@ohos.base';
247
248function callback(error: BusinessError, data: void) {
249    if (error && error.code !== 0) {
250        console.error(`Operation failed error: ${JSON.stringify(error)}`);
251    } else {
252        console.info(`Operation succeeded, data: ${data}`);
253    }
254}
255
256let wantAgentInfo: wantAgent.WantAgentInfo = {
257    wants: [
258        {
259            bundleName: 'com.example.myapplication',
260            abilityName: 'EntryAbility'
261        }
262    ],
263    operationType: wantAgent.OperationType.START_ABILITY,
264    requestCode: 0,
265    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
266};
267
268wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
269    let id = 1;
270    particleAbility.startBackgroundRunning(id, {
271        content:
272        {
273            contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
274            normal:
275            {
276                title: 'title',
277                text: 'text'
278            }
279        },
280        wantAgent: wantAgentObj
281    }, callback);
282});
283
284```
285
286## particleAbility.startBackgroundRunning<sup>(deprecated)</sup>
287
288startBackgroundRunning(id: number, request: NotificationRequest): Promise&lt;void&gt;
289
290Requests a continuous task from the system. This API uses a promise to return the result.
291
292**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
293
294**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
295
296**Note**: This API can be used only in the FA model. In the stage model, use [backgroundTaskManager.startBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstartbackgroundrunning8-1) instead.
297
298**Parameters**
299
300| Name| Type| Mandatory| Description|
301| -------- | -------- | -------- | -------- |
302| id | number | Yes| Notification ID of a continuous task.|
303| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | Yes| Notification parameter, which is used to display information in the notification bar.|
304
305**Return value**
306
307| Type          | Description                     |
308| -------------- | ------------------------- |
309| Promise\<void> | Promise used to return the result. Promise that returns no value.|
310
311**Example**
312
313```ts
314import notification from '@ohos.notificationManager';
315import particleAbility from '@ohos.ability.particleAbility';
316import wantAgent from '@ohos.app.ability.wantAgent';
317import { BusinessError } from '@ohos.base';
318
319let wantAgentInfo: wantAgent.WantAgentInfo = {
320    wants: [
321        {
322            bundleName: 'com.example.myapplication',
323            abilityName: 'EntryAbility'
324        }
325    ],
326    operationType: wantAgent.OperationType.START_ABILITY,
327    requestCode: 0,
328    wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
329};
330
331wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
332    let id = 1;
333    particleAbility.startBackgroundRunning(id, {
334        content:
335        {
336            contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
337            normal:
338            {
339                title: 'title',
340                text: 'text'
341            }
342        },
343        wantAgent: wantAgentObj
344    }).then(() => {
345        console.info('Operation succeeded');
346    }).catch((err: BusinessError) => {
347        console.error(`Operation failed cause: ${JSON.stringify(err)}`);
348    });
349});
350
351```
352
353## particleAbility.cancelBackgroundRunning<sup>(deprecated)</sup>
354
355cancelBackgroundRunning(callback: AsyncCallback&lt;void&gt;): void
356
357Requests to cancel a continuous task from the system. This API uses an asynchronous callback to return the result.
358
359**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
360
361**Note**: This API can be used only in the FA model. In the stage model, use [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8) instead.
362
363 **Parameters**
364
365| Name| Type| Mandatory| Description|
366| -------- | -------- | -------- | -------- |
367| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
368
369 **Example**
370
371```ts
372import particleAbility from '@ohos.ability.particleAbility';
373import { BusinessError } from '@ohos.base';
374
375function callback(error: BusinessError, data: void) {
376    if (error && error.code !== 0) {
377        console.error(`Operation failed error: ${JSON.stringify(error)}`);
378    } else {
379        console.info(`Operation succeeded, data: ${data}`);
380    }
381}
382
383particleAbility.cancelBackgroundRunning(callback);
384
385```
386
387## particleAbility.cancelBackgroundRunning<sup>(deprecated)</sup>
388
389cancelBackgroundRunning(): Promise&lt;void&gt;
390
391Requests to cancel a continuous task from the system. This API uses a promise to return the result.
392
393**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
394
395**Note**: This API can be used only in the FA model. In the stage model, use [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1) instead.
396
397**Return value**
398
399| Type          | Description                     |
400| -------------- | ------------------------- |
401| Promise\<void> | Promise used to return the result. Promise that returns no value.|
402
403 **Example**
404
405```ts
406import particleAbility from '@ohos.ability.particleAbility';
407import { BusinessError } from '@ohos.base';
408
409particleAbility.cancelBackgroundRunning().then(() => {
410    console.info('Operation succeeded');
411}).catch((err: BusinessError) => {
412    console.error(`Operation failed cause: ${JSON.stringify(err)}`);
413});
414
415```
416
417## particleAbility.connectAbility
418
419connectAbility(request: Want, options:ConnectOptions): number
420
421Connects this ability to a specific ServiceAbility.
422
423Observe the following when using this API:
424 - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**)..
425 - If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. (Applications developed using the SDK of API version 8 or earlier are not restricted by this restriction when connecting to the ServiceAbility.)
426 - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
427 - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md).
428
429**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
430
431**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.connectServiceExtensionAbility](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextconnectserviceextensionability) instead.
432
433**Parameters**
434
435| Name   | Type          | Mandatory| Description                        |
436| ------- | -------------- | ---- | ---------------------------- |
437| request | [Want](js-apis-application-want.md)           | Yes  | ServiceAbility to connect.|
438| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes  | Connection options.          |
439
440**Return value**
441
442| Type    | Description                  |
443| ------ | -------------------- |
444| number | ID of the connected ServiceAbility. The ID starts from 0 and is incremented by 1 each time a connection is set up.|
445
446**Example**
447
448```ts
449import particleAbility from '@ohos.ability.particleAbility';
450import rpc from '@ohos.rpc';
451import { BusinessError } from '@ohos.base';
452
453let connId = particleAbility.connectAbility(
454    {
455        bundleName: 'com.ix.ServiceAbility',
456        abilityName: 'ServiceAbilityA',
457    },
458    {
459        onConnect: (element, remote) => {
460            console.log(`ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}`);
461        },
462        onDisconnect: (element) => {
463            console.log(`ConnectAbility onDisconnect element.deviceId: ${element.deviceId}`);
464        },
465        onFailed: (code) => {
466            console.error(`particleAbilityTest ConnectAbility onFailed errCode: ${code}`);
467        },
468    },
469);
470
471particleAbility.disconnectAbility(connId).then((data) => {
472    console.log(`data: ${data}`);
473}).catch((error: BusinessError) => {
474    console.error(`particleAbilityTest result errCode: ${error.code}`);
475});
476```
477
478## particleAbility.disconnectAbility
479
480disconnectAbility(connection: number, callback:AsyncCallback\<void>): void
481
482Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result.
483
484**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
485
486**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.disconnectServiceExtensionAbility](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability) instead.
487
488**Parameters**
489
490| Name| Type| Mandatory| Description|
491| -------- | -------- | -------- | -------- |
492| connection | number               | Yes   | ID of the ServiceAbility to disconnect.|
493| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
494
495**Example**
496
497```ts
498import particleAbility from '@ohos.ability.particleAbility';
499import rpc from '@ohos.rpc';
500
501let connId = particleAbility.connectAbility(
502    {
503        bundleName: 'com.ix.ServiceAbility',
504        abilityName: 'ServiceAbilityA',
505    },
506    {
507        onConnect: (element, remote) => {
508            console.log(`ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}`);
509        },
510        onDisconnect: (element) => {
511            console.log(`ConnectAbility onDisconnect element.deviceId: ${element.deviceId}`);
512        },
513        onFailed: (code) => {
514            console.error(`particleAbilityTest ConnectAbility onFailed errCode: ${code}`);
515        },
516    },
517);
518
519particleAbility.disconnectAbility(connId, (err) => {
520    console.error(`particleAbilityTest disconnectAbility err: ${JSON.stringify(err)}`);
521});
522```
523
524
525## particleAbility.disconnectAbility
526
527disconnectAbility(connection: number): Promise\<void>
528
529Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result.
530
531**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel
532
533**Note**: This API can be used only in the FA model. In the stage model, use [ServiceExtensionContext.disconnectServiceExtensionAbility](js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextdisconnectserviceextensionability-1) instead.
534
535**Return value**
536
537| Type          | Description                     |
538| -------------- | ------------------------- |
539| connection | number               | Yes   | ID of the ServiceAbility to disconnect.|
540| Promise\<void> | Promise used to return the result. Promise that returns no value.|
541
542**Example**
543
544```ts
545import particleAbility from '@ohos.ability.particleAbility';
546import rpc from '@ohos.rpc';
547import { BusinessError } from '@ohos.base';
548
549let connId = particleAbility.connectAbility(
550    {
551        bundleName: 'com.ix.ServiceAbility',
552        abilityName: 'ServiceAbilityA',
553    },
554    {
555        onConnect: (element, remote) => {
556            console.log(`ConnectAbility onConnect remote is proxy: ${(remote instanceof rpc.RemoteProxy)}`);
557        },
558        onDisconnect: (element) => {
559            console.log(`ConnectAbility onDisconnect element.deviceId: ${element.deviceId}`);
560        },
561        onFailed: (code) => {
562            console.error(`particleAbilityTest ConnectAbility onFailed errCode: ${code}`);
563        },
564    },
565);
566
567particleAbility.disconnectAbility(connId).then(() => {
568    console.log('disconnectAbility success');
569}).catch((error: BusinessError) => {
570    console.error(`particleAbilityTest result errCode : ${error.code}`);
571});
572```
573## ErrorCode
574
575Enumerates the error codes that may be returned when an ability is started.
576
577**System capability**: SystemCapability.Ability.AbilityRuntime.Core
578
579| Name                            | Value   | Description                                      |
580| ------------------------------ | ---- | ---------------------------------------- |
581| INVALID_PARAMETER | -1   | Invalid parameter.|
582