提交 6bcd828d 编写于 作者: S sienna1128

Merge branch 'master' of https://gitee.com/openharmony/docs into docs/1114

此差异已折叠。
...@@ -18,15 +18,15 @@ ...@@ -18,15 +18,15 @@
- master:最新开发版本。 - master:最新开发版本。
- OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。 版本已更新至OpenHarmony 3.1.3 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.3-release.md)了解版本详情。
- OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。
该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。 该版本已更新至OpenHarmony 3.0.6 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md)了解版本详情。
- OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。
...@@ -34,7 +34,7 @@ ...@@ -34,7 +34,7 @@
### 历史稳定版本 ### 历史稳定版本
OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md)了解版本详情。 OpenHarmony_v1.x_release:OpenHarmony 1.1.5 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md)了解版本详情。
如需了解更多版本详情,点击[此处](zh-cn/release-notes/) 如需了解更多版本详情,点击[此处](zh-cn/release-notes/)
......
# Legal Notices
**Copyright (c) 2020-2022 OpenAtom OpenHarmony. All rights reserved.**
## Copyright
All copyrights of the OpenHarmony documents are reserved by OpenAtom OpenHarmony.
The OpenHarmony documents are licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). For easier understanding, you can visit [Creative Commons](https://creativecommons.org/licenses/by/4.0/) to get a human-readable summary of the license. For the complete content, see [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode).
## Trademarks and Permissions
No content provided in the OpenHarmony documentation shall be deemed as a grant of the approval or right to use any trademark, name, or logo of the OpenAtom Foundation and OpenAtom OpenHarmony. No third parties shall use any of the aforementioned trademarks, names, or logos in any way without explicit prior written permission of the OpenAtom Foundation.
## Disclaimer
The information in the OpenHarmony documents is subject to change without notice.
The OpenHarmony documents are provided without any express or implied warranty. In any case, the OpenAtom Foundation or the copyright owner is not liable for any direct or indirect loss arising from the use of the OpenHarmony documents, regardless of the cause or legal theory, even if the OpenHarmony documents have stated that there is a possibility of such loss.
<!--no_check-->
\ No newline at end of file
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [SysCap](quick-start/syscap.md) - [SysCap](quick-start/syscap.md)
- [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md) - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md)
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
...@@ -26,6 +27,7 @@ ...@@ -26,6 +27,7 @@
- [Security](security/Readme-EN.md) - [Security](security/Readme-EN.md)
- [Connectivity](connectivity/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md)
- [Data Management](database/Readme-EN.md) - [Data Management](database/Readme-EN.md)
- [File Management](file-management/Readme-EN.md)
- [Telephony](telephony/Readme-EN.md) - [Telephony](telephony/Readme-EN.md)
- [Task Management](task-management/Readme-EN.md) - [Task Management](task-management/Readme-EN.md)
- [Device Management](device/Readme-EN.md) - [Device Management](device/Readme-EN.md)
......
...@@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
| Class/Interface | Function | Description | | Class/Interface | Function | Description |
| --------------- | -------- | ----------- | | --------------- | -------- | ----------- |
| IRemoteBroker | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | | [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
| IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
| IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
...@@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
``` ```
class ITestAbility : public IRemoteBroker { class ITestAbility : public IRemoteBroker {
public: public:
// DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string.
DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility");
int TRANS_ID_PING_ABILITY = 1; // Define the message code. int TRANS_ID_PING_ABILITY = 1; // Define the message code.
virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions.
}; };
``` ```
......
...@@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background.
To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
```
{
"module": {
"reqPermissions": [
"name": "ohos.permission.LOCATION",
"reason": "$string:reason_description",
"usedScene": {
"ability": ["com.myapplication.LocationAbility"],
"when": "inuse"
}
]
}
}
```
For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities.
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
The sample server provides a package search server for checking update packages and obtaining the update package download URLs, which was previously unavailable in the real-world update service. The sample server supports update service testing and secondary development function verification, building an end-to-end environment to cater for diverse update service use cases. The sample server provides a package search server for checking update packages and obtaining the update package download URLs, which was previously unavailable in the real-world update service. The sample server supports update service testing and functional verification for secondary development, building an end-to-end environment to cater for diverse update service use cases.
## How to Develop ## How to Develop
...@@ -14,8 +14,6 @@ The sample server provides a package search server for checking update packages ...@@ -14,8 +14,6 @@ The sample server provides a package search server for checking update packages
openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com" openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com"
``` ```
2. Modify the **bundle.json** file. 2. Modify the **bundle.json** file.
Add **sub_component** to the **build** field. Add **sub_component** to the **build** field.
...@@ -32,13 +30,13 @@ The sample server provides a package search server for checking update packages ...@@ -32,13 +30,13 @@ The sample server provides a package search server for checking update packages
Go to the **update_updateservice** directory and run the following commands to create a code directory: Go to the **update_updateservice** directory and run the following commands to create a code directory:
``` ```
mkdir server_sample // Create the server_sample folder. mkdir server_sample // Create the server_sample folder.
touch server_sample/BUILD.gn // Create the BUILD.gn file. touch server_sample/BUILD.gn // Create the BUILD.gn file.
mkdir server_sample/include // Create the include folder to store the header file of the sample server. mkdir server_sample/include // Create the include folder to store the header file of the sample server.
touch server_process.h // Create the server_process.h header file. touch server_process.h // Create the server_process.h header file.
mkdir server_sample/src // Create the src folder to store the C/C++ files of the sample server. mkdir server_sample/src // Create the src folder to store the C/C++ files of the sample server.
touch server_sample/src/server_process.c // Create the server_process.c file. touch server_sample/src/server_process.c // Create the server_process.c file.
touch server_sample/src/main.cpp // Create the main.cpp file. touch server_sample/src/main.cpp // Create the main.cpp file.
``` ```
4. Write the **BUILD.gn** file. 4. Write the **BUILD.gn** file.
......
# File Management
- MediaLibrary Management
- [MediaLibrary Overview](medialibrary-overview.md)
- [Media Asset Management](medialibrary-resource-guidelines.md)
- [File Path Management](medialibrary-filepath-guidelines.md)
- [Album Management](medialibrary-album-guidelines.md)
\ No newline at end of file
# Album Management
You can use the APIs provided by the **mediaLibrary** module to create and delete an album and obtain images in the album.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## Obtaining Images and Videos in an Album
You can obtain images and videos in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines#obtaining-images-and-videos-in-an-album).
## Creating an Album
You can use [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1), with the relative path set, to create an album while adding a media asset to the album. The relative path is the album name.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to create an album named **myAlbum**.
**How to Develop**
1. Call **getPublicDirectory** to obtain the public directory that stores files of a certain type.
For details about the operation, see [Obtaining a Public Directory](medialibrary-filepath-guidelines.md#obtaining-a-public-directory).
2. Call **createAsset** to create an image, with the relative path set to **path + 'myAlbum/'**.
This operation creates an album and adds an image to it.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE)
// myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) {
console.info('createAlbum successfully, message = ' + fileAsset);
} else {
console.info('createAlbum failed, message = ' + err);
}
});
}
```
## Renaming an Album
Renaming modifies the **FileAsset.albumName** attribute of the album, that is, the album name. After the modification, call [Album.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-3) to commit the modification to the database.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the album **newAlbum**.
**How to Develop**
1. Create a retrieval condition for obtaining the target album.
2. Call **getAlbums** to obtain the album list.
3. Rename the album **newAlbum**.
4. Call **Album.commitModify** to commit the modification of the attributes to the database.
```ts
async function example() {
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0];
album.albumName = 'newAlbum';
// Void callback.
album.commitModify().then(function() {
console.info("albumRename successfully");
}).catch(function(err){
console.info("albumRename failed with error:"+ err);
});
}
```
# File Path Management
User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## File Formats Supported by Public Directories
Before using file paths for development, learn the file formats supported by each public directory.
> **CAUTION**
>
> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces. <br> For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding.
| Directory | Directory Type | Media Type | Description | Supported File Format |
| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ |
| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif |
| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg |
| Documents/ | DIR_DOCUMENTS | FILE |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| - |
| Download/ | DIR_DOWNLOAD | ALLTYPE |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| - |
## Obtaining a Public Directory
Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
The following describes how to obtain the public directory that stores camera files.
```ts
async function example(){
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed');
} else {
console.info('mediaLibraryTest : getPublicDirectory failed');
}
}
```
## Copying Files Between the Application Sandbox and the Public Directory
OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information.
Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself.
### Copying a File
You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory.
You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop**
1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory.
5. Call **fileio.copyfile** to copy the file.
6. Call **fileAsset.close** and **fileio.close** to close the file.
**Example 1: Copying Files from the Public Directory to the Sandbox**
```ts
async function copyPublic2Sandbox() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let fileKeyObj = mediaLibrary.FileKey
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
let fdPub = await fileAsset.open('rw');
let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666);
await fileio.copyFile(fdPub, fdSand);
await fileAsset.close(fdPub);
await fileio.close(fdSand);
let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt');
console.log('content read from sandbox file: ', content_sand)
}
```
**Example 2: Copying a File from the Sandbox to the Public Directory**
```ts
async function copySandbox2Public() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS);
try {
let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath);
console.info('createFile successfully, message = ' + fileAsset);
} catch (err) {
console.info('createFile failed, message = ' + err);
}
try {
let fileKeyObj = mediaLibrary.FileKey
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile02.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject();
} catch (err) {
console.info('file asset get failed, message = ', err)
}
var fdPub = await fileAsset.open('rw');
var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
await fileio.copyFile(fdSand, fdPub);
await fileio.close(fdPub);
await fileio.close(fdSand);
let fdPubRead = await fileAsset.open('rw');
try {
var arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead);
} catch (err) {
console.log('read text failed, message = ', err);
}
console.log('content read from public file: ', content_pub);
}
```
### Reading and Writing a File
You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary.
**How to Develop**
1. Create a file.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) {
console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch(function(err){
console.info("createAsset failed with error:"+ err);
});
}
```
2. Call **FileAsset.open** to open the file.
3. Call **fileio.write** to write a string to the file.
4. Call **fileio.read** to read the file and save the data read in an array buffer.
5. Convert the array buffer to a string.
6. Use **FileAsset.close** to close the file.
**Example 1: Opening an Existing File and Writing Data to It**
```ts
async function writeOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName);
try {
let fd = await fileAsset.open('w');
console.info('file descriptor: ', fd);
await fileio.write(fd, "Write file test content.");
await fileAsset.close(fd);
} catch (err) {
console.info('write file failed, message = ', err);
}
}
```
**Example 2: Opening an Existing File and Reading Data from It**
```ts
async function readOnlyPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey
let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'],
};
let fetchResult = await media.getFileAssets(fileAssetFetchOp);
let fileAsset = await fetchResult.getFirstObject();
console.info('fileAssetName: ', fileAsset.displayName);
try {
let fd = await fileAsset.open('r');
let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent
globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent);
await fileAsset.close(fd);
} catch (err) {
console.info('read file failed, message = ', err);
}
}
```
# 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).
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.
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);
var media = mediaLibrary.getMediaLibrary(context);
```
## 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 |
After configuring the permissions in the **module.json5** file, the application must call [Context.requestPermissionsFromUser](../reference/apis/js-apis-ability-context.md#abilitycontextrequestpermissionsfromuser) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
> **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).
```json
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.MEDIA_LOCATION",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.READ_MEDIA",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "always"
}
},
{
"name": "ohos.permission.WRITE_MEDIA",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"MainAbility"
],
"when": "always"
}
}
]
}
}
```
2. Call **requestPermissionsFromUser** to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts
import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA']
var permissionRequestResult;
this.context.requestPermissionsFromUser(permissions,(err,result) => {
if(err){
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err));
}else{
permissionRequestResult=result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
}
});
}
}
```
# Media Asset Management
Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files.
> **NOTE**
>
> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
## Querying Media Assets
You can query media assets by condition such as the media type, date, or album name.
To do so, call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1), with a **MediaFetchOptions** object passed in to specify the conditions. In this object, **MediaFetchOptions.selections** are the retrieval conditions, and the enumerated values of **FileKey** are used as the column names of the conditions; **MediaFetchOptions.selectionArgs** are the values of the conditions. You can also specify **order** (sorting mode of the search result), **uri** (file URI), and **networkId** (network ID of the registered device) as the conditions.
To obtain the object at the specified position (for example, the first, the last, or with the specified index) in the result set, call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7). In this section, **getNextObject** is used cyclically to obtain all media assets in the result set.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
### Querying Media Assets with the Specified Media Type
The following describes how to obtain images.
**How to Develop**
To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**.
To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
})
}
}
```
### Querying Media Assets with the Specified Date
The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions.
To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let option = {
selections: fileKeyObj.DATE_ADDED + '= ?',
selectionArgs: ['2022-8-5'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
})
}
}
```
### Querying Media Assets and Sorting Them
The following describes how to query images and sort them in descending order by the date when they are added. You can also sort them in ascending order.
To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
})
}
}
```
### Querying Media Assets with the Specified Album Name
The following describes how to query media assets in **myAlbum**.
To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**.
To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.IMAGE
let option = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs: ['myAlbum'],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
})
}
}
```
## Obtaining Images and Videos in an Album
You can obtain media assets in an album in either of the following ways:
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name).
- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
**How to Develop**
The following describes how to obtain videos in an album named **New Album 1**.
1. Create a retrieval condition for obtaining the target **Album** instance.
```ts
let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1']
}
```
2. Create a retrieval condition for obtaining videos in the target album.
```ts
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.VIDEO;
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
}
```
3. Call **Album.getFileAssets** to obtain the videos in the target album.
Complete sample code:
```ts
async function getCameraImagePromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
}
let AlbumNoArgsFetchOp = {
selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs:['New Album 1']
}
let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
if (albumList.length > 0) {
const album = albumList[0];
let fetchFileResult = await album.getFileAssets(imagesFetchOp);
let count = fetchFileResult.getCount();
console.info("get mediaLibrary IMAGE number", count);
} else {
console.info('getAlbum list is: 0');
}
}
```
## Obtaining the Thumbnail of an Image or a Video
You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Thumbnails are usually displayed on the UI.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.
### Obtaining the Thumbnail of an Image
Your application may need to obtain the thumbnail of an image for preview purposes.
The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **getThumbnail** to obtain the thumbnail of the first image.
```ts
async function getFirstThumbnailPromise() {
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
}
let size = { width: 720, height: 720 };
const fetchFileResult = await media.getFileAssets(imagesFetchOp);
if (fetchFileResult != undefined) {
const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size).then((pixelMap) => {
pixelMap.getImageInfo().then((info) => {
console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
}).catch((err) => {
console.info("getImageInfo failed with error:" + err);
});
}).catch((err) => {
console.info("getImageInfo failed with error:" + err);
});
} else {
console.info("get image failed with error");
}
}
```
## Creating a Media Asset
You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
- [Obtain the public directory](medialibrary-filepath-guidelines.md).
The following describes how to create a file of the **MediaType.FILE** type.
```ts
async function example() {
let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset));
}).catch((err) => {
console.info("createAsset failed with error:"+ err);
});
}
```
## Moving a Media Asset to the Recycle Bin
You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin.
By default, files in the recycle bin will be stored for 30 days. During this period, you can set **isTrash** in **trash** to **false** to recover the files from the recycle bin. Application users can also recover the files through the system applications **Files** or **Gallery**.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to move the first file in the result set to the recycle bin.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **trash** to move the first image to the recycle bin.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
}
// Void callback.
asset.trash(true).then(() => {
console.info("trash successfully");
}).catch((err) => {
console.info("trash failed with error:"+ err);
});
}
```
## Renaming a Media Asset
Renaming modifies the **FileAsset.displayName** attribute of a file, that is, the displayed file name, including the file name extension.
After the modification, call [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1) to commit the modification to the database.
Before renaming a file, you must call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7) to obtain the file.
**Prerequisites**
- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
The following describes how to rename the first file in the result set as **newtitle.text**.
**How to Develop**
1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Rename the image as **newImage.jpg**.
5. Call **FileAsset.commitModify** to commit the modification of the attributes to the database.
```ts
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let fileType = mediaLibrary.MediaType.FILE
let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
};
const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) {
console.error('asset not exist')
return
}
asset.displayName = 'newImage.jpg';
// Void callback.
asset.commitModify((err) => {
if (err) {
console.error('fileRename Failed ');
return;
}
console.log('fileRename successful.');
})
}
```
# Rendering Control
ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration.
## Conditional Rendering
Use **if/else** for conditional rendering.
> **NOTE**
>
> - State variables can be used in the **if/else** statement.
>
> - The **if/else** statement can be used to implement rendering of child components.
>
> - The **if/else** statement must be used in container components.
>
> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\<Grid>** container component, whose child components can only be **\<GridItem>**, only the **\<GridItem>** component can be used in the **if/else** statement.
```ts
Column() {
if (this.count < 0) {
Text('count is negative').fontSize(14)
} else if (this.count % 2 === 0) {
Text('count is even').fontSize(14)
} else {
Text('count is odd').fontSize(14)
}
}
```
## Loop Rendering
You can use **ForEach** to obtain data from arrays and create components for each data item.
```
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
keyGenerator?: (item: any, index?: number) => string
)
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.|
> **NOTE**
>
> - **ForEach** must be used in container components.
>
> - The generated child components should be allowed in the parent container component of **ForEach**.
>
> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
## Example
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State arr: number[] = [10, 20, 30]
build() {
Column({ space: 5 }) {
Button('Reverse Array')
.onClick(() => {
this.arr.reverse()
})
ForEach(this.arr, (item: number) => {
Text(`item value: ${item}`).fontSize(18)
Divider().strokeWidth(2)
}, (item: number) => item.toString())
}
}
}
```
![forEach1](figures/forEach1.gif)
## Lazy Loading
You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration.
```ts
LazyForEach(
dataSource: IDataSource,
itemGenerator: (item: any) => void,
keyGenerator?: (item: any) => string
): void
interface IDataSource {
totalCount(): number;
getData(index: number): any;
registerDataChangeListener(listener: DataChangeListener): void;
unregisterDataChangeListener(listener: DataChangeListener): void;
}
interface DataChangeListener {
onDataReloaded(): void;
onDataAdd(index: number): void;
onDataMove(from: number, to: number): void;
onDataDelete(index: number): void;
onDataChange(index: number): void;
}
```
**Parameters**
| Name | Type | Mandatory| Description |
| ------------- | --------------------- | ---- | ------------------------------------------------------------ |
| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. |
| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.|
| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.|
### Description of IDataSource
| Name | Description |
| ------------------------------------------------------------ | ---------------------- |
| totalCount(): number | Obtains the total number of data records. |
| getData(index: number): any | Obtains the data corresponding to the specified index. |
| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.|
| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.|
### Description of DataChangeListener
| Name | Description |
| -------------------------------------------------------- | -------------------------------------- |
| onDataReloaded(): void | Invoked when all data is reloaded. |
| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. |
| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. |
| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. |
| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.|
| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. |
| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. |
## Example
```ts
// xxx.ets
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
// Initialize the data list.
private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png']
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List({ space: 3 }) {
LazyForEach(this.data, (item: string) => {
ListItem() {
Row() {
Image(item).width(50).height(50)
Text(item).fontSize(20).margin({ left: 10 })
}.margin({ left: 10, right: 10 })
}
.onClick(() => {
// The count increases by one each time the list is clicked.
this.data.pushData('/path/image' + this.data.totalCount() + '.png')
})
}, item => item)
}
}
}
```
> **NOTE**
>
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
>
> - **LazyForEach** must create and only one child component in each iteration.
>
> - The generated child components must be allowed in the parent container component of **LazyForEach**.
>
> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement.
>
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
>
> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage:
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => item.data.id.toString())
> ```
![lazyForEach](figures/lazyForEach.gif)
...@@ -2,18 +2,15 @@ ...@@ -2,18 +2,15 @@
HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop, distributed platform developed based on the IntelliJ IDEA Community (Open Source) Edition. It helps you develop versatile all-device, all-scenario applications, offering distributed multi-device development, debugging, and simulation, as well as comprehensive quality and security safeguards. HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop integrated development environment (IDE) powered by the IntelliJ IDEA Community Edition and oriented to OpenHarmony devices in all scenarios. It allows you to create project templates, and develop, build, debug, and release OpenHarmony applications from end to end.
[DevEco Studio 3.0 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) stands out in the following aspects: [DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/) stands out in the following aspects:
- One-stop information acquisition platform - **Efficient and intelligent code editing**: Code highlighting, intelligent code completion, code error check, automatic code navigation, code formatting, and code search for programming languages such as ArkTS, JavaScript, and C/C++. For details, see [Editor Usage Tips](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493).
- A wide range of device project templates - **Low-code development**: A diverse array of features to punch up your UI development productivity, including component drag and drop, visualized data binding, instant previewing, and low-code development for service widgets. For details, see [Using Low-Code Development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652).
- Efficient code editing - **Multi-device bidirectional real-time preview**: Bidirectional preview, real-time preview, live preview, component preview, and multi-device preview of UI code to quickly view how your code runs on devices. For details, see [Previewing Your App/Service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596).
- Visualized UI development - **High-performance build system**: Hvigor, a compilation and building tool to compile and package applications/services in one-click mode, better supporting ArkTS/JS development.
- Bidirectional and instant UI preview - **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities.
- High-performing compilation tool Hvigor - **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues.
- Support for application development based on the device System Capability (SysCap) sets
- Automatic application signing mechanism
- A diverse array of code debugging and profiling features
For more information, see [HUAWEI DevEco Studio For OpenHarmony User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). For more information, see [DevEco Studio (OpenHarmony) User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421).
...@@ -8,6 +8,10 @@ SysCap is short for System Capability. It refers to a standalone feature in the ...@@ -8,6 +8,10 @@ SysCap is short for System Capability. It refers to a standalone feature in the
![image-20220326064841782](figures/image-20220326064841782.png) ![image-20220326064841782](figures/image-20220326064841782.png)
For details about the SysCap sets in OpenHarmony, see [SysCap List](../reference/syscap-list.md).
### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set ### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
...@@ -60,14 +64,14 @@ You can add APIs to the associated SysCap set in DevEco Studio by adding system ...@@ -60,14 +64,14 @@ You can add APIs to the associated SysCap set in DevEco Studio by adding system
Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device.
```json ```json
/* syscap.json */ // syscap.json
{ {
"devices": { "devices": {
"general": [ /* General devices. Each general device supports a SysCap set. Multiple general devices can be configured. */ "general": [ // General devices. Each general device supports a SysCap set. Multiple general devices can be configured.
"default", "default",
"car" "car"
], ],
"custom": [ /* Custom devices. */ "custom": [ // Custom devices.
{ {
"Custom device": [ "Custom device": [
"SystemCapability.Communication.SoftBus.Core" "SystemCapability.Communication.SoftBus.Core"
...@@ -75,12 +79,12 @@ Exercise caution when modifying the required SysCap set. Incorrect modifications ...@@ -75,12 +79,12 @@ Exercise caution when modifying the required SysCap set. Incorrect modifications
} }
] ]
}, },
"development": { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ "development": { // The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set.
"addedSysCaps": [ "addedSysCaps": [
"SystemCapability.Location.Location.Lite" "SystemCapability.Location.Location.Lite"
] ]
}, },
"production": { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ "production": { // Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices.
"addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. "addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set.
"removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. "removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device.
} }
......
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
- [@ohos.application.formInfo](js-apis-formInfo.md) - [@ohos.application.formInfo](js-apis-formInfo.md)
- [@ohos.application.formProvider](js-apis-formprovider.md) - [@ohos.application.formProvider](js-apis-formprovider.md)
- [@ohos.application.missionManager](js-apis-missionManager.md) - [@ohos.application.missionManager](js-apis-missionManager.md)
- [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md)
- [@ohos.application.Want](js-apis-application-Want.md) - [@ohos.application.Want](js-apis-application-Want.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md)
- [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md)
...@@ -68,13 +69,13 @@ ...@@ -68,13 +69,13 @@
- [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md)
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md) - [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md)
- [@ohos.zlib](js-apis-zlib.md) - [@ohos.zlib](js-apis-zlib.md)
- bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md)
- bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)
- bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md)
- bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md) - bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md)
- bundle/[BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md)
- bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md)
- bundle/[DispatchInfo](js-apis-dispatchInfo.md) - bundle/[DispatchInfo](js-apis-dispatchInfo.md)
- bundle/[ElementName](js-apis-bundle-ElementName.md) - bundle/[ElementName](js-apis-bundle-ElementName.md)
...@@ -86,15 +87,17 @@ ...@@ -86,15 +87,17 @@
- bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md)
- bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)
- bundle/[ShortcutInfo<sup>(deprecated)</sup>](js-apis-bundle-ShortcutInfo.md) - bundle/[ShortcutInfo<sup>(deprecated)</sup>](js-apis-bundle-ShortcutInfo.md)
- bundle/[PackInfo](js-apis-bundle-PackInfo.md)
- UI Page - UI Page
- [@ohos.animator](js-apis-animator.md) - [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.promptAction](js-apis-promptAction.md)
- [@ohos.router](js-apis-router.md) - [@ohos.router](js-apis-router.md)
- [@ohos.uiAppearance](js-apis-uiappearance.md)
- Graphics - Graphics
- [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md)
- [@ohos.display ](js-apis-display.md) - [@ohos.display ](js-apis-display.md)
- [@ohos.effectKit](js-apis-effectKit.md) - [@ohos.effectKit](js-apis-effectKit.md)
- [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md)
- [@ohos.screen](js-apis-screen.md) - [@ohos.screen](js-apis-screen.md)
- [@ohos.screenshot](js-apis-screenshot.md) - [@ohos.screenshot](js-apis-screenshot.md)
- [@ohos.window](js-apis-window.md) - [@ohos.window](js-apis-window.md)
...@@ -133,7 +136,6 @@ ...@@ -133,7 +136,6 @@
- [@ohos.data.dataShare](js-apis-data-dataShare.md) - [@ohos.data.dataShare](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md) - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md) - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
...@@ -145,6 +147,7 @@ ...@@ -145,6 +147,7 @@
- [@ohos.document](js-apis-document.md) - [@ohos.document](js-apis-document.md)
- [@ohos.environment](js-apis-environment.md) - [@ohos.environment](js-apis-environment.md)
- [@ohos.fileio](js-apis-fileio.md) - [@ohos.fileio](js-apis-fileio.md)
- [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- [@ohos.statfs](js-apis-statfs.md) - [@ohos.statfs](js-apis-statfs.md)
...@@ -160,9 +163,13 @@ ...@@ -160,9 +163,13 @@
- [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.sms](js-apis-sms.md)
- Network Management - Network Management
- [@ohos.net.connection](js-apis-net-connection.md) - [@ohos.net.connection](js-apis-net-connection.md)
- [@ohos.net.ethernet](js-apis-net-ethernet.md)
- [@ohos.net.http](js-apis-http.md) - [@ohos.net.http](js-apis-http.md)
- [@ohos.net.policy](js-apis-net-policy.md)
- [@ohos.net.sharing](js-apis-net-sharing.md)
- [@ohos.net.socket](js-apis-socket.md) - [@ohos.net.socket](js-apis-socket.md)
- [@ohos.net.statistics](js-apis-net-statistics.md)
- [@ohos.net.tlsSocket](js-apis-tlsSocket.md)
- [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md)
- [@ohos.request](js-apis-request.md) - [@ohos.request](js-apis-request.md)
- Connectivity - Connectivity
...@@ -174,8 +181,8 @@ ...@@ -174,8 +181,8 @@
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
- [@ohos.nfc.tag](js-apis-nfctech.md) - tag/[nfctech](js-apis-nfctech.md)
- [@ohos.nfc.tag](js-apis-tagSession.md) - tag/[tagSession](js-apis-tagSession.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md)
...@@ -196,6 +203,7 @@ ...@@ -196,6 +203,7 @@
- [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.systemTimer](js-apis-system-timer.md)
- [@ohos.wallpaper](js-apis-wallpaper.md) - [@ohos.wallpaper](js-apis-wallpaper.md)
- [console](js-apis-logs.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- Device Management - Device Management
...@@ -255,8 +263,10 @@ ...@@ -255,8 +263,10 @@
- [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md) - [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained - APIs No Longer Maintained
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.bytrace](js-apis-bytrace.md)
- [@ohos.data.storage](js-apis-data-storage.md) - [@ohos.data.storage](js-apis-data-storage.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.prompt](js-apis-prompt.md) - [@ohos.prompt](js-apis-prompt.md)
- [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md)
- [@system.app](js-apis-system-app.md) - [@system.app](js-apis-system-app.md)
...@@ -278,4 +288,4 @@ ...@@ -278,4 +288,4 @@
- [@system.sensor](js-apis-system-sensor.md) - [@system.sensor](js-apis-system-sensor.md)
- [@system.storage](js-apis-system-storage.md) - [@system.storage](js-apis-system-storage.md)
- [@system.vibrator](js-apis-system-vibrate.md) - [@system.vibrator](js-apis-system-vibrate.md)
- [console](js-apis-logs.md) - [console](js-apis-logs.md)
\ No newline at end of file
# BundleStatusCallback
The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md).
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## BundleStatusCallback
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Description |
| ------ | --------------------------------------------- | -------------------------------------- |
| add | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is added.|
| update | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is updated.|
| remove | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is removed.|
...@@ -106,8 +106,8 @@ This is a system API and cannot be called by third-party applications. ...@@ -106,8 +106,8 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | --------------------- | ---- | ---------------------------------------------------- | | -------------------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. | | type | string | Yes | Event type. Only **BundleStatusChange** is supported. |
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. | | bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.| | callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.on ## innerBundleManager.on
...@@ -130,10 +130,10 @@ This is a system API and cannot be called by third-party applications. ...@@ -130,10 +130,10 @@ This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------- | ---- | ------------------ | | -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------ |
| type | "BundleStatusChange" | Yes | Event type. | | type | string | Yes | Event type. Only **BundleStatusChange** is supported.|
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.| | bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. |
**Return value** **Return value**
...@@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------------------------------------------------- | | -------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. | | type | string | Yes | Event type. Only **BundleStatusChange** is supported. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.| | callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.off ## innerBundleManager.off
...@@ -186,9 +186,9 @@ This is a system API and cannot be called by third-party applications. ...@@ -186,9 +186,9 @@ This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ---- | -------------------- | ---- | ---------------- | | ---- | ------ | ---- | ------------------------------------------ |
| type | "BundleStatusChange" | Yes | Event type.| | type | string | Yes | Event type. Only **BundleStatusChange** is supported.|
**Return value** **Return value**
......
...@@ -14,7 +14,7 @@ This module provides APIs for accessing ability-specific resources. You can use ...@@ -14,7 +14,7 @@ This module provides APIs for accessing ability-specific resources. You can use
Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**. Before using the **AbilityContext** module, you must define a child class that inherits from **Ability**.
```js ```js
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability';
class MainAbility extends Ability { class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
let context = this.context; let context = this.context;
...@@ -34,7 +34,7 @@ class MainAbility extends Ability { ...@@ -34,7 +34,7 @@ class MainAbility extends Ability {
## AbilityContext.startAbility ## AbilityContext.startAbility
startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability. This API uses an asynchronous callback to return the result. Starts an ability. This API uses an asynchronous callback to return the result.
...@@ -63,9 +63,9 @@ Starts an ability. This API uses an asynchronous callback to return the result. ...@@ -63,9 +63,9 @@ Starts an ability. This API uses an asynchronous callback to return the result.
## AbilityContext.startAbility ## AbilityContext.startAbility
startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&gt;): void;
Starts an ability with start options specified. This API uses an asynchronous callback to return the result. Starts an ability with the start options specified. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -1143,7 +1143,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ...@@ -1143,7 +1143,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call
## AbilityContext.setMissionLabel ## AbilityContext.setMissionLabel
setMissionLabel(label: string): Promise&lt;void&gt; setMissionLabel(label: string): Promise&lt;void&gt;;
Sets a label for this ability in the mission. This API uses a promise to return the result. Sets a label for this ability in the mission. This API uses a promise to return the result.
...@@ -1190,7 +1190,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call ...@@ -1190,7 +1190,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
**Example** **Example**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image';
var imagePixelMap; var imagePixelMap;
var color = new ArrayBuffer(0); var color = new ArrayBuffer(0);
var initializationOptions = { var initializationOptions = {
...@@ -1237,7 +1237,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return ...@@ -1237,7 +1237,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return
**Example** **Example**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image';
var imagePixelMap; var imagePixelMap;
var color = new ArrayBuffer(0); var color = new ArrayBuffer(0);
var initializationOptions = { var initializationOptions = {
......
...@@ -22,7 +22,7 @@ import config from "@ohos.accessibility.config"; ...@@ -22,7 +22,7 @@ import config from "@ohos.accessibility.config";
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| highContrastText | [Config](#config)\<boolean>| Yes| Yes| Whether to enable high-contrast text.| | highContrastText | [Config](#config)\<boolean>| Yes| Yes| Whether to enable high-contrast text.|
| invertColor | [Config](#config)\<boolean>| Yes| Yes| Whether to enable color inversion.| | invertColor | [Config](#config)\<boolean>| Yes| Yes| Whether to enable color inversion.|
| daltonizationColorFilter | [Config](#config)&lt;[DaltonizationColorFilter](#daltonizationcolorfilter)&gt;| Yes| Yes| Configuration of the daltonization filter.| | daltonizationColorFilter | [Config](#config)\<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Daltonization filter. |
| contentTimeout | [Config](#config)\<number>| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.| | contentTimeout | [Config](#config)\<number>| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.|
| animationOff | [Config](#config)\<boolean>| Yes| Yes| Whether to enable animation.| | animationOff | [Config](#config)\<boolean>| Yes| Yes| Whether to enable animation.|
| brightnessDiscount | [Config](#config)\<number>| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| | brightnessDiscount | [Config](#config)\<number>| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.|
...@@ -163,7 +163,7 @@ Adds a listener for changes in the list of enabled accessibility extension abili ...@@ -163,7 +163,7 @@ Adds a listener for changes in the list of enabled accessibility extension abili
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| | type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. |
| callback | Callback&lt;void&gt; | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| | callback | Callback&lt;void&gt; | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.|
**Example** **Example**
...@@ -186,7 +186,7 @@ Cancels the listener for changes in the list of enabled accessibility extension ...@@ -186,7 +186,7 @@ Cancels the listener for changes in the list of enabled accessibility extension
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| | type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. |
| callback | Callback&lt;void&gt; | No| Callback invoked when the list of enabled accessibility extension abilities changes.| | callback | Callback&lt;void&gt; | No| Callback invoked when the list of enabled accessibility extension abilities changes.|
**Example** **Example**
......
...@@ -34,13 +34,13 @@ Enumerates the focus directions. ...@@ -34,13 +34,13 @@ Enumerates the focus directions.
| up | Search for the next focusable item above the current item in focus.| | up | Search for the next focusable item above the current item in focus.|
| down | Search for the next focusable item below the current item in focus.| | down | Search for the next focusable item below the current item in focus.|
| left | Search for the next focusable item on the left of the current item in focus.| | left | Search for the next focusable item on the left of the current item in focus.|
| right | Search for the next focusable item on the right the current item in focus.| | right | Search for the next focusable item on the right of the current item in focus.|
| forward | Search for the next focusable item before the current item in focus.| | forward | Search for the next focusable item before the current item in focus.|
| backward | Search for the next focusable item after the current item in focus.| | backward | Search for the next focusable item after the current item in focus.|
## FocusType ## FocusType
Enumerates of the focus types. Enumerates the focus types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
...@@ -55,8 +55,6 @@ Defines a rectangle. ...@@ -55,8 +55,6 @@ Defines a rectangle.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | --------- | | ------ | ------ | ---- | ---- | --------- |
| left | number | Yes | No | Left boundary of the rectangle.| | left | number | Yes | No | Left boundary of the rectangle.|
...@@ -75,35 +73,9 @@ Enumerates the window types. ...@@ -75,35 +73,9 @@ Enumerates the window types.
| application | Application window.| | application | Application window.|
| system | System window.| | system | System window.|
## AccessibilityExtensionContext.setEventTypeFilter
setEventTypeFilter(type: Array<accessibility.EventType>): Promise\<boolean>;
Sets the concerned event type.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------- |
| type | Array&lt;[EventType](js-apis-accessibility.md#EventType)&gt; | Yes | Event type.|
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```ts
this.context.setEventTypeFilter(['click', 'longClick']);
```
## AccessibilityExtensionContext.setTargetBundleName ## AccessibilityExtensionContext.setTargetBundleName
setTargetBundleName(targetNames: Array\<string>): Promise\<boolean>; setTargetBundleName(targetNames: Array\<string>): Promise\<void>;
Sets the concerned target bundle. Sets the concerned target bundle.
...@@ -139,7 +111,7 @@ Obtains the focus element. ...@@ -139,7 +111,7 @@ Obtains the focus element.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------------------- | ------- | ---- | ------------------- | | -------------------- | ------- | ---- | ------------------- |
| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is false.| | isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.|
**Return value** **Return value**
...@@ -213,7 +185,7 @@ this.context.getWindows().then(windows => { ...@@ -213,7 +185,7 @@ this.context.getWindows().then(windows => {
## AccessibilityExtensionContext.injectGesture ## AccessibilityExtensionContext.injectGesture
injectGesture(gesturePath: GesturePath, listener: Callback\<boolean>): Promise\<boolean injectGesture(gesturePath: GesturePath, callback: AsyncCallback\<void>): void
Injects a gesture. Injects a gesture.
...@@ -224,13 +196,7 @@ Injects a gesture. ...@@ -224,13 +196,7 @@ Injects a gesture.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- | | ----------- | ---------------------------------------- | ---- | -------------- |
| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | | gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. |
| listener | Callback&lt;boolean&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ---------------------- | ---------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -244,3 +210,170 @@ this.context.gestureInject(gesturePath, (result) => { ...@@ -244,3 +210,170 @@ this.context.gestureInject(gesturePath, (result) => {
console.info('gestureInject result: ' + result); console.info('gestureInject result: ' + result);
}) })
``` ```
## AccessibilityElement.attributeNames
attributeNames\<T extends keyof ElementAttributeValues>(): Promise\<Array\<T>>;
Obtains all attribute names of this element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;T&gt;&gt; | Promise used to return all attribute names of the element.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.attributeNames().then((values) => {
console.log("get attribute names success");
}).catch((err) => {
console.log("get attribute names err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.attributeValue
attributeValue\<T extends keyof ElementAttributeValues>(attributeName: T): Promise\<ElementAttributeValues[T]>;
Obtains the attribute value based on an attribute name.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| attributeName | T | Yes | Attribute name. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;ElementAttributeValues[T]&gt;&gt; | Promise used to return the attribute value.|
**Example**
```ts
let accessibilityElement;
try {
let attributeName = 'name';
accessibilityElement.attributeValue(attributeName).then((value) => {
console.log("get attribute value by name success");
}).catch((err) => {
console.log("get attribute value by name err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.actionNames
actionNames(): Promise\<Array\<string>>;
Obtains the names of all actions supported by this element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the names of all actions supported by the element.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.actionNames().then((values) => {
console.log("get action names success");
}).catch((err) => {
console.log("get action names err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.performAction
performAction(actionName: string, parameters?: object): Promise\<boolean>;
Performs an action based on the specified action name.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| actionName | string | Yes | Action name. |
| parameters | object | No | Parameter required for performing the target action. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;boolean&gt;&gt; | Promise used to return the result.|
**Example**
```ts
let accessibilityElement;
try {
accessibilityElement.performAction('action').then((result) => {
console.info('perform action result: ' + result);
}).catch((err) => {
console.log("perform action err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
## AccessibilityElement.findElement
findElement(type: 'content', condition: string): Promise\<Array\<AccessibilityElement>>;
Queries the information about this element based on the specified information type and condition.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| type | string | Yes | Information type. The value is fixed at **'content'**. |
| condition | string | Yes | Search criteria. |
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;T&gt;&gt; | Promise used to return the result.|
**Example**
```ts
let accessibilityElement;
try {
let condition = 'keyword';
accessibilityElement.findElement('content', condition).then((values) => {
console.log("find element success");
}).catch((err) => {
console.log("find element err: " + JSON.stringify(err));
});
} catch (e) {
console.log("An unexpected error occurred. Error:" + e);
}
```
...@@ -48,8 +48,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -48,8 +48,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
...@@ -94,8 +94,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -94,8 +94,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
...@@ -139,8 +139,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -139,8 +139,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
...@@ -181,8 +181,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -181,8 +181,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
...@@ -224,8 +224,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -224,8 +224,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
...@@ -269,8 +269,8 @@ import rdb from '@ohos.data.rdb'; ...@@ -269,8 +269,8 @@ import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db"; let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00"; let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
......
# quickFixManager
The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire application.
> **NOTE**
>
> 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.
## Modules to Import
```
import quickFixManager from '@ohos.application.quickFixManager';
```
## HapModuleQuickFixInfo
Defines the quick fix information at the HAP file level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| moduleName | Read only | string | Yes | Name of the HAP file. |
| originHapHash | Read only | string | Yes | Hash value of the HAP file. |
| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. |
## ApplicationQuickFixInfo
Defines the quick fix information at the application level.
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
| Name | Readable/Writable| Type | Mandatory| Description |
| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ |
| bundleName | Read only | string | Yes | Bundle name of the application. |
| bundleVersionCode | Read only | number | Yes | Internal version number of the application. |
| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. |
| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. |
| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. |
| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. |
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<void>): void;
Applies a quick fix patch. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
| callback | AsyncCallback\<void> | No| Callback used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => {
if (error) {
console.info( `applyQuickFix failed with error + ${error}`)
} else {
console.info( 'applyQuickFix success')
}
})
```
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
Applies a quick fix patch. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INSTALL_BUNDLE
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| hapModuleQuickFixFiles | Array\<string> | No| Quick fix files, each of which must contain a valid file path.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"]
quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => {
console.info('applyQuickFix success')
}).catch((error) => {
console.info(`applyQuickFix err: + ${error}`)
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<ApplicationQuickFixInfo>): void;
Obtains the quick fix information of the application. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No|Bundle name of the application. |
| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => {
if (error) {
console.info(`getApplicationQuickFixInfo error: + ${error}`)
} else {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}
})
```
## quickFixManager.getApplicationQuickFixInfo
getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo>;
Obtains the quick fix information of the application. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Parameter| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| bundleName | string | No| Bundle name of the application. |
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.|
**Example**
```js
import quickFixManager from '@ohos.application.quickFixManager'
let bundleName = "bundleName"
quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => {
console.info(`getApplicationQuickFixInfo success: + ${data}`)
}).catch((error) => {
console.info(`getApplicationQuickFixInfo err: + ${error}`)
})
```
...@@ -2,15 +2,17 @@ ...@@ -2,15 +2,17 @@
The **BackgroundTaskManager** module provides APIs to manage background tasks. The **BackgroundTaskManager** module provides APIs to manage background tasks.
If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension.
If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup. If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup.
If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task. If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
> **NOTE** If a privileged system application needs to use certain system resources (for example, resources required to receive common events) when suspended, it can request efficiency resources.
> **NOTE**
> >
> 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. > 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.
## Modules to Import ## Modules to Import
...@@ -298,6 +300,64 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() ...@@ -298,6 +300,64 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(()
``` ```
## backgroundTaskManager.applyEfficiencyResources<sup>9+</sup>
applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest9)): boolean
Requests efficiency resources from the system.
A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest9) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest9).|
**Return value**
| Type | Description |
| -------------- | ---------------- |
| boolean | Returns **true** if the request for the resources is successful; returns **false** otherwise.|
**Example**
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: false,
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("result of applyEfficiencyResources is: " + res)
```
## backgroundTaskManager.resetAllEfficiencyResources<sup>9+</sup>
resetAllEfficiencyResources(): void
Releases all resources that have been requested.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**System API**: This is a system API.
**Example**
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources();
```
## DelaySuspendInfo ## DelaySuspendInfo
Provides the information about the suspension delay. Provides the information about the suspension delay.
...@@ -325,3 +385,38 @@ Provides the information about the suspension delay. ...@@ -325,3 +385,38 @@ Provides the information about the suspension delay.
| WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API.| | WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API.|
| VOIP | 8 | Audio and video calls.<br>This is a system API. | | VOIP | 8 | Audio and video calls.<br>This is a system API. |
| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | | TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
## EfficiencyResourcesRequest<sup>9+</sup>
Describes the parameters for requesting efficiency resources.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**System API**: This is a system API.
| Name | Type | Mandatory | Description |
| --------------- | ------ | ---- | ---------------------------------------- |
| resourceTypes | number | Yes | Type of the resource to request. |
| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. |
| timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. |
| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. |
| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. |
| reason | string | Yes | Reason for requesting the resource. |
## ResourceType<sup>9+</sup>
Enumerates the efficiency resource types.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**System API**: This is a system API.
| Name | Value | Description |
| ----------------------- | ---- | --------------------- |
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | A type of software resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | A type of software resources, which prevent timers from being proxied when the application is suspended. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. |
| AUDIO | 64 | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.|
...@@ -223,7 +223,7 @@ cancelPairedDevice(deviceId: string): boolean ...@@ -223,7 +223,7 @@ cancelPairedDevice(deviceId: string): boolean
Cancels a paired remote device. Cancels a paired remote device.
This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
...@@ -389,7 +389,7 @@ startBluetoothDiscovery(): boolean ...@@ -389,7 +389,7 @@ startBluetoothDiscovery(): boolean
Starts Bluetooth scan to discover remote devices. Starts Bluetooth scan to discover remote devices.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -1293,7 +1293,7 @@ No value is returned. ...@@ -1293,7 +1293,7 @@ No value is returned.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let retArray = a2dpSrc.getConnectionDevices(); let retArray = a2dpSrc.getConnectionDevices();
``` ```
...@@ -1322,7 +1322,7 @@ Obtains the connection state of the profile. ...@@ -1322,7 +1322,7 @@ Obtains the connection state of the profile.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1356,7 +1356,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. ...@@ -1356,7 +1356,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1386,7 +1386,7 @@ Disconnects an A2DP connection. ...@@ -1386,7 +1386,7 @@ Disconnects an A2DP connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1416,7 +1416,7 @@ No value is returned. ...@@ -1416,7 +1416,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data)); console.info('a2dp state = '+ JSON.stringify(data));
} }
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1446,7 +1446,7 @@ No value is returned. ...@@ -1446,7 +1446,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data)); console.info('a2dp state = '+ JSON.stringify(data));
} }
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.on('connectionStateChange', onReceiveEvent);
a2dpSrc.off('connectionStateChange', onReceiveEvent); a2dpSrc.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1475,7 +1475,7 @@ Obtains the playing state of a device. ...@@ -1475,7 +1475,7 @@ Obtains the playing state of a device.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile;
let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1510,7 +1510,8 @@ Sets up a Hands-free Profile (HFP) connection of a device. ...@@ -1510,7 +1510,8 @@ Sets up a Hands-free Profile (HFP) connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as
bluetooth.HandsFreeAudioGatewayProfile;
let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1540,7 +1541,8 @@ Disconnects the HFP connection of a device. ...@@ -1540,7 +1541,8 @@ Disconnects the HFP connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as
bluetooth.HandsFreeAudioGatewayProfile;
let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1570,7 +1572,8 @@ No value is returned. ...@@ -1570,7 +1572,8 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data)); console.info('hfp state = '+ JSON.stringify(data));
} }
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as
bluetooth.HandsFreeAudioGatewayProfile;
hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1600,7 +1603,8 @@ No value is returned. ...@@ -1600,7 +1603,8 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data)); console.info('hfp state = '+ JSON.stringify(data));
} }
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as
bluetooth.HandsFreeAudioGatewayProfile;
hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.on('connectionStateChange', onReceiveEvent);
hfpAg.off('connectionStateChange', onReceiveEvent); hfpAg.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1617,7 +1621,7 @@ connect(device: string): boolean ...@@ -1617,7 +1621,7 @@ connect(device: string): boolean
Connects to the HidHost service of a device. Connects to the HidHost service of a device.
This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
...@@ -1638,7 +1642,7 @@ This is a system API. ...@@ -1638,7 +1642,7 @@ This is a system API.
**Example** **Example**
```js ```js
let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile;
let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1649,7 +1653,7 @@ disconnect(device: string): boolean ...@@ -1649,7 +1653,7 @@ disconnect(device: string): boolean
Disconnects from the HidHost service of a device. Disconnects from the HidHost service of a device.
This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
...@@ -1670,7 +1674,7 @@ This is a system API. ...@@ -1670,7 +1674,7 @@ This is a system API.
**Example** **Example**
```js ```js
let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile;
let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1700,7 +1704,7 @@ No value is returned. ...@@ -1700,7 +1704,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data)); console.info('hidHost state = '+ JSON.stringify(data));
} }
let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile;
hidHost.on('connectionStateChange', onReceiveEvent); hidHost.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1730,7 +1734,7 @@ No value is returned. ...@@ -1730,7 +1734,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data)); console.info('hidHost state = '+ JSON.stringify(data));
} }
let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile;
hidHost.on('connectionStateChange', onReceiveEvent); hidHost.on('connectionStateChange', onReceiveEvent);
hidHost.off('connectionStateChange', onReceiveEvent); hidHost.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1747,7 +1751,7 @@ disconnect(device: string): boolean ...@@ -1747,7 +1751,7 @@ disconnect(device: string): boolean
Disconnects from the Personal Area Network (PAN) service of a device. Disconnects from the Personal Area Network (PAN) service of a device.
This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -1768,7 +1772,7 @@ This is a system API. ...@@ -1768,7 +1772,7 @@ This is a system API.
**Example** **Example**
```js ```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile;
let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1798,7 +1802,7 @@ No value is returned. ...@@ -1798,7 +1802,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data)); console.info('pan state = '+ JSON.stringify(data));
} }
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile;
panProfile.on('connectionStateChange', onReceiveEvent); panProfile.on('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1828,7 +1832,7 @@ No value is returned. ...@@ -1828,7 +1832,7 @@ No value is returned.
function onReceiveEvent(data) { function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data)); console.info('pan state = '+ JSON.stringify(data));
} }
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile;
panProfile.on('connectionStateChange', onReceiveEvent); panProfile.on('connectionStateChange', onReceiveEvent);
panProfile.off('connectionStateChange', onReceiveEvent); panProfile.off('connectionStateChange', onReceiveEvent);
``` ```
...@@ -1840,7 +1844,7 @@ setTethering(enable: boolean): void ...@@ -1840,7 +1844,7 @@ setTethering(enable: boolean): void
Sets tethering. Sets tethering.
This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
...@@ -1861,7 +1865,7 @@ This is a system API. ...@@ -1861,7 +1865,7 @@ This is a system API.
**Example** **Example**
```js ```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile;
let ret = panProfile.setTethering(true); let ret = panProfile.setTethering(true);
``` ```
...@@ -1872,7 +1876,7 @@ isTetheringOn(): boolean ...@@ -1872,7 +1876,7 @@ isTetheringOn(): boolean
Obtains the tethering state. Obtains the tethering state.
This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -1885,7 +1889,7 @@ This is a system API. ...@@ -1885,7 +1889,7 @@ This is a system API.
**Example** **Example**
```js ```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile;
let ret = panProfile.isTetheringOn(); let ret = panProfile.isTetheringOn();
``` ```
...@@ -2217,7 +2221,7 @@ function ReadCharacteristicReq(CharacteristicReadReq) { ...@@ -2217,7 +2221,7 @@ function ReadCharacteristicReq(CharacteristicReadReq) {
let characteristicUuid = CharacteristicReadReq.characteristicUuid; let characteristicUuid = CharacteristicReadReq.characteristicUuid;
let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC};
let ret = gattServer.sendResponse(serverResponse); let ret = gattServer.sendResponse(serverResponse);
if (ret) { if (ret) {
console.log('bluetooth sendResponse successfully'); console.log('bluetooth sendResponse successfully');
...@@ -2294,10 +2298,10 @@ function WriteCharacteristicReq(CharacteristicWriteReq) { ...@@ -2294,10 +2298,10 @@ function WriteCharacteristicReq(CharacteristicWriteReq) {
let needRsp = CharacteristicWriteReq.needRsp; let needRsp = CharacteristicWriteReq.needRsp;
let value = new Uint8Array(CharacteristicWriteReq.value); let value = new Uint8Array(CharacteristicWriteReq.value);
let characteristicUuid = CharacteristicWriteReq.characteristicUuid; let characteristicUuid = CharacteristicWriteReq.characteristicUuid;
cccValue[0] = value[0]; cccValue[0] = value[0];
let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC};
let ret = gattServer.sendResponse(serverResponse); let ret = gattServer.sendResponse(serverResponse);
if (ret) { if (ret) {
console.log('bluetooth sendResponse successfully'); console.log('bluetooth sendResponse successfully');
...@@ -2374,7 +2378,7 @@ function ReadDescriptorReq(DescriptorReadReq) { ...@@ -2374,7 +2378,7 @@ function ReadDescriptorReq(DescriptorReadReq) {
let descriptorUuid = DescriptorReadReq.descriptorUuid; let descriptorUuid = DescriptorReadReq.descriptorUuid;
let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc};
let ret = gattServer.sendResponse(serverResponse); let ret = gattServer.sendResponse(serverResponse);
if (ret) { if (ret) {
console.log('bluetooth sendResponse successfully'); console.log('bluetooth sendResponse successfully');
...@@ -2454,7 +2458,7 @@ function WriteDescriptorReq(DescriptorWriteReq) { ...@@ -2454,7 +2458,7 @@ function WriteDescriptorReq(DescriptorWriteReq) {
descValue[0] = value[0]; descValue[0] = value[0];
let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc};
let ret = gattServer.sendResponse(serverResponse); let ret = gattServer.sendResponse(serverResponse);
if (ret) { if (ret) {
console.log('bluetooth sendResponse successfully'); console.log('bluetooth sendResponse successfully');
......
# BundleInfo # BundleInfo
The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
> **NOTE** > **NOTE**
> >
> 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. > 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.
The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**.
## BundleInfo ## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Bundle name. | | name | string | Yes | No | Bundle name. |
| type | string | Yes | No | Bundle type. | | type | string | Yes | No | Bundle type. |
| appId | string | Yes | No | ID of the application to which the bundle belongs. | | appId | string | Yes | No | ID of the application to which the bundle belongs. |
| uid | number | Yes | No | UID of the application to which the bundle belongs. | | uid | number | Yes | No | UID of the application to which the bundle belongs. |
| installTime | number | Yes | No | Time when the HAP file was installed. | | installTime | number | Yes | No | Time when the HAP file was installed. |
| updateTime | number | Yes | No | Time when the HAP file was updated. | | updateTime | number | Yes | No | Time when the HAP file was updated. |
| appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | | appInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. |
| abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.<br>The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.| | abilityInfos | Array\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | No | Ability configuration information.<br>The value is obtained by passing **GET_BUNDLE_WITH_ABILITIES**.|
| reqPermissions | Array\<string> | Yes | No | Permissions to request from the system for running the application.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissions | Array\<string> | Yes | No | Permissions to request from the system for running the application.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.| | reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetail)> | Yes | No | Detailed information of the permissions to request from the system.<br>The value is obtained by passing **GET_BUNDLE_WITH_REQUESTED_PERMISSION**.|
| vendor | string | Yes | No | Vendor of the bundle. | | vendor | string | Yes | No | Vendor of the bundle. |
| versionCode | number | Yes | No | Version number of the bundle. | | versionCode | number | Yes | No | Version number of the bundle. |
| versionName | string | Yes | No | Version description of the bundle. | | versionName | string | Yes | No | Version description of the bundle. |
| compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. | | compatibleVersion | number | Yes | No | Earliest SDK version required for running the bundle. |
| targetVersion | number | Yes | No | Latest SDK version required for running the bundle. | | targetVersion | number | Yes | No | Latest SDK version required for running the bundle. |
| isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. | | isCompressNativeLibs | boolean | Yes | No | Whether to compress the native library of the bundle. The default value is **true**. |
| hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. | | hapModuleInfos | Array\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | No | Module configuration information. |
| entryModuleName | string | Yes | No | Name of the entry module. | | entryModuleName | string | Yes | No | Name of the entry module. |
| cpuAbi | string | Yes | No | CPU and ABI information of the bundle. | | cpuAbi | string | Yes | No | CPU and ABI information of the bundle. |
| isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. | | isSilentInstallation | string | Yes | No | Whether the application can be installed in silent mode. |
| minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. | | minCompatibleVersionCode | number | Yes | No | Earliest version compatible with the bundle in the distributed scenario. |
| entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. | | entryInstallationFree | boolean | Yes | No | Whether installation-free is supported for the entry module. |
| reqPermissionStates<sup>8+</sup> | Array\<number> | Yes | No | Permission grant state. | | reqPermissionStates<sup>8+</sup> | Array\<number> | Yes | No | Permission grant state. |
| extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.<br>The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.| | extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Extension ability information.<br>The value is obtained by passing **GET_BUNDLE_WITH_EXTENSION_ABILITY**.|
...@@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system. ...@@ -45,8 +45,8 @@ Provides the detailed information of the permissions to request from the system.
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------------------- | ----------------------- | ---- | ---- | -------------------- | | --------------------- | ----------------------- | ---- | ---- | ---------------------- |
| name | string | Yes | Yes | Name of the permission to request. | | name | string | Yes | Yes | Name of the permission to request. |
| reason | string | Yes | Yes | Reason for requesting the permission. | | reason | string | Yes | Yes | Reason for requesting the permission. |
| reasonId<sup>9+</sup> | number | Yes | Yes | ID of the reason for requesting the permission.| | reasonId<sup>9+</sup> | number | Yes | Yes | ID of the reason for requesting the permission.|
...@@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission. ...@@ -60,7 +60,7 @@ Describes the application scenario and timing for using the permission.
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| --------- | -------------- | ---- | ---- | ------------------------- | | --------- | -------------- | ---- | ---- | --------------------------- |
| abilities | Array\<string> | Yes | Yes | Abilities that use the permission.| | abilities | Array\<string> | Yes | Yes | Abilities that use the permission.|
| when | string | Yes | Yes | Time when the permission is used. | | when | string | Yes | Yes | Time when the permission is used. |
# ElementName # ElementName
The **ElementName** module provides the element name information. The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md).
> **NOTE** > **NOTE**
> >
> 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. > 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.
## ElementName ## ElementName<sup>(deprecated)<sup>
**System capability**: SystemCapability.BundleManager.BundleFramework > This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- | | ----------------------- | ---------| ---- | ---- | ------------------------- |
| deviceId | string | Yes | Yes | Device ID. | | deviceId | string | Yes | Yes | Device ID. |
| bundleName | string | Yes | Yes | Bundle name of the application. | | bundleName | string | Yes | Yes | Bundle name of the application. |
| abilityName | string | Yes | Yes | Name of the ability. | | abilityName | string | Yes | Yes | Name of the ability. |
| uri | string | Yes | Yes | URI. | | uri | string | Yes | Yes | Resource ID. |
| shortName | string | Yes | Yes | Short name of the ability. | | shortName | string | Yes | Yes | Short name of the ability. |
| moduleName<sup>9+</sup> | string | Yes | Yes | Name of the HAP file to which the ability belongs. | | moduleName<sup>9+</sup> | string | Yes | Yes | Name of the HAP file to which the ability belongs. |
<!--no_check-->
\ No newline at end of file
# PackInfo
The **PackInfo** module provides the bundle package information, which can be obtained using [bundle.getBundlePackInfo](js-apis-Bundle.md).
> **NOTE**
>
> 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.
## BundlePackFlag
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Value | Description |
| ------------------ | ---------- | ---------------------------------- |
| GET_PACK_INFO_ALL | 0x00000000 | All information about the package. |
| GET_PACKAGES | 0x00000001 | Package information about the package.|
| GET_BUNDLE_SUMMARY | 0x00000002 | Bundle summary of the package. |
| GET_MODULE_SUMMARY | 0x00000004 | Module summary of the package. |
## BundlePackInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| -------- | --------------------------------------- | ---- | ---- | ----------------------------- |
| packages | Array\<[PackageConfig](#packageconfig)> | Yes | No | Package configuration information. |
| summary | [PackageSummary](#packagesummary) | Yes | No | Package summary.|
## PackageConfig
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| deviceType | Array\<string> | Yes | No | Device types supported. |
| name | string | Yes | No | Package name. |
| moduleType | string | Yes | No | Module type. |
| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.|
## PackageSummary
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------- | --------------------------------------------- | ---- | ---- | -------------------- |
| app | [BundleConfigInfo](#bundleconfiginfo) | Yes | No | Bundle configuration information. |
| modules | Array\<[ModuleConfigInfo](#moduleconfiginfo)> | Yes | No | Module configuration information.|
## BundleConfigInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ---------- | ------------------- | ---- | ---- | ---------------------------------- |
| bundleName | string | Yes | No | Bundle name of an application. It uniquely identifies the application.|
| version | [Version](#version) | Yes | No | Bundle version. |
## ModuleConfigInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------------------ | ------------------------------------------------- | ---- | ---- | ---------------------------------- |
| apiVersion | [ApiVersion](#apiversion) | Yes | No | API version of the module. |
| deviceType | Array\<string> | Yes | No | Device type of the module. |
| distro | [ModuleDistroInfo](#moduledistroinfo) | Yes | No | Distribution information of the module. |
| abilities | Array\<[ModuleAbilityInfo](#moduleabilityinfo)> | Yes | No | Ability information of the module. |
| extensionAbilities | Array\<[ExtensionAbilities](#extensionabilities)> | Yes | No | Extension ability information of the module.|
## ModuleDistroInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------------------- | ------- | ---- | ---- | ------------------------------------------------------------ |
| mainAbility | string | Yes | No | Name of the main ability. |
| deliveryWithInstall | boolean | Yes | No | Whether the HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.|
| installationFree | boolean | Yes | No | Whether the HAP file supports the installation-free feature. The value **true** means that the HAP file supports the installation-free feature and meets installation-free constraints, and **false** means the opposite.|
| moduleName | string | Yes | No | Module name. |
| moduleType | string | Yes | No | Module type. |
## ModuleAbilityInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Logical name of the ability. The name must be unique in the application. |
| label | string | Yes | No | Name of the ability displayed to users. The value is a resource index to names in multiple languages.|
| visible | boolean | Yes | No | Whether the ability can be called by other applications. The value **true** means that the ability can be called by other applications, and **false** means the opposite.|
| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Widget information. |
## ExtensionAbilities
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ----- | ------------------------------------------- | ---- | ---- | ------------------------------------------------------------ |
| forms | Array\<[AbilityFormInfo](#abilityforminfo)> | Yes | No | Specification of the widget. A widget is a brief view of an application that is embedded on the home screen to receive periodical updates.|
## AbilityFormInfo
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Widget name. |
| type | string | Yes | No | Widget type. |
| updateEnabled | boolean | Yes | No | Whether the widget supports periodical update. The value **true** means that the widget supports periodical update, and **false** means the opposite.|
| scheduledUpdateTime | string | Yes | No | Scheduled time to update the widget. The value is in 24-hour format and accurate to the minute. |
| updateDuration | number | Yes | No | Interval to update the widget. The unit is 30 minutes. The value is a multiple of 30. A widget can be updated periodically, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). If both are configured, **updateDuration** takes precedence.|
| supportDimensions | Array\<number> | Yes | No | Dimensions of the widget. The value can be **1\*2**, **2\*2**, **2\*4**, **4\*4**, or a combination of these options. At least one option must be specified when defining the widget.|
| defaultDimension | number | Yes | No | Default dimensions of the widget. The value must be available in the **supportDimensions** array of the widget.|
## ApiVersion
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ----------- | ------ | ---- | ---- | -------------------- |
| releaseType | string | Yes | No | Name of the API version. |
| compatible | number | Yes | No | Minimum API version.|
| target | numbe | Yes | No | Target API version. |
## Version
**System API**: This is a system API and cannot be called by third-party applications.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ------------------------ | ------ | ---- | ---- | ------------------------------------------------------------ |
| minCompatibleVersionCode | number | Yes | No | Minimum compatible version of the application. It is used to check whether the application is compatible with a version on other devices in the cross-device scenario. The value is a 32-bit non-negative integer.|
| name | string | Yes | No | Application version number visible to users. |
| code | number | Yes | No | Application version number used only for application management. The value is a 32-bit non-negative integer. It is used only to determine whether a version is later than another version. A larger value indicates a later version.|
...@@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. ...@@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100.
**Example** **Example**
```js ```js
call.formatPhoneNumber("138xxxxxxxx",{ call.formatPhoneNumber("138xxxxxxxx", {
countryCode: "CN" countryCode: "CN"
}, (err, data) => { }, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
......
# Standard NFC Card Emulation # Standard NFC Card Emulation
The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE).
> **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul ...@@ -12,6 +12,17 @@ The **cardEmulation** module implements Near-Field Communication (NFC) card emul
import cardEmulation from '@ohos.nfc.cardEmulation'; import cardEmulation from '@ohos.nfc.cardEmulation';
``` ```
## FeatureType
Enumerates the NFC card emulation types.
**System capability**: SystemCapability.Communication.NFC.Core
| Name| Default Value| Description|
| -------- | -------- | -------- |
| HCE | 0 | HCE.|
| UICC | 1 | Subscriber identity module (SIM) card emulation.|
| ESE | 2 | embedded Secure Element (eSE) emulation.|
## cardEmulation.isSupported ## cardEmulation.isSupported
...@@ -19,23 +30,31 @@ isSupported(feature: number): boolean ...@@ -19,23 +30,31 @@ isSupported(feature: number): boolean
Checks whether a certain type of card emulation is supported. Checks whether a certain type of card emulation is supported.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| feature | number | Yes | Card emulation type. For details, see [FeatureType](#featuretype).|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.| | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
## HceService<sup>8+</sup> ## HceService<sup>8+</sup>
Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance. Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE.
### startHCE<sup>8+</sup> ### startHCE<sup>8+</sup>
startHCE(aidList: string[]): boolean startHCE(aidList: string[]): boolean
Starts HCE. Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
...@@ -45,13 +64,13 @@ Starts HCE. ...@@ -45,13 +64,13 @@ Starts HCE.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- | | ------- | -------- | ---- | ----------------------- |
| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.| | aidList | string[] | Yes | AID list to register.|
### stopHCE<sup>8+</sup> ### stopHCE<sup>8+</sup>
stopHCE(): boolean stopHCE(): boolean
Stops HCE. Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
...@@ -61,7 +80,7 @@ Stops HCE. ...@@ -61,7 +80,7 @@ Stops HCE.
on(type: "hceCmd", callback: AsyncCallback<number[]>): void; on(type: "hceCmd", callback: AsyncCallback<number[]>): void;
Subscribes to messages from the peer device after **startHCE()**. Registers a callback to receive APDUs from the peer card reader.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
...@@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**. ...@@ -72,13 +91,13 @@ Subscribes to messages from the peer device after **startHCE()**.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | | type | string | Yes | Event type to subscribe to. The value is **hceCmd**. |
| callback | AsyncCallback<number[]> | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).| | callback | AsyncCallback<number[]> | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.|
### sendResponse<sup>8+</sup> ### sendResponse<sup>8+</sup>
sendResponse(responseApdu: number[]): void; sendResponse(responseApdu: number[]): void;
Sends a response to the peer device. Sends a response to the peer card reader.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
...@@ -88,16 +107,25 @@ Sends a response to the peer device. ...@@ -88,16 +107,25 @@ Sends a response to the peer device.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | -------- | ---- | -------------------------------------------------- | | ------------ | -------- | ---- | -------------------------------------------------- |
| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.| | responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.|
**Example** **Example**
```js ```js
import cardEmulation from '@ohos.nfc.cardEmulation';
var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
if (!isHceSupported) {
console.log('this device is not supported for HCE, ignore it.');
return;
}
// The device supports HCE and transimits APDUs with the remote NFC reader.
var hceService = new cardEmulation.HceService(); var hceService = new cardEmulation.HceService();
hceService.startHCE([ hceService.startHCE([
"F0010203040506", "A0000000041010" "F0010203040506", "A0000000041010"
]) ]);
hceService.stopHCE();
hceService.on("hceCmd", (err, res) => { hceService.on("hceCmd", (err, res) => {
if(err.data === 0) { if(err.data === 0) {
console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res));
...@@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => { ...@@ -108,4 +136,7 @@ hceService.on("hceCmd", (err, res) => {
console.log('callback => Operation hceCmd failed. Cause: ' + err.data); console.log('callback => Operation hceCmd failed. Cause: ' + err.data);
} }
}) })
// Stop HCE when the application exits the NFC card emulation.
hceService.stopHCE();
``` ```
# Color Space Management
The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes.
> **NOTE**
>
> 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.
## Modules to Import
```js
import colorSpaceManager from '@ohos.graphics.colorSpaceManager';
```
## ColorSpace
Enumerates the color space types.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
| Name | Value | Description |
| --------------------------- | ------ | ----------------------- |
| UNKNOWN | 0 | Unknown type.|
| ADOBE_RGB_1998 | 1 | Adobe RGB (1998).|
| DCI_P3 | 2 | DCI-P3.|
| DISPLAY_P3 | 3 | Display P3.|
| SRGB | 4 | SRGB.<br>This is the default color space type.|
| CUSTOM | 5 | Custom type.|
## ColorSpacePrimaries
Defines the color space primaries. A color space is defined by chromaticity coordinates of the red, green, and blue additive primaries, the white point, and the gamma.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
| Name | Type| Readable| Writable| Description |
| ---------------------------- | -------- | ---- | ---- | ----------------------------------------------------- |
| redX | number | Yes | Yes | X coordinate of the red color in the color space.|
| redY | number | Yes | Yes | Y coordinate of the red color in the color space.|
| greenX | number | Yes | Yes | X coordinate of the green color in the color space.|
| greenY | number | Yes | Yes | Y coordinate of the green color in the color space.|
| blueX | number | Yes | Yes | X coordinate of the blue color in the color space.|
| blueY | number | Yes | Yes | Y coordinate of the blue color in the color space.|
| whitePointX | number | Yes | Yes | X coordinate of the white point in the color space.|
| whitePointY | number | Yes | Yes | Y coordinate of the white point in the color space.|
## colorSpaceManager.create
create(colorSpaceName: ColorSpace): ColorSpaceManager
Creates a standard color space object.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Parameters**
| Parameter | Type | Mandatory| Description |
| --------------- | ------------------------ | ---- | -----------------------------|
| colorSpaceName | [ColorSpace](#colorspace)| Yes | Type of the color space.<br>**UNKNOWN** and **CUSTOM** cannot be used when creating standard color space objects. |
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpaceManager](#colorspacemanager) | Color space object created. |
**Example**
```js
let colorSpace = null;
try {
colorSpace = colorSpaceManager.create(colorSpaceManager.ColorSpace.SRGB);
} catch (err) {
console.log(`Failed to create SRGB colorSpace. Cause: ` + JSON.stringify(err));
}
```
## colorSpaceManager.create
create(primaries: ColorSpacePrimaries, gamma: number): ColorSpaceManager
Creates a custom color space object.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Parameters**
| Parameter | Type | Mandatory| Description |
| --------------- | ------------------------------------------ | ---- | -----------------------------|
| primaries | [ColorSpacePrimaries](#colorspaceprimaries)| Yes | Primaries of the color space. |
| gamma | number | Yes | Gamma of the color space. |
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpaceManager](#colorspacemanager) | Color space object created.<br>The color space type is **CUSTOM** of [ColorSpace](#colorspace).|
**Example**
```js
let colorSpace = null;
try {
let primaries = {
redX: 0.1,
redY: 0.1,
greenX: 0.2,
greenY: 0.2,
blueX: 0.3,
blueY: 0.3,
whitePointX: 0.4,
whitePointY: 0.4
};
let gamma = 2.2;
colorSpace = colorSpaceManager.create(primaries, gamma);
} catch (err) {
console.log(`Failed to create colorSpace with customized primaries and gamma. Cause: ` + JSON.stringify(err));
}
```
## ColorSpaceManager
Implements management of color space objects.
Before calling any of the following APIs, you must use [create()](#colorspacemanagercreate) to create a color space object.
### getColorSpaceName
getColorSpaceName(): ColorSpace
Obtains the color space type.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| [ColorSpace](#colorspace) | Color space type.|
**Example**
```js
try {
let csType = colorSpace.getColorSpaceName();
} catch (err) {
console.log(`Fail to get colorSpace's name. Cause: ` + JSON.stringify(err));
}
```
### getWhitePoint
getWhitePoint(): Array\<number\>
Obtains the coordinates of the white point of the color space.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| Array\<number\> | Coordinates [x, y] of the white point.|
**Example**
```js
try {
let wp = colorSpace.getWhitePoint();
} catch (err) {
console.log(`Failed to get white point. Cause: ` + JSON.stringify(err));
}
```
### getGamma
getGamma(): number
Obtains the gamma of the color space.
**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core
**Return value**
| Type | Description |
| ------------------ | ------------------------ |
| number | Gamma of the color space.|
**Example**
```js
try {
let gamma = colorSpace.getGamma();
} catch (err) {
console.log(`Failed to get gamma. Cause: ` + JSON.stringify(err));
}
```
...@@ -167,7 +167,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v ...@@ -167,7 +167,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v
| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | | COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. |
| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | | COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. |
| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | | COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. |
| COMMON_EVENT_SPLIT_SCREEN<sup>8+<sup> | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | | COMMON_EVENT_SPLIT_SCREEN<sup>8+<sup> | usual.event.SPLIT_SCREEN | - | Indicates the common event of screen splitting. |
| COMMON_EVENT_SLOT_CHANGE<sup>9+<sup> | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | | COMMON_EVENT_SLOT_CHANGE<sup>9+<sup> | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. |
| COMMON_EVENT_SPN_INFO_CHANGED <sup>9+<sup> | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | | COMMON_EVENT_SPN_INFO_CHANGED <sup>9+<sup> | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. |
| COMMON_EVENT_QUICK_FIX_APPLY_RESULT <sup>9+<sup> | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. | | COMMON_EVENT_QUICK_FIX_APPLY_RESULT <sup>9+<sup> | usual.event.QUICK_FIX_APPLY_RESULT | - | Indicates the common event that a quick fix is applied to the application. |
......
...@@ -726,7 +726,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. ...@@ -726,7 +726,7 @@ Sets a **DataAbilityPredicates** object to specify the index column.
in(field: string, value: Array&lt;ValueType&gt;): DataAbilityPredicates in(field: string, value: Array&lt;ValueType&gt;): DataAbilityPredicates
Sets a **DataAbilityPredicates** object to match the field with data type Array<ValueType> and value within the specified range. Sets a **DataAbilityPredicates** object to match the field with data type Array\<ValueType> and value within the specified range.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **System capability**: SystemCapability.DistributedDataManager.DataShare.Core
...@@ -754,7 +754,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< ...@@ -754,7 +754,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array<
notIn(field: string, value: Array&lt;ValueType&gt;): DataAbilityPredicates notIn(field: string, value: Array&lt;ValueType&gt;): DataAbilityPredicates
Sets a **DataAbilityPredicates** object to match the field with data type Array<ValueType> and value out of the specified range. Sets a **DataAbilityPredicates** object to match the field with data type Array\<ValueType> and value out of the specified range.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core **System capability**: SystemCapability.DistributedDataManager.DataShare.Core
......
# Device Information # Device Information
The **deviceInfo** module provides product information.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
...@@ -101,7 +101,7 @@ This is a system API. ...@@ -101,7 +101,7 @@ This is a system API.
inputMonitor.off("touch"); inputMonitor.off("touch");
``` ```
off(type: "mouse", receiver?:Callback<MouseEvent>):void off(type: "mouse", receiver?:Callback\<MouseEvent>):void
Stops listening for global mouse events. Stops listening for global mouse events.
......
此差异已折叠。
...@@ -37,4 +37,4 @@ export default class MainAbility extends Ability { ...@@ -37,4 +37,4 @@ export default class MainAbility extends Ability {
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| permissions | Array&lt;string&gt; | Yes| No| Permissions requested.| | permissions | Array&lt;string&gt; | Yes| No| Permissions requested.|
| authResults | Array&lt;number&gt; | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and **-1** means the opposite. | | authResults | Array&lt;number&gt; | Yes| No| Whether the requested permissions are granted or denied. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite. |
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册