• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.application.uriPermissionManager (URI Permission Management) (System API)
2
3The **uriPermissionManager** module provides capabilities for granting the permission on a file to another application and revoking the granted permissions. The file is identified by a uniform resource identifier (URI).
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8> The APIs of this module are system APIs and cannot be called by third-party applications.
9
10
11## Modules to Import
12
13
14```ts
15import { uriPermissionManager } from '@kit.AbilityKit';
16```
17
18
19## uriPermissionManager.grantUriPermission
20
21grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string, callback: AsyncCallback<number>): void
22
23Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses an asynchronous callback to return the result.
24
25> **NOTE**
26>
27> If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions.
28
29**System API**: This is a system API.
30
31**System capability**: SystemCapability.Ability.AbilityRuntime.Core
32
33**Required permissions**: ohos.permission.PROXY_AUTHORIZATION_URI
34
35**Parameters**
36
37  | Name| Type| Mandatory| Description|
38  | -------- | -------- | -------- | -------- |
39  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
40  | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.|
41  | targetBundleName | string | Yes| Bundle name of the target application.|
42  | callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
43
44**Error codes**
45
46  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
47
48| ID| Error Message|
49| ------- | -------------------------------- |
50| 201 | Permission denied. |
51| 202 | Not System App. Interface caller is not a system app. |
52| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
53| 801 | Capability not supported. |
54| 16000050 | Internal error. |
55| 16000058 | Invalid URI flag. |
56| 16000059 | Invalid URI type. |
57| 16000060 | A sandbox application cannot grant URI permission. |
58
59
60**Example**
61
62  ```ts
63  import { uriPermissionManager, wantConstant } from '@kit.AbilityKit';
64  import { fileIo, fileUri } from '@kit.CoreFileKit';
65
66  let targetBundleName = 'com.example.test_case1'
67  let path = 'file://com.example.test_case1/data/storage/el2/base/haps/entry_test/files/newDir';
68  fileIo.mkdir(path, (err) => {
69    if (err) {
70      console.error(`mkdir failed, err code: ${err.code}, err msg: ${err.message}.`);
71    } else {
72      console.info(`mkdir success.`);
73    }
74  });
75  let uri = fileUri.getUriFromPath(path);
76  uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName,
77    (error) => {
78      if (error && error.code !== 0) {
79        console.error(`grantUriPermission failed, err code: ${error.code}, err msg: ${error.message}.`);
80        return;
81      }
82      console.info(`grantUriPermission success.`);
83    });
84  ```
85
86
87## uriPermissionManager.grantUriPermission
88
89grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string): Promise<number>
90
91Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses a promise to return the result.
92
93> **NOTE**
94>
95> If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions.
96
97**System API**: This is a system API.
98
99**System capability**: SystemCapability.Ability.AbilityRuntime.Core
100
101**Required permissions**: ohos.permission.PROXY_AUTHORIZATION_URI
102
103**Parameters**
104
105  | Name| Type| Mandatory| Description|
106  | -------- | -------- | -------- | -------- |
107  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
108  | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.|
109  | targetBundleName | string | Yes| Bundle name of the target application.|
110
111**Return value**
112
113  | Type| Description|
114  | -------- | -------- |
115  | Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
116
117**Error codes**
118
119  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
120
121  | ID| Error Message|
122  | ------- | -------------------------------- |
123  | 201 | Permission denied. |
124  | 202 | Not System App. Interface caller is not a system app. |
125  | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
126  | 801 | Capability not supported. |
127  | 16000050 | Internal error. |
128  | 16000058 | Invalid URI flag. |
129  | 16000059 | Invalid URI type. |
130  | 16000060 | A sandbox application cannot grant URI permission. |
131
132**Example**
133
134  ```ts
135  import { uriPermissionManager, wantConstant } from '@kit.AbilityKit';
136  import { fileIo, fileUri } from '@kit.CoreFileKit';
137  import { BusinessError } from '@kit.BasicServicesKit';
138
139  let targetBundleName = 'com.example.test_case1'
140  let path = 'file://com.example.test_case1/data/storage/el2/base/haps/entry_test/files/newDir';
141
142  fileIo.mkdir(path, (err) => {
143    if (err) {
144      console.error(`mkdir failed, err code: ${err.code}, err msg: ${err.message}.`);
145    } else {
146      console.info(`mkdir succeed.`);
147    }
148  });
149  let uri = fileUri.getUriFromPath(path);
150  uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName)
151    .then((data) => {
152      console.info(`Verification succeeded, data: ${JSON.stringify(data)}.`);
153    }).catch((err: BusinessError) => {
154    console.error(`Verification failed, err code: ${err.code}, err msg: ${err.message}.`);
155  });
156  ```
157
158## uriPermissionManager.grantUriPermission<sup>14+</sup>
159
160grantUriPermission(uri: string, flag: wantConstant.Flags, targetBundleName: string, appCloneIndex: number): Promise&lt;void&gt;
161
162Grants the URI permission to an application. If the call is successful, the application obtains the permission to access the file specified by the URI. Once the application exits, the permission will be automatically revoked. For details about how to access the file based on the URI, see [Sharing an Application File](../../file-management/share-app-file.md). This API uses a promise to return the result.
163
164> **NOTE**
165>
166>- If an application has the ohos.permission.PROXY_AUTHORIZATION_URI permission, it can grant the accessible URIs of another application. If the application does not have this permission, it can grant only its own URI permissions.
167>- This API can be used to grant URI access permission to a cloned application. You need to specify the application bundle name and index of the cloned application.
168
169**System API**: This is a system API.
170
171**System capability**: SystemCapability.Ability.AbilityRuntime.Core
172
173**Required permissions**: ohos.permission.PROXY_AUTHORIZATION_URI
174
175**Parameters**
176
177  | Name| Type| Mandatory| Description|
178  | -------- | -------- | -------- | -------- |
179  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
180  | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant.|
181  | targetBundleName | string | Yes| Bundle name of the target application.|
182  | appCloneIndex | number | Yes| Index of the cloned application. The value range is [0, 1000]. The value **0** indicates the application itself.|
183
184**Return value**
185
186  | Type| Description|
187  | -------- | -------- |
188  | Promise&lt;void&gt; | Promise that returns no value.|
189
190**Error codes**
191
192  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
193
194  | ID| Error Message|
195  | ------- | -------------------------------- |
196  | 201 | Permission denied. |
197  | 202 | Not System App. Interface caller is not a system app. |
198  | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
199  | 801 | Capability not supported. |
200  | 16000050 | Internal error. |
201  | 16000058 | Invalid URI flag. |
202  | 16000059 | Invalid URI type. |
203  | 16000060 | A sandbox application cannot grant URI permission. |
204  | 16000081 | Failed to obtain the target application information. |
205
206**Example**
207
208  ```ts
209  import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit';
210  import { fileUri } from '@kit.CoreFileKit';
211  import { BusinessError } from '@kit.BasicServicesKit';
212
213  export default class EntryAbility extends UIAbility {
214    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
215    }
216
217    onForeground(): void {
218      let targetBundleName: string = 'com.example.demo1';
219      let filePath: string = this.context.filesDir + "/test.txt";
220      let uri: string = fileUri.getUriFromPath(filePath);
221      // grant uri permission to main application
222      try {
223        let appCloneIndex: number = 0;
224        uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName,
225          appCloneIndex)
226          .then(() => {
227            console.info('grantUriPermission succeeded.');
228          }).catch((error: BusinessError) => {
229          console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`);
230        });
231      } catch (error) {
232        console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`);
233      }
234
235      // grant uri permission to clone application
236      try {
237        let appCloneIndex: number = 1;
238        uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName,
239          appCloneIndex)
240          .then(() => {
241            console.info('grantUriPermission succeeded.');
242          }).catch((error: BusinessError) => {
243          console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`);
244        });
245      } catch (error) {
246        console.error(`grantUriPermission failed. error: ${JSON.stringify(error)}.`);
247      }
248    }
249  }
250
251  ```
252
253## uriPermissionManager.revokeUriPermission
254
255revokeUriPermission(uri: string, targetBundleName: string, callback: AsyncCallback&lt;number&gt;): void
256
257Revokes the URI permission from an application. This API uses an asynchronous callback to return the result.
258
259> **NOTE**
260>
261> This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application.
262
263**System API**: This is a system API.
264
265**System capability**: SystemCapability.Ability.AbilityRuntime.Core
266
267**Parameters**
268
269  | Name| Type| Mandatory| Description|
270  | -------- | -------- | -------- | -------- |
271  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
272  | targetBundleName | string | Yes| Bundle name of the application, from which the permission is revoked.|
273  | callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
274
275**Error codes**
276
277  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
278
279  | ID| Error Message|
280  | ------- | -------------------------------- |
281  | 202 | Not System App. Interface caller is not a system app. |
282  | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
283  | 801 | Capability not supported. |
284  | 16000050 | Internal error. |
285  | 16000059 | Invalid URI type. |
286
287**Example**
288
289  ```ts
290  import { uriPermissionManager } from '@kit.AbilityKit';
291
292  let targetBundleName = 'com.example.test_case2';
293  let uri = "file://com.example.test_case1/data/storage/el2/base/haps/entry_test/files/newDir";
294
295  uriPermissionManager.revokeUriPermission(uri, targetBundleName, (error) => {
296    if (error && error.code !== 0) {
297      console.error("revokeUriPermission failed, error.code = " + error.code);
298      return;
299    }
300    console.info("revokeUriPermission success");
301  });
302  ```
303
304
305## uriPermissionManager.revokeUriPermission
306
307revokeUriPermission(uri: string, targetBundleName: string): Promise&lt;number&gt;
308
309Revokes the URI permission from an application. This API uses a promise to return the result.
310
311> **NOTE**
312>
313> This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application.
314
315**System API**: This is a system API.
316
317**System capability**: SystemCapability.Ability.AbilityRuntime.Core
318
319**Parameters**
320
321  | Name| Type| Mandatory| Description|
322  | -------- | -------- | -------- | -------- |
323  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
324  | targetBundleName | string | Yes| Bundle name of the target application.|
325
326**Return value**
327
328  | Type| Description|
329  | -------- | -------- |
330  | Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, **-1** is returned.|
331
332**Error codes**
333
334  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
335
336  | ID| Error Message|
337  | ------- | -------------------------------- |
338  | 202 | Not System App. Interface caller is not a system app. |
339  | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
340  | 801 | Capability not supported. |
341  | 16000050 | Internal error. |
342  | 16000059 | Invalid URI type. |
343
344
345**Example**
346
347  ```ts
348  import { uriPermissionManager } from '@kit.AbilityKit';
349  import { BusinessError } from '@kit.BasicServicesKit';
350
351  let targetBundleName = 'com.example.test_case2';
352  let uri = 'file://com.example.test_case1/data/storage/el2/base/haps/entry_test/files/newDir';
353
354  uriPermissionManager.revokeUriPermission(uri, targetBundleName)
355    .then((data) => {
356      console.info(`Verification success, data: ${JSON.stringify(data)}.`);
357    }).catch((error: BusinessError) => {
358    console.error(`Verification failed, err code: ${error.code}, err msg: ${error.message}.`);
359  });
360  ```
361## uriPermissionManager.revokeUriPermission<sup>14+</sup>
362
363revokeUriPermission(uri: string, targetBundleName: string, appCloneIndex: number): Promise&lt;void&gt;
364
365Revokes the URI permission from an application. This API uses a promise to return the result.
366
367> **NOTE**
368>
369>- This API can be used to revoke the URI permission of another application obtained by this application or URI permission granted by this application.
370>- This API can be used to revoke the URI permissions granted to a cloned application. You need to specify the application bundle name and index of the cloned application.
371
372**System API**: This is a system API.
373
374**System capability**: SystemCapability.Ability.AbilityRuntime.Core
375
376**Parameters**
377
378  | Name| Type| Mandatory| Description|
379  | -------- | -------- | -------- | -------- |
380  | uri | string | Yes| URI of the file. The scheme has a fixed value of **file**. For details, see [FileUri](../apis-core-file-kit/js-apis-file-fileuri.md#constructor10).|
381  | targetBundleName | string | Yes| Bundle name of the target application.|
382  | appCloneIndex | number | Yes| Index of the cloned application. The value range is [0, 1000]. The value **0** indicates the application itself.|
383
384**Return value**
385
386  | Type| Description|
387  | -------- | -------- |
388  | Promise&lt;void&gt; | Promise that returns no value.|
389
390**Error codes**
391
392  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
393
394  | ID| Error Message|
395  | ------- | -------------------------------- |
396  | 202 | Not System App. Interface caller is not a system app. |
397  | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.|
398  | 801 | Capability not supported. |
399  | 16000050 | Internal error. |
400  | 16000059 | Invalid URI type. |
401  | 16000081 | Failed to obtain the target application information. |
402
403**Example**
404
405  ```ts
406
407  import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit';
408  import { fileUri } from '@kit.CoreFileKit';
409  import { BusinessError } from '@kit.BasicServicesKit';
410
411  export default class EntryAbility extends UIAbility {
412    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
413    }
414
415    onForeground(): void {
416      let targetBundleName: string = 'com.example.demo1';
417      let filePath: string = this.context.filesDir + "/test.txt";
418      let uri: string = fileUri.getUriFromPath(filePath);
419      // revoke uri permission of main application
420      try {
421        let appCloneIndex: number = 0;
422        uriPermissionManager.revokeUriPermission(uri, targetBundleName, appCloneIndex)
423          .then(() => {
424            console.info('revokeUriPermission succeeded.');
425          }).catch((error: BusinessError) => {
426          console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`);
427        });
428      } catch (error) {
429        console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`);
430      }
431
432      // revoke uri permission of clone application
433      try {
434        let appCloneIndex: number = 0;
435        uriPermissionManager.revokeUriPermission(uri, targetBundleName, appCloneIndex)
436          .then(() => {
437            console.info('revokeUriPermission succeeded.');
438          }).catch((error: BusinessError) => {
439          console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`);
440        });
441      } catch (error) {
442        console.error(`revokeUriPermission failed. error: ${JSON.stringify(error)}.`);
443      }
444    }
445  }
446  ```
447
448## uriPermissionManager.grantUriPermissionByKey<sup>20+</sup>
449
450grantUriPermissionByKey(key: string, flag: wantConstant.Flags, targetTokenId: number): Promise&lt;void&gt;
451
452Grants the URI access permission of the current application to the target application through the unique key of the Unified Data Management Framework (UDMF) data. The permission will be revoked after the target application exits. This API uses a promise to return the result.
453
454This API takes effect only on phones, 2-in-1 devices, and tablets.
455
456**System API**: This is a system API.
457
458**System capability**: SystemCapability.Ability.AbilityRuntime.Core
459
460**Parameters**
461
462  | Name| Type| Mandatory| Description|
463  | -------- | -------- | -------- | -------- |
464  | key | string | Yes| Unique key of the target UDMF data. The key must be created by the caller using [unifiedDataChannel.insertData](../apis-arkdata/js-apis-data-unifiedDataChannel.md#unifieddatachannelinsertdata), and the written data must be the URIs of the authorized files.<br>Currently, only the keys of the [UDMF data channels](../apis-arkdata/js-apis-data-unifiedDataChannel.md#intention) of the **SYSTEM_SHARE**, **PICKER**, and **MENU** types are supported. For details about how to create and use a key, see [Sharing Data via Unified Data Channels](../../database/unified-data-channels.md).|
465  | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant. The options are as follows:<br>- **FLAG_AUTH_READ_URI_PERMISSION**: read permission.<br>- **FLAG_AUTH_WRITE_URI_PERMISSION**: write permission.|
466  | targetTokenId  | number  | Yes| Identity of the target application, which can be obtained through [bundleManager.getApplicationInfo](js-apis-bundleManager-sys.md#bundlemanagergetapplicationinfo).|
467
468**Return value**
469
470  | Type| Description|
471  | -------- | -------- |
472  | Promise&lt;void&gt; | Promise that returns no value.|
473
474**Error codes**
475
476  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
477
478  | ID| Error Message|
479  | ------- | -------------------------------- |
480  | 202 | Not System App. Interface caller is not a system app. |
481  | 801 | Capability not supported. |
482  | 16000050 | Internal error. |
483  | 16000058 | Invalid URI flag. |
484  | 16000060 | A sandbox application cannot grant URI permission. |
485  | 16000091 | Failed to get the file URI from the key. |
486  | 16000092 | No permission to authorize the URI. |
487  | 16000094 | The target token ID is invalid. |
488
489**Example**
490
491  ```ts
492  // The bundle name of the API caller is com.example.test.
493  // ExntryAbility.ets
494  import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit';
495  import { BusinessError } from '@kit.BasicServicesKit';
496
497  export default class EntryAbility extends UIAbility {
498    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
499    }
500
501    onForeground(): void {
502      try {
503        // You can generate a key using unifiedDataChannel.insertData.
504        let key: string = 'udmf://SystemShare/com.example.test/ap\\t5kKMYTOSHBh9\\f1@817VnBBvxI[e';
505        // You can obtain targetTokenId by calling bundleManager.getApplicationInfo.
506        // Assume that the obtained targetTokenId is 1001.
507        let targetTokenId: number = 1001;
508        uriPermissionManager.grantUriPermissionByKey(key,
509          wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetTokenId)
510          .then(() => {
511            console.info('grantUriPermissionByKey succeeded.');
512          }).catch((error: BusinessError) => {
513          console.error('grantUriPermissionByKey failed: ' + JSON.stringify(error));
514        });
515      } catch (error) {
516        console.error('grantUriPermissionByKey failed: ' + JSON.stringify(error));
517      }
518    }
519  }
520  ```
521
522## uriPermissionManager.grantUriPermissionByKeyAsCaller<sup>20+</sup>
523
524grantUriPermissionByKeyAsCaller(key: string, flag: wantConstant.Flags, callerTokenId: number, targetTokenId: number): Promise&lt;void&gt;
525
526Grants the URI access permission of the specified application to the target application through the unique key of the Unified Data Management Framework (UDMF) data. The permission will be revoked after the target application exits. This API uses a promise to return the result.
527
528This API takes effect only on phones, 2-in-1 devices, and tablets.
529
530**System API**: This is a system API.
531
532**Required permissions**: ohos.permission.GRANT_URI_PERMISSION_AS_CALLER (available only to system applications)
533
534**System capability**: SystemCapability.Ability.AbilityRuntime.Core
535
536**Parameters**
537
538  | Name| Type| Mandatory| Description|
539  | -------- | -------- | -------- | -------- |
540  | key | string | Yes| Unique key of the target UDMF data. The key must be created by the application (corresponding to **callerTokenId**) through [unifiedDataChannel.insertData](../apis-arkdata/js-apis-data-unifiedDataChannel.md#unifieddatachannelinsertdata), and the written data must be the URIs of the authorized files.<br>Currently, only the keys of the [UDMF data channels](../apis-arkdata/js-apis-data-unifiedDataChannel.md#intention) of the **SYSTEM_SHARE**, **PICKER**, and **MENU** types are supported. For details about how to create and use a key, see [Sharing Data via Unified Data Channels](../../database/unified-data-channels.md).|
541  | flag | [wantConstant.Flags](js-apis-app-ability-wantConstant.md#flags) | Yes| Read or write permission on the file to grant. The options are as follows:<br>- **FLAG_AUTH_READ_URI_PERMISSION**: read permission.<br>- **FLAG_AUTH_WRITE_URI_PERMISSION**: write permission.|
542  | callerTokenId  | number  | Yes| Identity of the caller application. You can obtain the value from the **ohos.aafwk.param.callerToken** field in [want](js-apis-app-ability-want.md).|
543  | targetTokenId  | number  | Yes| Identity of the target application, which can be obtained through [bundleManager.getApplicationInfo](js-apis-bundleManager-sys.md#bundlemanagergetapplicationinfo).|
544
545**Return value**
546
547  | Type| Description|
548  | -------- | -------- |
549  | Promise&lt;void&gt; | Promise that returns no value.|
550
551**Error codes**
552
553  For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md).
554
555  | ID| Error Message|
556  | ------- | -------------------------------- |
557  | 201 | Permission denied. |
558  | 202 | Not System App. Interface caller is not a system app. |
559  | 801 | Capability not supported. |
560  | 16000050 | Internal error. |
561  | 16000058 | Invalid URI flag. |
562  | 16000060 | A sandbox application cannot grant URI permission. |
563  | 16000091 | Failed to get the file URI from the key. |
564  | 16000092 | No permission to authorize the URI. |
565  | 16000093 | The caller token ID is invalid. |
566  | 16000094 | The target token ID is invalid. |
567
568**Example**
569  ```ts
570  // The bundle name of the caller application is com.example.caller.
571  // Index.ets
572  import { common, Want, wantConstant } from '@kit.AbilityKit';
573
574  @Entry
575  @Component
576  struct Index {
577    @State message: string = 'Hello World';
578
579    build() {
580      Row() {
581        Column() {
582          Text(this.message)
583
584          Button('Share File')
585            .onClick(() => {
586              // You can generate a key using unifiedDataChannel.insertData.
587              let udKey: string = 'udmf://SystemShare/com.example.caller/ap\\t5kKMYTOSHBh9\\f1@817VnBBvxI[e';
588              let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
589              let want: Want = {
590                bundleName: 'com.example.test',
591                abilityName: 'EntryAbility',
592                parameters: {
593                  [wantConstant.Params.ABILITY_UNIFIED_DATA_KEY]: udKey
594                }
595              };
596              context.startAbility(want);
597            })
598        }
599      }
600    }
601  }
602  ```
603  ```ts
604  // The bundle name of the API caller is com.example.test.
605  // EntryAbility.ets
606  import { AbilityConstant, UIAbility, Want, wantConstant, uriPermissionManager } from '@kit.AbilityKit';
607  import { BusinessError } from '@kit.BasicServicesKit';
608
609  export default class EntryAbility extends UIAbility {
610    onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
611      let udKey: string = want.parameters?.[wantConstant.Params.ABILITY_UNIFIED_DATA_KEY] as string;
612      let callerTokenId: number = want.parameters?.['ohos.aafwk.param.callerToken'] as number;
613      AppStorage.setOrCreate('udKey', udKey);
614      AppStorage.setOrCreate('callerTokenId', callerTokenId);
615    }
616
617    onForeground(): void {
618      try {
619        let udKey: string = AppStorage.get<string>('udKey') as string;
620        let callerTokenId: number = AppStorage.get<number>('callerTokenId') as number;
621        // You can obtain targetTokenId by calling bundleManager.getApplicationInfo.
622        // Assume that the obtained targetTokenId is 1001.
623        let targetTokenId: number = 1001;
624
625        uriPermissionManager.grantUriPermissionByKeyAsCaller(udKey,
626          wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, callerTokenId, targetTokenId)
627          .then(() => {
628            console.info('grantUriPermissionByKeyAsCaller succeeded.');
629          }).catch((error: BusinessError) => {
630          console.error('grantUriPermissionByKeyAsCaller failed: ' + JSON.stringify(error));
631        });
632      } catch (error) {
633        console.error('grantUriPermissionByKeyAsCaller failed: ' + JSON.stringify(error));
634      }
635    }
636  }
637  ```
638