• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.app.ability.Want (Want)
2
3Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When UIAbilityA needs to start UIAbilityB and transfer some data to UIAbilityB, it can use Want a carrier to transfer the data.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8
9## Modules to Import
10
11```ts
12import { Want } from '@kit.AbilityKit';
13```
14
15## Properties
16
17**Atomic service API**: This API can be used in atomic services since API version 11.
18
19**System capability**: SystemCapability.Ability.AbilityBase
20
21| Name       | Type                | Mandatory| Description                                                        |
22| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
23| deviceId    | string               | No  | ID of the device running the ability. If this field is unspecified, the local device is used.                               |
24| bundleName   | string               | No  | Bundle name of the ability.|
25| moduleName | string | No| Name of the module to which the ability belongs.<br>**NOTE**<br>If the ability belongs to a [HAR](../../quick-start/har-package.md) module, **moduleName** must be set to the name of the [HAP](../../quick-start/hap-package.md) or [HSP](../../quick-start/in-app-hsp.md) module that depends on this HAR.|
26| abilityName  | string               | No  | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
27| action | string               | No  | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md).            |
28| entities | Array\<string> | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.|
29| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
30| type | string | No| MIME type, that is, the type of the file to open, for example, **'text/xml'** and **'image/*'**. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.|
31| parameters   | Record\<string, Object> | No  | List of parameters in the **Want** object.<br>1. The values of the following keys are assigned by the system. Manual settings do not take effect, since the system automatically changes the values to the actual values during data transfer.<br>- **ohos.aafwk.param.callerPid**: PID of the caller. The value is a string.<br>- **ohos.aafwk.param.callerBundleName**: bundle name of the caller. The value is a string.<br>- **ohos.aafwk.param.callerAbilityName**: ability name of the caller. The value is a string.<br>- **ohos.aafwk.param.callerNativeName**: process name of the caller when the native method is called. The value is a string.<br>- **ohos.aafwk.param.callerAppId**: appId of the caller. The value is a string.<br>- **ohos.aafwk.param.callerAppIdentifier**: appIdentifier of the caller. The value is a string.<br>- **ohos.aafwk.param.callerToken**: token of the caller. The value is a string.<br>- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application's UID in the bundle information. The value is a number.<br>- **ohos.param.callerAppCloneIndex**: clone index of the caller. The value is of the numeric type.<br>- **component.startup.newRules**: enabled status of the new control rule. The value is of the Boolean type.<br>- **moduleName**: module name of the caller. The value is a string.<br>- **ability.params.backToOtherMissionStack**: support for redirection back across mission stacks. The value is of the Boolean type.<br>- **ohos.ability.params.abilityRecoveryRestart**: support for ability restart upon fault recovery. The value is of the Boolean type.<br>- **ohos.extra.param.key.contentTitle**: title that can be shared by the atomic service. The value is a string.<br>- **ohos.extra.param.key.shareAbstract**: content that can be shared by the atomic service. The value is a string.<br>- **ohos.extra.param.key.shareUrl**: URL of the content that can be shared by the atomic service. The value is a string.<br>- **ohos.extra.param.key.supportContinuePageStack**: support for migration of page stack information during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that page stack information is automatically migrated.<br>- **ohos.extra.param.key.supportContinueSourceExit**: support for application exit on the source device during cross-device migration. The value is of the Boolean type. The default value is **true**, indicating that the application on the source device automatically exits.<br>- **ohos.extra.param.key.showMode**: mode to show the atomic service startup. The value is an enumerated value of [wantConstant.ShowMode](js-apis-app-ability-wantConstant.md#showmode12).<br>- **ohos.dlp.params.sandbox**: available only for DLP files. This key is involved only in system applications.<br>- **ohos.dlp.params.bundleName**: bundle name of DLP. The value is a string. This key is involved only in system applications.<br>- **ohos.dlp.params.moduleName**: module name of DLP. The value is a string. This key is involved only in system applications.<br>- **ohos.dlp.params.abilityName**: ability name of DLP. The value is a string. This key is involved only in system applications.<br>- 	**ohos.dlp.params.index**: DLP index. The value is a number. This key is involved only in system applications.<br>- **ohos.ability.params.asssertFaultSessionId**: session ID of the fault assertion. The value is a string. This key is involved only in system applications.<br><br>2. The following keys are defined by the system, and their values need to be manually assigned.<br>- **ability.params.stream**: File URIs to be authorized to the target ability. The value is a file URI array of the string type.<br>- **ohos.extra.param.key.appCloneIndex**: index of the application clone.<br><br>3. In addition to the foregoing cases, applications may further agree on the key-value pairs to transfer.<br><br>**NOTE**<br>For details about the constants of **Params** in **want**, see [wantConstant](js-apis-app-ability-wantConstant.md).<br>Note that a maximum of 200 KB data that can be transferred by using **WantParams**. If the data volume exceeds 200 KB, transfer data in [WriteRawDataBuffer](../apis-ipc-kit/js-apis-rpc.md#writerawdatabuffer11) or [uri](../apis-arkts/js-apis-uri.md) mode.<br>The values of **parameters** must be of the following basic data types: String, Number, Boolean, Object, undefined, and null. Functions in an object cannot be transferred.|
32| [flags](js-apis-app-ability-wantConstant.md#flags) | number | No| How the **Want** object will be handled. By default, a number is passed in.<br>For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.|
33| fds<sup>15+</sup> | Record\<string, number> | No| Want file descriptor (FD), which is used to identify the Want file opened. You can obtain the FD from [fs.open](../apis-core-file-kit/js-apis-file-fs.md#fsopen). When the FD is no longer needed, you must call [fs.close](../apis-core-file-kit/js-apis-file-fs.md#fsclose) to destroy the FD in a timely manner to prevent FD leakage.<br>**Atomic service API**: This API can be used in atomic services since API version 15.|
34
35**Example**
36
37- Basic usage: called in a UIAbility object, as shown in the example below. For details about how to obtain the context, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability).
38
39  ```ts
40  import { common, Want } from '@kit.AbilityKit';
41  import { BusinessError } from '@kit.BasicServicesKit';
42
43  let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
44  let want: Want = {
45    deviceId: '', // An empty deviceId indicates the local device.
46    bundleName: 'com.example.myapplication',
47    abilityName: 'FuncAbility',
48    moduleName: 'entry' // moduleName is optional.
49  };
50
51  context.startAbility(want, (err: BusinessError) => {
52    if (err.code) {
53      // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
54      console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
55    }
56  });
57  ```
58
59- Currently, the following data types are supported: string, number, Boolean, object, array, and file descriptor (FD).
60
61    * String
62        ```ts
63        import { common, Want } from '@kit.AbilityKit';
64        import { BusinessError } from '@kit.BasicServicesKit';
65
66        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
67        let want: Want = {
68          bundleName: 'com.example.myapplication',
69          abilityName: 'FuncAbility',
70          parameters: {
71            keyForString: 'str',
72          },
73        };
74
75        context.startAbility(want, (err: BusinessError) => {
76          if (err.code) {
77            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
78          }
79        });
80        ```
81    * Number
82        ```ts
83        import { common, Want } from '@kit.AbilityKit';
84
85        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
86        let want: Want = {
87          bundleName: 'com.example.myapplication',
88          abilityName: 'FuncAbility',
89          parameters: {
90            keyForInt: 100,
91            keyForDouble: 99.99,
92          },
93        };
94
95        context.startAbility(want, (err) => {
96          if (err.code) {
97            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
98          }
99        });
100        ```
101    * Boolean
102        ```ts
103        import { common, Want } from '@kit.AbilityKit';
104        import { BusinessError } from '@kit.BasicServicesKit';
105
106        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
107        let want: Want = {
108          bundleName: 'com.example.myapplication',
109          abilityName: 'FuncAbility',
110          parameters: {
111            keyForBool: true,
112          },
113        };
114
115        context.startAbility(want, (err: BusinessError) => {
116          if (err.code) {
117            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
118          }
119        });
120        ```
121    * Object
122        ```ts
123        import { common, Want } from '@kit.AbilityKit';
124        import { BusinessError } from '@kit.BasicServicesKit';
125
126        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
127        let want: Want = {
128          bundleName: 'com.example.myapplication',
129          abilityName: 'FuncAbility',
130          parameters: {
131            keyForObject: {
132              keyForObjectString: 'str',
133              keyForObjectInt: -200,
134              keyForObjectDouble: 35.5,
135              keyForObjectBool: false,
136            },
137          },
138        };
139
140        context.startAbility(want, (err: BusinessError) => {
141          if (err.code) {
142            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
143          }
144        });
145        ```
146    * Array
147
148        ```ts
149        import { common, Want } from '@kit.AbilityKit';
150        import { BusinessError } from '@kit.BasicServicesKit';
151
152        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
153        let want: Want = {
154          bundleName: 'com.example.myapplication',
155          abilityName: 'FuncAbility',
156          parameters: {
157            keyForArrayString: ['str1', 'str2', 'str3'],
158            keyForArrayInt: [100, 200, 300, 400],
159            keyForArrayDouble: [0.1, 0.2],
160            keyForArrayObject: [{ obj1: 'aaa' }, { obj2: 100 }],
161          },
162        };
163
164        context.startAbility(want, (err: BusinessError) => {
165          if (err.code) {
166            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
167          }
168        });
169        ```
170
171    * FD
172
173        ```ts
174        import { fileIo } from '@kit.CoreFileKit';
175        import { common, Want } from '@kit.AbilityKit';
176        import { BusinessError } from '@kit.BasicServicesKit';
177
178        let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
179        let fd: number = 0;
180
181        try {
182          fd = fileIo.openSync('/data/storage/el2/base/haps/pic.png').fd;
183        } catch(err) {
184          let code = (err as BusinessError).code;
185          let message = (err as BusinessError).message;
186          console.error(`Failed to openSync. Code: ${code}, message: ${message}`);
187        }
188        let want: Want = {
189          deviceId: '', // An empty deviceId indicates the local device.
190          bundleName: 'com.example.myapplication',
191          abilityName: 'FuncAbility',
192          moduleName: 'entry', // moduleName is optional.
193          parameters: {
194            'keyFd': { 'type': 'FD', 'value': fd } // {'type':'FD', 'value':fd} is a fixed usage, indicating that the data is a file descriptor.
195          }
196        };
197
198        context.startAbility(want, (err: BusinessError) => {
199          if (err.code) {
200            console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
201          }
202        });
203        ```
204
205- **parameter** usage: **parameter** carries custom parameters. It is transferred by UIAbilityA to UIAbilityB and obtained from UIAbilityB.
206
207    ```ts
208    // (1) UIAbilityA calls startAbility to start UIAbilityB.
209    import { common, Want } from '@kit.AbilityKit';
210    import { BusinessError } from '@kit.BasicServicesKit';
211
212    let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
213    let want: Want = {
214      bundleName: 'com.example.myapplication',
215      abilityName: 'UIAbilityB',
216      parameters: {
217        developerParameters: 'parameters',
218      },
219    };
220
221    context.startAbility(want, (err: BusinessError) => {
222      if (err.code) {
223        console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
224      }
225    });
226    ```
227
228    ```ts
229    // (2) If the UIAbilityB instance is started for the first time, it enters the onCreate lifecycle.
230    import { UIAbility, Want, AbilityConstant } from '@kit.AbilityKit';
231
232    class UIAbilityB extends UIAbility {
233      onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {
234        console.log(`onCreate, want parameters: ${want.parameters?.developerParameters}`);
235      }
236    }
237    ```
238
239- Usage of the keys of [wantConstant](js-apis-app-ability-wantConstant.md) in **parameter**.
240
241    ```ts
242    import { common, Want, wantConstant } from '@kit.AbilityKit';
243    import { BusinessError } from '@kit.BasicServicesKit';
244
245    let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
246    let want: Want = {
247      bundleName: 'com.example.myapplication',
248      abilityName: 'FuncAbility',
249      parameters: {
250        [wantConstant.Params.CONTENT_TITLE_KEY]: 'contentTitle',
251      },
252    };
253
254    context.startAbility(want, (err: BusinessError) => {
255      if (err.code) {
256        console.error(`Failed to startAbility. Code: ${err.code}, message: ${err.message}`);
257      }
258    });
259    ```
260