medialibrary-overview.md 5.6 KB
Newer Older
G
Gloria 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# MediaLibrary Development Overview

The **mediaLibrary** module provides APIs for you to access and modify media files.

- You can manage [media assets (audios, videos, image, and files)](medialibrary-resource-guidelines.md) as follows:
  - Query media assets.
  - Obtain an image or a video.
  - Obtain the thumbnail of an image or a video.
  - Create a media asset.
  - Rename a media asset.
  - Move a media asset to the recycle bin.
- You can manage [file paths](medialibrary-filepath-guidelines.md) as follows:
  - Obtain the public directory that stores files of a certain type.
  - Copy files between the application sandbox and the public directory.
  - Read and write a file.
- You can manage [albums](medialibrary-album-guidelines.md) as follows:
  - Obtain images and videos in an album.
  - Create an album.
  - Rename an album.

> **NOTE**
>
> This development guide applies only to the stage model (available from API version 9).

25
To 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.
G
Gloria 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

Before using the **MediaLibrary** APIs to develop features, you must learn how to:

- [Obtain a MediaLibrary Instance](#obtaining-a-medialibrary-instance)
- [Request Permissions](#requesting-permissions)

## Obtaining a MediaLibrary Instance

An 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).

**How to Develop**

1. Import the **mediaLibrary** module.
2. Call **getContext** to obtain the application context.
3. Obtain a **MediaLibrary** instance.

```ts
import mediaLibrary from '@ohos.multimedia.mediaLibrary';

const context = getContext(this);
46
let media = mediaLibrary.getMediaLibrary(context);
G
Gloria 已提交
47 48 49 50 51 52 53 54 55 56 57 58
```

## Requesting Permissions

To 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.  

| Permission                        | Description                                      | Authorization Mode  |
| ------------------------------ | ------------------------------------------ | ---------- |
| ohos.permission.READ_MEDIA     | Allows an application to read media files from the user's external storage.| user_grant |
| ohos.permission.WRITE_MEDIA    | Allows an application to read media files from and write media files into the user's external storage.| user_grant |
| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant |

59
After 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.
G
Gloria 已提交
60 61 62 63 64 65 66

> **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**.

**How to Develop**

1. 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).

G
Gloria 已提交
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
```json
{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.MEDIA_LOCATION",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.READ_MEDIA",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.WRITE_MEDIA",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "EntryAbility"
          ],
          "when": "always"
        }
      }
    ]
  }
}    
```
G
Gloria 已提交
105

106
2. 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.
G
Gloria 已提交
107

G
Gloria 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';

export default class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage) {
    let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
    let permissionRequestResult;
    let atManager = abilityAccessCtrl.createAtManager();
    atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
      if (err) {
        console.error('requestPermissionsFromUserError: ' + JSON.stringify(err));
      } else {
        permissionRequestResult = result;
        console.info('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
      }
    });       
  }
}
```