• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# MediaLibrary Development Overview
2
3The **mediaLibrary** module provides APIs for you to access and modify media files.
4
5- You can manage [media assets (audios, videos, image, and files)](medialibrary-resource-guidelines.md) as follows:
6  - Query media assets.
7  - Obtain an image or a video.
8  - Obtain the thumbnail of an image or a video.
9  - Create a media asset.
10  - Rename a media asset.
11  - Move a media asset to the recycle bin.
12- You can manage [file paths](medialibrary-filepath-guidelines.md) as follows:
13  - Obtain the public directory that stores files of a certain type.
14  - Copy files between the application sandbox and the public directory.
15  - Read and write a file.
16- You can manage [albums](medialibrary-album-guidelines.md) as follows:
17  - Obtain images and videos in an album.
18  - Create an album.
19  - Rename an album.
20
21> **NOTE**
22>
23> This development guide applies only to the stage model (available from API version 9).
24
25To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. Unless otherwise specified, the **MediaLibrary** APIs are used in **pages/index.ets** or custom .ets files of the project code.
26
27Before using the **MediaLibrary** APIs to develop features, you must learn how to:
28
29- [Obtain a MediaLibrary Instance](#obtaining-a-medialibrary-instance)
30- [Request Permissions](#requesting-permissions)
31
32## Obtaining a MediaLibrary Instance
33
34An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) to obtain a **MediaLibrary** instance based on the application context. Through this instance, the application can access and modify personal media data (such as audios, videos, images, and files).
35
36**How to Develop**
37
381. Import the **mediaLibrary** module.
392. Call **getContext** to obtain the application context.
403. Obtain a **MediaLibrary** instance.
41
42```ts
43import mediaLibrary from '@ohos.multimedia.mediaLibrary';
44
45const context = getContext(this);
46let media = mediaLibrary.getMediaLibrary(context);
47```
48
49## Requesting Permissions
50
51To read and write a **MediaLibrary** instance, you must have the required permissions, as described in the table below. Before requesting the permissions, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met.
52
53| Permission                        | Description                                      | Authorization Mode  |
54| ------------------------------ | ------------------------------------------ | ---------- |
55| ohos.permission.READ_MEDIA     | Allows an application to read media files from the user's external storage.| user_grant |
56| ohos.permission.WRITE_MEDIA    | Allows an application to read media files from and write media files into the user's external storage.| user_grant |
57| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant |
58
59After configuring the permissions in the **module.json5** file, the application must call [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
60
61> **NOTE**<br>Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**.
62
63**How to Develop**
64
651. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md).
66
67```json
68{
69  "module": {
70    "requestPermissions": [
71      {
72        "name": "ohos.permission.MEDIA_LOCATION",
73        "reason": "$string:reason",
74        "usedScene": {
75          "abilities": [
76            "EntryAbility"
77          ],
78          "when": "always"
79        }
80      },
81      {
82        "name": "ohos.permission.READ_MEDIA",
83        "reason": "$string:reason",
84        "usedScene": {
85          "abilities": [
86            "EntryAbility"
87          ],
88          "when": "always"
89        }
90      },
91      {
92        "name": "ohos.permission.WRITE_MEDIA",
93        "reason": "$string:reason",
94        "usedScene": {
95          "abilities": [
96            "EntryAbility"
97          ],
98          "when": "always"
99        }
100      }
101    ]
102  }
103}
104```
105
1062. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
107
108```ts
109import UIAbility from '@ohos.app.ability.UIAbility';
110import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
111
112export default class EntryAbility extends UIAbility {
113  onWindowStageCreate(windowStage) {
114    let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
115    let permissionRequestResult;
116    let atManager = abilityAccessCtrl.createAtManager();
117    atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
118      if (err) {
119        console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
120      } else {
121        permissionRequestResult = result;
122        console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
123      }
124    });
125  }
126}
127```
128