提交 2eea83d9 编写于 作者: Y yudechen

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

Change-Id: Iaa686f91a88d13cc1204e1661241f61c7a587d99
...@@ -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)
......
# 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.');
})
}
```
...@@ -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.
} }
......
...@@ -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);
}
```
# 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.
......
...@@ -2,17 +2,15 @@ ...@@ -2,17 +2,15 @@
The **\<RichText>** component parses and displays HTML text. The **\<RichText>** component parses and displays HTML text.
> **NOTE** > **NOTE**
> >
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -20,9 +18,9 @@ RichText(content:string) ...@@ -20,9 +18,9 @@ RichText(content:string)
**Parameters** **Parameters**
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory | Description|
| -------- | -------- | -------- | -------- | -------- | | ------- | -------- | ------------- | -------- |
| content | string | Yes| - | String in HTML format.| | content | string | Yes | String in HTML format.|
## Events ## Events
...@@ -49,34 +47,38 @@ RichText(content:string) ...@@ -49,34 +47,38 @@ RichText(content:string)
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> | | \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> |
## Example ## Example
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct RichTextExample { struct RichTextExample {
@State data: string = "<h1 style='text-align: center;'>h1 heading</h1>" + @State data: string = '<h1 style="text-align: center;">h1 heading</h1>' +
"<h1 style='text-align: center;'><i>h1 italic</i></h1>" + '<h1 style="text-align: center;"><i>h1 italic</i></h1>' +
"<h1 style='text-align: center;'><u>h1 underlined</u></h1>" + '<h1 style="text-align: center;"><u>h1 underlined</u></h1>' +
"<h2 style='text-align: center;'>h2 heading</h2>" + '<h2 style="text-align: center;">h2 heading</h2>' +
"<h3 style='text-align: center;'>h3 heading</h3>" + '<h3 style="text-align: center;">h3 heading</h3>' +
"<p style='text-align: center;'>Regular paragraph</p><hr/>" + '<p style="text-align: center;">Regular paragraph</p><hr/>' +
"<div style='width: 500px;height: 500px;border: 1px solid;margin: 0auto;'>" + '<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' +
"<p style='font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)'>Font size: 35px; line height: 45px</p>" + '<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' +
"<p style='background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;'>" + '<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
"<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>" '<p>This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.</p>';
build() { build() {
Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center, Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }){ justifyContent: FlexAlign.Center }) {
RichText(this.data) RichText(this.data)
.onStart(()=>{ .onStart(() => {
console.info("RichText onStart") console.info('RichText onStart');
}) })
.onComplete(()=>{ .onComplete(() => {
console.info("RichText onComplete") console.info('RichText onComplete');
}) })
} }
} }
} }
``` ```
![richText](figures/richText.png)
...@@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.<br>Default value: **1**| | fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | SwipeDirection | No| Swipe direction.<br>Default value: **SwipeDirection.All**| | direction | [swipeDirection](#swipedirection)| No| Swipe direction.<br>Default value: **SwipeDirection.All**|
| speed | number | No| Minimum speed of the swipe gesture, in vp/s.<br>Default value: **100**| | speed | number | No| Minimum speed of the swipe gesture, in vp/s.<br>Default value: **100**|
## SwipeDirection ## SwipeDirection
...@@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| All | All directions.| | All | All directions.|
| Horizontal | Horizontal direction.| | Horizontal | Horizontal direction. The gesture event is triggered when the angle between the finger moving direction and the x-axis is less than 45 degrees.|
| Vertical | Vertical direction.| | Vertical | Vertical direction. The gesture event is triggered when the angle between the finger moving direction and the y-axis is less than 45 degrees.|
| None | Swiping disabled.| | None | Swiping disabled.|
...@@ -33,9 +33,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -33,9 +33,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) =&gt; void) | Triggered when a swipe gesture is recognized.| | onAction(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) =&gt; void) | Triggered when a swipe gesture is recognized.|
![en-us_image_0000001231374661](figures/en-us_image_0000001231374661.png)
## Example ## Example
```ts ```ts
...@@ -43,27 +42,31 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num ...@@ -43,27 +42,31 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
@Entry @Entry
@Component @Component
struct SwipeGestureExample { struct SwipeGestureExample {
@State rotateAngle : number = 0 @State rotateAngle: number = 0;
@State speed : number = 1 @State speed: number = 1;
build() { build() {
Column() { Column() {
Text("SwipGesture speed : " + this.speed) Column() {
Text("SwipGesture angle : " + this.rotateAngle) Text("SwipeGesture speed\n" + this.speed)
} Text("SwipeGesture angle\n" + this.rotateAngle)
.position({x: 80, y: 200}) }
.border({width:2}) .border({ width: 3 })
.width(260).height(260) .width(300)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) .height(200)
.gesture( .margin(100)
SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical}) .rotate({ angle: this.rotateAngle })
// The gesture event is triggered by swiping vertically with one finger.
.gesture(
SwipeGesture({ direction: SwipeDirection.Vertical })
.onAction((event: GestureEvent) => { .onAction((event: GestureEvent) => {
this.speed = event.speed this.speed = event.speed;
this.rotateAngle = event.angle this.rotateAngle = event.angle;
}) })
) )
}.width('100%')
} }
} }
``` ```
![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif) ![en-us_image_0000001231374559.png](figures/en-us_image_0000001231374559.png)
...@@ -29,7 +29,7 @@ Creates a standard **\<Flex>** component. ...@@ -29,7 +29,7 @@ Creates a standard **\<Flex>** component.
| direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. | | direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. | | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. | | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.|
...@@ -240,9 +240,7 @@ struct FlexExample4 { ...@@ -240,9 +240,7 @@ struct FlexExample4 {
} }
``` ```
![en-us_image_0000001257138371](figures/en-us_image_0000001257138371.jpg) ![en-us_image_0000001174422904](figures/en-us_image_0000001174422904.jpg)
![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif)
```ts ```ts
// xxx.ets // xxx.ets
......
...@@ -6,7 +6,7 @@ The **\<Scroll>** component scrolls the content when the layout size of a compon ...@@ -6,7 +6,7 @@ The **\<Scroll>** component scrolls the content when the layout size of a compon
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - When nesting a **\<List>** within this component, specify the width and height for the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**. > - When nesting a **\<List>** within this component, specify the width and height for the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**.
> - This component can scroll only when the size on the main axis is less than the content size. > - This component can scroll only when the size on the main axis is less than the content size.
> - The prerequisite for the component to rebound is that the component is scrolled. > - This component can produce a bounce effect only when there is more than one screen of content.
## Child Components ## Child Components
...@@ -24,11 +24,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -24,11 +24,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description | | Name | Type | Description |
| -------------- | ---------------------------------------- | --------- | | -------------- | ---------------------------------------- | --------- |
| scrollable | ScrollDirection | Scroll direction.<br>Default value: **ScrollDirection.Vertical**| | scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.<br>Default value: **ScrollDirection.Vertical**|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| scrollBarColor | string \| number \| Color | Color of the scrollbar.| | scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar.|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**| | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.None**|
## ScrollDirection ## ScrollDirection
| Name | Description | | Name | Description |
...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Horizontal | Only horizontal scrolling is supported. | | Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. | | Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. | | None | Scrolling is disabled. |
| Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br> This API is deprecated since API version 9.| | Free<sup>(deprecated) </sup> | Vertical or horizontal scrolling is supported.<br>This API is deprecated since API version 9. |
## Events ## Events
...@@ -104,7 +104,7 @@ Scrolls to the next or previous page. ...@@ -104,7 +104,7 @@ Scrolls to the next or previous page.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------- | ---- | ------------------------------ | | --------- | ------- | ---- | ------------------------------ |
| next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br> This API is deprecated since API version 9. | | direction<sup>(deprecated) </sup> | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.<br>This API is deprecated since API version 9. |
### currentOffset ### currentOffset
...@@ -161,14 +161,15 @@ Scrolls by the specified amount. ...@@ -161,14 +161,15 @@ Scrolls by the specified amount.
## Example ## Example
### Example 1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct ScrollExample { struct ScrollExample {
scroller: Scroller = new Scroller() scroller: Scroller = new Scroller();
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
build() { build() {
Stack({ alignContent: Alignment.TopStart }) { Stack({ alignContent: Alignment.TopStart }) {
...@@ -186,38 +187,39 @@ struct ScrollExample { ...@@ -186,38 +187,39 @@ struct ScrollExample {
}, item => item) }, item => item)
}.width('100%') }.width('100%')
} }
.scrollable(ScrollDirection.Vertical) .scrollable(ScrollDirection.Vertical) // The scrollbar scrolls in the vertical direction.
.scrollBar(BarState.On) .scrollBar(BarState.On) // The scrollbar is always displayed.
.scrollBarColor(Color.Gray) .scrollBarColor(Color.Gray) // Color of the scrollbar.
.scrollBarWidth(30) .scrollBarWidth(30) // Width of the scrollbar.
.edgeEffect(EdgeEffect.None)
.onScroll((xOffset: number, yOffset: number) => { .onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset) console.info(xOffset + ' ' + yOffset);
}) })
.onScrollEdge((side: Edge) => { .onScrollEdge((side: Edge) => {
console.info('To the edge') console.info('To the edge');
}) })
.onScrollEnd(() => { .onScrollEnd(() => {
console.info('Scroll Stop') console.info('Scroll Stop');
}) })
Button('scroll 150') Button('scroll 150')
.onClick(() => { // Click to scroll down to 150.0 vp. .onClick(() => { // Click to scroll down to 150.0 vp.
this.scroller.scrollBy(0,150) this.scroller.scrollBy(0,150);
}) })
.margin({ top: 10, left: 20 }) .margin({ top: 10, left: 20 })
Button('scroll 100') Button('scroll 100')
.onClick(() => { // Click to scroll down by 100.0 vp. .onClick(() => { // Click to scroll down by 100.0 vp.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 });
}) })
.margin({ top: 60, left: 20 }) .margin({ top: 60, left: 20 })
Button('back top') Button('back top')
.onClick(() => { // Click to go back to the top. .onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top) this.scroller.scrollEdge(Edge.Top);
}) })
.margin({ top: 110, left: 20 }) .margin({ top: 110, left: 20 })
Button('next page') Button('next page')
.onClick(() => { // Click to go to the next page. .onClick(() => { // Click to go to the next page.
this.scroller.scrollPage({ next: true }) this.scroller.scrollPage({ next: true });
}) })
.margin({ top: 170, left: 20 }) .margin({ top: 170, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC) }.width('100%').height('100%').backgroundColor(0xDCDCDC)
...@@ -227,14 +229,14 @@ struct ScrollExample { ...@@ -227,14 +229,14 @@ struct ScrollExample {
![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) ![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif)
### Example 2
```ts ```ts
@Entry @Entry
@Component @Component
struct NestedScroll { struct NestedScroll {
@State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list. @State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
private scroller: Scroller = new Scroller() private scroller: Scroller = new Scroller();
build() { build() {
Flex() { Flex() {
...@@ -255,18 +257,18 @@ struct NestedScroll { ...@@ -255,18 +257,18 @@ struct NestedScroll {
} }
.width("100%").height("50%").edgeEffect(EdgeEffect.None) .width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => { .onReachStart(() => {
this.listPosition = 0 this.listPosition = 0;
}) })
.onReachEnd(() => { .onReachEnd(() => {
this.listPosition = 2 this.listPosition = 2;
}) })
.onScrollBegin((dx: number, dy: number) => { .onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy) this.scroller.scrollBy(0, -dy);
return { dxRemain: dx, dyRemain: 0 } return { dxRemain: dx, dyRemain: 0 };
} }
this.listPosition = 1; this.listPosition = 1;
return { dxRemain: dx, dyRemain: dy } return { dxRemain: dx, dyRemain: dy };
}) })
Text("Scroll Area") Text("Scroll Area")
......
# Time Picker Dialog Box # Time Picker Dialog Box
A time picker dialog box is a dialog box that allows users to select a time from the given range, which is from 00:00 to 23:59 by default. A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## TimePickerDialog.show ## TimePickerDialog.show
...@@ -18,71 +13,63 @@ show(options?: TimePickerDialogOptions) ...@@ -18,71 +13,63 @@ show(options?: TimePickerDialogOptions)
Shows a time picker dialog box. Shows a time picker dialog box.
- TimePickerDialogOptions - TimePickerDialogOptions
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | Name| Type| Mandatory| Description|
| selected | Date | No| Current system time| Time of the selected item.| | -------- | -------- | -------- | -------- |
| useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| | selected | Date | No| Selected time.<br>Default value: current system time|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| | useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.<br>Default value: **false**|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.| | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.|
## Example ## Example
### Time Picker Sample Code (24-Hour Clock)
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
@Component @Component
struct TimePickerDialogExample01 { struct TimePickerDialogExample {
@State isUseMilitaryTime: boolean = true private selectTime: Date = new Date('2020-12-25T08:30:00')
build() { build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, Column() {
justifyContent: FlexAlign.Center }) { Button ("TimePickerDialog 12-hour format")
Button("TimePickerDialog").onClick(() => { .margin(20)
TimePickerDialog.show({ .onClick(() => {
useMilitaryTime: this.isUseMilitaryTime, TimePickerDialog.show({
onAccept: (value: TimePickerResult) => { selected: this.selectTime,
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) onAccept: (value: TimePickerResult) => {
}, //Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
onCancel: () => { this.selectTime.setHours(value.hour, value.minute)
console.info("TimePickerDialog:onCancel()") console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
}, },
onChange: (value: TimePickerResult) => { onCancel: () => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) console.info("TimePickerDialog:onCancel()");
} },
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
}
})
}) })
}) Button ("TimePickerDialog 24-hour format")
} .margin(20)
} .onClick(() => {
} TimePickerDialog.show({
``` selected: this.selectTime,
### Time Picker Sample Code (12-Hour Clock) useMilitaryTime: true,
```ts onAccept: (value: TimePickerResult) => {
// xxx.ets this.selectTime.setHours(value.hour, value.minute)
@Entry console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
@Component },
struct TimePickerDialogExample02 { onCancel: () => {
@State isUseMilitaryTime: boolean = false console.info("TimePickerDialog:onCancel()");
},
build() { onChange: (value: TimePickerResult) => {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
justifyContent: FlexAlign.Center }) { }
Button("TimePickerDialog").onClick(() => { })
TimePickerDialog.show({
useMilitaryTime: this.isUseMilitaryTime,
onAccept: (value: TimePickerResult) => {
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
}) })
}) }.width('100%')
}
} }
} }
``` ```
...@@ -77,7 +77,7 @@ Sends a touch event. ...@@ -77,7 +77,7 @@ Sends a touch event.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ----------- | ---- | ------------------------------------------------------------ | | ----- | ----------- | ---- | ------------------------------------------------------------ |
| event | TouchObject | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| | event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
**Return value** **Return value**
...@@ -95,7 +95,7 @@ Sends a key event. ...@@ -95,7 +95,7 @@ Sends a key event.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | -------- | ---- | ------------------------------------------------------------ | | ----- | -------- | ---- | ------------------------------------------------------------ |
| event | KeyEvent | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| | event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
**Return value** **Return value**
...@@ -113,7 +113,7 @@ Sends a mouse event. ...@@ -113,7 +113,7 @@ Sends a mouse event.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----- | ---------- | ---- | --------------------------------------- | | ----- | ---------- | ---- | --------------------------------------- |
| event | MouseEvent | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| | event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
**Return value** **Return value**
...@@ -132,6 +132,7 @@ class Utils { ...@@ -132,6 +132,7 @@ class Utils {
static rect_bottom; static rect_bottom;
static rect_value; static rect_value;
// Obtain the coordinates of the rectangular area occupied by the component.
static getComponentRect(key) { static getComponentRect(key) {
let strJson = getInspectorByKey(key); let strJson = getInspectorByKey(key);
let obj = JSON.parse(strJson); let obj = JSON.parse(strJson);
...@@ -171,7 +172,7 @@ struct IdExample { ...@@ -171,7 +172,7 @@ struct IdExample {
console.info(getInspectorTree()) console.info(getInspectorTree())
this.text = "Button 'click to start' is clicked" this.text = "Button 'click to start' is clicked"
setTimeout(() => { setTimeout(() => {
sendEventByKey("longClick", 11, "") sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick".
}, 2000) }, 2000)
}).id('click') }).id('click')
...@@ -183,18 +184,18 @@ struct IdExample { ...@@ -183,18 +184,18 @@ struct IdExample {
console.info('long clicked') console.info('long clicked')
this.text = "Button 'longClick' is longclicked" this.text = "Button 'longClick' is longclicked"
setTimeout(() => { setTimeout(() => {
let rect = Utils.getComponentRect('onTouch') let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch".
let touchPoint: TouchObject = { let touchPoint: TouchObject = {
id: 1, id: 1,
x: rect.left + (rect.right - rect.left) / 2, x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
y: rect.top + (rect.bottom - rect.top) / 2, y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
type: TouchType.Down, type: TouchType.Down,
screenX: rect.left + (rect.right - rect.left) / 2, screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
screenY: rect.left + (rect.right - rect.left) / 2, screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center.
} }
sendTouchEvent(touchPoint) sendTouchEvent(touchPoint) // Send a touch event.
touchPoint.type = TouchType.Up touchPoint.type = TouchType.Up
sendTouchEvent(touchPoint) sendTouchEvent(touchPoint) // Send a touch event.
}, 2000) }, 2000)
})).id('longClick') })).id('longClick')
...@@ -205,14 +206,14 @@ struct IdExample { ...@@ -205,14 +206,14 @@ struct IdExample {
console.info('onTouch is clicked') console.info('onTouch is clicked')
this.text = "Button 'onTouch' is clicked" this.text = "Button 'onTouch' is clicked"
setTimeout(() => { setTimeout(() => {
let rect = Utils.getComponentRect('onMouse') let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse".
let mouseEvent: MouseEvent = { let mouseEvent: MouseEvent = {
button: MouseButton.Left, button: MouseButton.Left,
action: MouseAction.Press, action: MouseAction.Press,
x: rect.left + (rect.right - rect.left) / 2, x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
y: rect.top + (rect.bottom - rect.top) / 2, y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
screenX: rect.left + (rect.right - rect.left) / 2, screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center.
screenY: rect.top + (rect.bottom - rect.top) / 2, screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center.
timestamp: 1, timestamp: 1,
target: { target: {
area: { area: {
...@@ -230,7 +231,7 @@ struct IdExample { ...@@ -230,7 +231,7 @@ struct IdExample {
}, },
source: SourceType.Mouse source: SourceType.Mouse
} }
sendMouseEvent(mouseEvent) sendMouseEvent(mouseEvent) // Send a mouse event.
}, 2000) }, 2000)
}).id('onTouch') }).id('onTouch')
...@@ -250,7 +251,7 @@ struct IdExample { ...@@ -250,7 +251,7 @@ struct IdExample {
metaKey: 0, metaKey: 0,
timestamp: 0 timestamp: 0
} }
sendKeyEvent(keyEvent) sendKeyEvent(keyEvent) // Send a key event.
}, 2000) }, 2000)
}).id('onMouse') }).id('onMouse')
......
...@@ -23,7 +23,6 @@ ...@@ -23,7 +23,6 @@
@Entry @Entry
@Component @Component
struct FlexExample { struct FlexExample {
build() { build() {
Column({ space: 5 }) { Column({ space: 5 }) {
Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -31,11 +30,18 @@ struct FlexExample { ...@@ -31,11 +30,18 @@ struct FlexExample {
// The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height(). // The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height().
Flex() { Flex() {
Text('flexBasis(100)') Text('flexBasis(100)')
.flexBasis('100').height(100).lineHeight(70) .flexBasis('100')
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexBasis("auto")') Text('flexBasis("auto")')
.flexBasis('auto').width('60%').height(100).lineHeight(70) .flexBasis('auto')
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('60%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -43,11 +49,17 @@ struct FlexExample { ...@@ -43,11 +49,17 @@ struct FlexExample {
// flexGrow() specifies the percentage of the remaining space allocated to the component. // flexGrow() specifies the percentage of the remaining space allocated to the component.
Flex() { Flex() {
Text('flexGrow(2)') Text('flexGrow(2)')
.flexGrow(2).height(100).lineHeight(70) .flexGrow(2)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexGrow(1)') Text('flexGrow(1)')
.flexGrow(1).height(100).lineHeight(70) .flexGrow(1)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -55,13 +67,25 @@ struct FlexExample { ...@@ -55,13 +67,25 @@ struct FlexExample {
// The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk. // The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk.
Flex({ direction: FlexDirection.Row }) { Flex({ direction: FlexDirection.Row }) {
Text('flexShrink(0)') Text('flexShrink(0)')
.flexShrink(0).width('50%').height(100).lineHeight(70) .flexShrink(0)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .width('50%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('no flexShrink') Text('no flexShrink')
.width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('flexShrink(2)') Text('flexShrink(2)')
.flexShrink(2).width('40%').height(100) .lineHeight(70) .flexShrink(2)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%')
...@@ -70,8 +94,12 @@ struct FlexExample { ...@@ -70,8 +94,12 @@ struct FlexExample {
Text('no alignSelf,height:80').width('33%').height(80) Text('no alignSelf,height:80').width('33%').height(80)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('alignSelf stretch') Text('alignSelf stretch')
.alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70) .alignSelf(ItemAlign.Stretch)
.backgroundColor(0xD2B48C).textAlign(TextAlign.Center) .width('33%')
.height(80)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('no alignSelf,height:100').width('34%').height(100) Text('no alignSelf,height:100').width('34%').height(100)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
......
...@@ -12,7 +12,7 @@ You can set the opacity of a component. ...@@ -12,7 +12,7 @@ You can set the opacity of a component.
| Name | Type | Description | | Name | Type | Description |
| ------- | ---------------------------------------- | ---------------------------------------- | | ------- | ---------------------------------------- | ---------------------------------------- |
| opacity | number \| [Resource](ts-types.md#resource) | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.<br>Default value: **1**| | opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout.<br>**NOTE**<br>A child component can inherit this attribute of its parent component. Default value: **1**|
## Example ## Example
...@@ -30,6 +30,10 @@ struct OpacityExample { ...@@ -30,6 +30,10 @@ struct OpacityExample {
Text().width('90%').height(50).opacity(0.7).backgroundColor(0xAFEEEE) Text().width('90%').height(50).opacity(0.7).backgroundColor(0xAFEEEE)
Text('opacity(0.4)').fontSize(9).width('90%').fontColor(0xCCCCCC) Text('opacity(0.4)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0.4).backgroundColor(0xAFEEEE) Text().width('90%').height(50).opacity(0.4).backgroundColor(0xAFEEEE)
Text('opacity(0.1)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0.1).backgroundColor(0xAFEEEE)
Text('opacity(0)').fontSize(9).width('90%').fontColor(0xCCCCCC)
Text().width('90%').height(50).opacity(0).backgroundColor(0xAFEEEE)
} }
.width('100%') .width('100%')
.padding({ top: 5 }) .padding({ top: 5 })
...@@ -37,4 +41,4 @@ struct OpacityExample { ...@@ -37,4 +41,4 @@ struct OpacityExample {
} }
``` ```
![en-us_image_0000001256858385](figures/en-us_image_0000001256858385.gif) ![opacity.png](figures/opacity.png)
# Visible Area Change Event # Visible Area Change Event
The visible area change event of a component refers to the change in the visual portion of a component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing. The visible area change event of a component refers to the change in the visual portion of the component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing.
> **NOTE** > **NOTE**
> >
...@@ -23,8 +23,8 @@ The visible area change event of a component refers to the change in the visual ...@@ -23,8 +23,8 @@ The visible area change event of a component refers to the change in the visual
struct ScrollExample { struct ScrollExample {
scroller: Scroller = new Scroller() scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State testTextStr: string = "test" @State testTextStr: string = 'test'
@State testRowStr: string = "test" @State testRowStr: string = 'test'
build() { build() {
Column() { Column() {
...@@ -46,22 +46,22 @@ struct ScrollExample { ...@@ -46,22 +46,22 @@ struct ScrollExample {
.height(200) .height(200)
.margin({ top: 50, bottom: 20 }) .margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green) .backgroundColor(Color.Green)
// Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen. // Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen.
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio) console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) { if (isVisible && currentRatio >= 1.0) {
console.info("Test Text is fully visible. currentRatio:" + currentRatio) console.info('Test Text is fully visible. currentRatio:' + currentRatio)
this.testTextStr = "Test Text is fully visible" this.testTextStr = 'Test Text is fully visible'
} }
if (!isVisible && currentRatio <= 0.0) { if (!isVisible && currentRatio <= 0.0) {
console.info("Test Text is completely invisible.") console.info('Test Text is completely invisible.')
this.testTextStr = "Test Text is completely invisible" this.testTextStr = 'Test Text is completely invisible'
} }
}) })
Row() { Row() {
Text("Test Row Visible Change") Text('Test Row Visible Change')
.fontSize(20) .fontSize(20)
.margin({ bottom: 20 }) .margin({ bottom: 20 })
...@@ -69,15 +69,15 @@ struct ScrollExample { ...@@ -69,15 +69,15 @@ struct ScrollExample {
.height(200) .height(200)
.backgroundColor(Color.Yellow) .backgroundColor(Color.Yellow)
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio) console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio)
if (isVisible && currentRatio >= 1.0) { if (isVisible && currentRatio >= 1.0) {
console.info("Test Row is fully visible.") console.info('Test Row is fully visible.')
this.testRowStr = "Test Row is fully visible" this.testRowStr = 'Test Row is fully visible'
} }
if (!isVisible && currentRatio <= 0.0) { if (!isVisible && currentRatio <= 0.0) {
console.info("Test Row is is completely invisible.") console.info('Test Row is is completely invisible.')
this.testRowStr = "Test Row is is completely invisible" this.testRowStr = 'Test Row is is completely invisible'
} }
}) })
......
# Device Management Error Codes
## 11600101 Service Invoking Exception
**Error Message**
Failed to execute the function.
**Possible Causes**
An error occurred during internal invocation.
**Procedure**
Call the API again.
## 11600102 Failed to Obtain the Service
**Error Message**
Failed to obtain the service.
**Possible Causes**
The service is not started or fails to start.
**Procedure**
Check whether the service is started normally and obtain the service again.
## 11600103 Authentication Unavailable
**Error Message**
Authentication invalid.
**Possible Causes**
The last authentication service is still in progress.
**Procedure**
Wait until the last authentication service is complete and call the authentication API again.
## 11600104 Discovery Unavailable
**Error Message**
Discovery invalid.
**Possible Causes**
The last discovery service is still in progress.
**Procedure**
Wait until the last discovery service is complete and call the discovery API again.
## 11600105 Publish Unavailable
**Error Message**
Publish invalid.
**Possible Causes**
The last publish service is still in progress.
**Procedure**
Wait until the last publish service is complete and call the publish API again.
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
SysCap, short for System Capability, refers to a standalone feature in the operating system. SysCap, short for System Capability, refers to a standalone feature in the operating system.
Before using an API for development, you are advised to read [SysCap](../quick-start/syscap.md) to familiarize yourself with Syscap, and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. Before using an API for development, you are advised to familiarize yourself with [SysCap](../quick-start/syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type.
## SystemCapability.ArkUI.ArkUI.Full ## SystemCapability.ArkUI.ArkUI.Full
......
# @Builder # @Builder
The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. The functionality and syntax of the **@Builder** decorator are the same as those of the [build Function](ts-function-build.md). The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. If a custom component is used in the **@Builder** decorated method, this component will be re-created each time the method is invoked. The functionality and syntax of the **@Builder** decorator are the same as those of the **build** function.
```ts ```ts
// xxx.ets // xxx.ets
@Component
struct CompB {
@State CompValue: string = '';
aboutToAppear() {
console.info('CompB aboutToAppear.');
}
aboutToDisappear() {
console.info('CompB aboutToDisappear.');
}
build() {
Column() {
Button(this.CompValue);
}
}
}
@Entry @Entry
@Component @Component
struct CompA { struct CompA {
size1 : number = 100; size1: number = 100;
@State CompValue1: string = "Hello,CompValue1";
@State CompValue2: string = "Hello,CompValue2";
@State CompValue3: string = "Hello,CompValue3";
// Use a custom component in the @Builder decorated method.
@Builder CompC(value: string) {
CompB({ CompValue: value });
}
@Builder SquareText(label: string) { @Builder SquareText(label: string) {
Text(label) Text(label)
...@@ -35,7 +63,16 @@ struct CompA { ...@@ -35,7 +63,16 @@ struct CompA {
} }
.width(2 * this.size1) .width(2 * this.size1)
.height(1 * this.size1) .height(1 * this.size1)
this.RowOfSquareTexts("C", "D") this.RowOfSquareTexts("C", "D")
Column() {
// Use the custom component in the @Builder decorated method three times.
this.CompC(this.CompValue1);
this.CompC(this.CompValue2);
this.CompC(this.CompValue3);
}
.width(2 * this.size1)
.height(2 * this.size1)
} }
.width(2 * this.size1) .width(2 * this.size1)
.height(2 * this.size1) .height(2 * this.size1)
...@@ -99,7 +136,7 @@ struct CustomContainerUser { ...@@ -99,7 +136,7 @@ struct CustomContainerUser {
} }
``` ```
### Component Initialization Through Trailing Closure ### Component Initialization Through Trailing Closure
In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of [build](../ui/ts-function-build.md). In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute. In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of the **build** function. In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute.
Example: Add a **\<Column>** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\<Column>** component. After the **\<Column>** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**. Example: Add a **\<Column>** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\<Column>** component. After the **\<Column>** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**.
```ts ```ts
......
# Adding Title and Paragraph Text # Adding Title and Paragraph Text
The **\<text>** component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a **\<text>** component and add the text to be displayed between the **\<text>** and **\</text>** tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page:
The &lt;text&gt; component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a &lt;text&gt; component and add the text to be displayed between the &lt;text&gt; and &lt;/text&gt; tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page:
```html ```html
...@@ -26,8 +25,10 @@ The &lt;text&gt; component is most commonly used to display text in title and pa ...@@ -26,8 +25,10 @@ The &lt;text&gt; component is most commonly used to display text in title and pa
font-size: 50px; font-size: 50px;
margin-top: 40px; margin-top: 40px;
margin-bottom: 20px; margin-bottom: 20px;
font-weight: 700;
} }
.paragraph-text { .paragraph-text {
width: 95%;
color: #000000; color: #000000;
font-size: 35px; font-size: 35px;
line-height: 60px; line-height: 60px;
...@@ -39,9 +40,11 @@ The &lt;text&gt; component is most commonly used to display text in title and pa ...@@ -39,9 +40,11 @@ The &lt;text&gt; component is most commonly used to display text in title and pa
// xxx.js // xxx.js
export default { export default {
data: { data: {
headTitle: 'Capture the Beauty in This Moment', headTitle: 'Capture the Beauty in Moment',
paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.', paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.',
paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.', paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.',
}, },
} }
``` ```
![en-us_image_0000001118642600](figures/en-us_image_0000001118642600.PNG)
# &lt;grid-container&gt; Development # Grid Layout
The **&lt;grid-container&gt;** component is the root container of the grid layout. Within the root container, you can use **&lt;grid-row&gt;** and **&lt;grid-col&gt;** for the grid layout. For details, see [grid-container](../reference/arkui-js/js-components-grid-container.md). The **\<grid-container>** component is the root container of the grid layout. Within the root container, you can use **\<grid-row>** and **\<grid-col>** for the grid layout. For details, see [Grid-container](../reference/arkui-js/js-components-grid-container.md).
## Creating a &lt;grid-container&gt; Component ## Creating a \<grid-container> Component
Create a **&lt;grid-container&gt;** component in the .hml file under **pages/index** and add a [**&lt;grid-row&gt;**](../reference/arkui-js/js-components-grid-row.md) child component. Create a **\<grid-container>** component in the .hml file under **pages/index** and add a [\<Grid-row>](../reference/arkui-js/js-components-grid-row.md) child component.
```html ```html
...@@ -37,12 +37,12 @@ Create a **&lt;grid-container&gt;** component in the .hml file under **pages/ind ...@@ -37,12 +37,12 @@ Create a **&lt;grid-container&gt;** component in the .hml file under **pages/ind
> **NOTE** > **NOTE**
> >
> **&lt;grid-container&gt;** supports only **&lt;grid-row&gt;** as a child component. > **\<grid-container>** supports only **\<grid-row>** as a child component.
## Methods ## Methods
Click the **&lt;grid-container&gt;** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**). Touch the **\<grid-container>** component to call the **getColumns**, **getColumnWidth**, and **getGutterWidth** methods to return the number of columns in the grid container, and column width and gutter width of the grid container. Press and hold the component to call the **getSizeType** method to return the size-responsive type of the grid container (**xs**|**sm**|**md**|**lg**).
```html ```html
...@@ -109,9 +109,9 @@ export default { ...@@ -109,9 +109,9 @@ export default {
![en-us_image_0000001231843088](figures/en-us_image_0000001231843088.gif) ![en-us_image_0000001231843088](figures/en-us_image_0000001231843088.gif)
## Adding &lt;grid-col&gt; ## Adding \<grid-col>
After adding a **&lt;grid-row&gt;** child component to **&lt;grid-container&gt;**, add a **&lt;grid-col&gt;** child component to **&lt;grid-row&gt;** to form a layout. After adding a **\<grid-row>** child component to **\<grid-container>**, add a **\<grid-col>** child component to **\<grid-row>** to form a layout.
```html ```html
...@@ -168,7 +168,7 @@ text{ ...@@ -168,7 +168,7 @@ text{
> **NOTE** > **NOTE**
> >
> **&lt;grid-row&gt;** supports only **&lt;grid-col&gt;** as a child component. You can add content only to **&lt;grid-col&gt;**. > **\<grid-row>** supports only **\<grid-col>** as a child component. You can add content only to **\<grid-col>**.
## Example Scenario ## Example Scenario
...@@ -243,4 +243,4 @@ export default { ...@@ -243,4 +243,4 @@ export default {
``` ```
![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif) ![en-us_image_0000001276003501](figures/en-us_image_0000001276003501.gif)
\ No newline at end of file
# OffscreenCanvasRenderingContext2D # OffscreenCanvasRenderingContext2D
**OffscreenCanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on an offscreen canvas. For details, see [OffscreenCanvasRenderingContext2D](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md). **OffscreenCanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on an offscreen canvas, which is a new buffer created by the GPU outside of the current buffer. For details, see [OffscreenCanvasRenderingContext2D](../reference/arkui-js/js-offscreencanvasrenderingcontext2d.md).
Create an **OffscreenCanvas** and then a **getContext2d** object on the canvas. Then, create an image and set the **filter** attribute to change the image style. In the following example, you first create an offscreen canvas, and then create a **getContext2d** object on the canvas, which is an image, and finally set the **filter** attribute for the image.
```html ```html
<!-- xxx.hml --> <!-- xxx.hml -->
...@@ -86,7 +86,7 @@ export default { ...@@ -86,7 +86,7 @@ export default {
## Determining the Position ## Determining the Position
Use **isPointInPath** and **isPointInStroke** to determine and show whether a coordinate is within the path area and whether a coordinate is on the edge of the path. Use **isPointInPath** to determine whether a coordinate is within the path area and use **isPointInStroke** to determine whether a coordinate is on the edge of the path.
```html ```html
...@@ -181,4 +181,4 @@ export default { ...@@ -181,4 +181,4 @@ export default {
} }
``` ```
![en-us_image_0000001276003489](figures/en-us_image_0000001276003489.gif) ![en-us_image_0000001178084014](figures/en-us_image_0000001178084014.gif)
# Window Manager # Window Manager
- [Window Overview](window-overview.md) - [Window Overview](window-overview.md)
- [System Window Development (Stage Model Only)](application-window-stage.md) - [Application Window Development (Stage Mode)](application-window-stage.md)
- [Application Window Development (FA Model)](application-window-fa.md) - [Application Window Development (FA Model)](application-window-fa.md)
- [Application Window Development (Stage Mode)](system-window-stage.md) - [System Window Development (Stage Model Only)](system-window-stage.md)
...@@ -32,7 +32,7 @@ The table below lists the common APIs used for application window development. F ...@@ -32,7 +32,7 @@ The table below lists the common APIs used for application window development. F
| WindowStage | getMainWindow(callback: AsyncCallback&lt;Window&gt;): void | Obtains the main window of this window stage.<br>This API can be used only in the stage model.| | WindowStage | getMainWindow(callback: AsyncCallback&lt;Window&gt;): void | Obtains the main window of this window stage.<br>This API can be used only in the stage model.|
| WindowStage | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to the main window in this window stage.<br>This API can be used only in the stage model.| | WindowStage | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to the main window in this window stage.<br>This API can be used only in the stage model.|
| WindowStage | createSubWindow(name: string, callback: AsyncCallback&lt;Window&gt;): void | Creates a subwindow.<br>This API can be used only in the stage model.| | WindowStage | createSubWindow(name: string, callback: AsyncCallback&lt;Window&gt;): void | Creates a subwindow.<br>This API can be used only in the stage model.|
| Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void | Creates a subwindow.<br>-`ctx`: application context.<br>-`type`: window type.| | Window static method| create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void | Creates a subwindow.<br>- **ctx**: application context.<br>- **type**: window type.|
| Window | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to this window.| | Window | loadContent(path: string, callback: AsyncCallback&lt;void&gt;): void | Loads the page content to this window.|
| Window | setBackgroundColor(color: string, callback: AsyncCallback&lt;void&gt;): void | Sets the background color for this window.| | Window | setBackgroundColor(color: string, callback: AsyncCallback&lt;void&gt;): void | Sets the background color for this window.|
| Window | setBrightness(brightness: number, callback: AsyncCallback&lt;void&gt;): void | Sets the brightness for this window.| | Window | setBrightness(brightness: number, callback: AsyncCallback&lt;void&gt;): void | Sets the brightness for this window.|
...@@ -42,7 +42,7 @@ The table below lists the common APIs used for application window development. F ...@@ -42,7 +42,7 @@ The table below lists the common APIs used for application window development. F
| Window | setFullScreen(isFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for this window.| | Window | setFullScreen(isFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for this window.|
| Window | setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for the window layout. | | Window | setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void | Sets whether to enable the full-screen mode for the window layout. |
| Window | setSystemBarEnable(names: Array&lt;'status'\|'navigation'&gt;): Promise&lt;void&gt; | Sets whether to display the status bar and navigation bar in this window.| | Window | setSystemBarEnable(names: Array&lt;'status'\|'navigation'&gt;): Promise&lt;void&gt; | Sets whether to display the status bar and navigation bar in this window.|
| Window | setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback&lt;void&gt;): void | Sets the properties of the status bar and navigation bar in this window.<br>`systemBarProperties`: properties of the status bar and navigation bar.| | Window | setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback&lt;void&gt;): void | Sets the properties of the status bar and navigation bar in this window.<br>**systemBarProperties**: properties of the status bar and navigation bar.|
| Window | show(callback: AsyncCallback\<void>): void | Shows this window.| | Window | show(callback: AsyncCallback\<void>): void | Shows this window.|
| Window | on(type: 'touchOutside', callback: Callback&lt;void&gt;): void | Enables listening for click events outside this window.| | Window | on(type: 'touchOutside', callback: Callback&lt;void&gt;): void | Enables listening for click events outside this window.|
| Window | destroy(callback: AsyncCallback&lt;void&gt;): void | Destroys this window.| | Window | destroy(callback: AsyncCallback&lt;void&gt;): void | Destroys this window.|
...@@ -50,19 +50,22 @@ The table below lists the common APIs used for application window development. F ...@@ -50,19 +50,22 @@ The table below lists the common APIs used for application window development. F
## Setting the Main Window of an Application ## Setting the Main Window of an Application
In the stage model, the main window of an application is created and maintained by an `Ability` instance. In the `onWindowStageCreate` callback of the `Ability` instance, use `WindowStage` to obtain the main window of the application and set its properties. In the stage model, the main window of an application is created and maintained by an **Ability** instance. In the **onWindowStageCreate** callback of the **Ability** instance, use **WindowStage** to obtain the main window of the application and set its properties.
### How to Develop ### How to Develop
1. Obtain the main window. 1. Obtain the main window.
Call `getMainWindow` to obtain the main window of the application.
Call **getMainWindow** to obtain the main window of the application.
2. Set the properties of the main window. 2. Set the properties of the main window.
You can set multiple properties of the main window, such as the background color, brightness, and whether the main window is touchable. The code snippet below uses the `touchable` property as an example.
You can set multiple properties of the main window, such as the background color, brightness, and whether the main window is touchable. The code snippet below uses the **touchable** property as an example.
3. Load content for the main window. 3. Load content for the main window.
Call `loadContent` to load the page content to the main window.
Call **loadContent** to load the page content to the main window.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
...@@ -109,19 +112,23 @@ You can create an application subwindow, such as a dialog box, and set its prope ...@@ -109,19 +112,23 @@ You can create an application subwindow, such as a dialog box, and set its prope
### How to Develop ### How to Develop
1. Create or obtain a subwindow. 1. Create or obtain a subwindow.
Call `createSubWindow` to create a subwindow.
Call `getSubWindow` to obtain a subwindow. Call **createSubWindow** to create a subwindow.
Call **getSubWindow** to obtain a subwindow.
2. Set the properties of the subwindow. 2. Set the properties of the subwindow.
After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness. After the subwindow is created, you can set its properties, such as the size, position, background color, and brightness.
3. Load content for the subwindow and show it. 3. Load content for the subwindow and show it.
Call `loadContent` and `show` to load and display the content in the subwindow.
Call **loadContent** and **show** to load and display the content in the subwindow.
4. Destroy the subwindow. 4. Destroy the subwindow.
When the subwindow is no longer needed, you can call `destroy` to destroy it.
When the subwindow is no longer needed, you can call **destroy** to destroy it.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
...@@ -201,16 +208,18 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -201,16 +208,18 @@ To create a better video watching and gaming experience, you can use the immersi
### How to Develop ### How to Develop
1. Obtain the main window. 1. Obtain the main window.
Call `getMainWindow` to obtain the main window of the application.
Call **getMainWindow** to obtain the main window of the application.
2. Implement the immersive effect. You can use any of the following methods: 2. Implement the immersive effect. You can use any of the following methods:
- Method 1: Call `setFullScreen` to set the main window to be displayed in full screen. In this case, the navigation bar and status bar are hidden. - Method 1: Call **setFullScreen** to set the main window to be displayed in full screen. In this case, the navigation bar and status bar are hidden.
- Method 2: Call `setSystemBarEnable` to hide the navigation bar and status bar. - Method 2: Call **setSystemBarEnable** to hide the navigation bar and status bar.
- Method 3: Call `setLayoutFullScreen` to enable the full-screen mode for the main window layout. Call `setSystemProperties` to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window. - Method 3: Call **setLayoutFullScreen** to enable the full-screen mode for the main window layout. Call **setSystemProperties** to set the opacity, background color, text color, and highlighted icon of the navigation bar and status bar to ensure that their display effect is consistent with that of the main window.
3. Load content for the immersive window and show it. 3. Load content for the immersive window and show it.
Call `loadContent` and `show` to load and display the content in the immersive window.
Call **loadContent** to load the content to the immersive window.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
...@@ -256,9 +265,6 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -256,9 +265,6 @@ To create a better video watching and gaming experience, you can use the immersi
let sysBarProps = { let sysBarProps = {
statusBarColor: '#ff00ff', statusBarColor: '#ff00ff',
navigationBarColor: '#00ff00', navigationBarColor: '#00ff00',
// The following properties are supported since API version 7.
isStatusBarLightIcon: false,
isNavigationBarLightIcon: false,
// The following properties are supported since API version 8. // The following properties are supported since API version 8.
statusBarContentColor: '#ffffff', statusBarContentColor: '#ffffff',
navigationBarContentColor: '#ffffff' navigationBarContentColor: '#ffffff'
...@@ -278,14 +284,6 @@ To create a better video watching and gaming experience, you can use the immersi ...@@ -278,14 +284,6 @@ To create a better video watching and gaming experience, you can use the immersi
return; return;
} }
console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data));
// 3. Show the immersive window.
windowStage.show((err, data) => {
if (err.code) {
console.error('Failed to show the window. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data));
});
}); });
} }
}; };
...@@ -300,11 +298,13 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -300,11 +298,13 @@ A floating window is created based on an existing task. It is always displayed i
### How to Develop ### How to Develop
1. Apply for permissions. 1. Apply for permissions.
To create a floating window (of the `WindowType.TYPE_FLOAT` type), you must configure the `ohos.permission.SYSTEM_FLOAT_WINDOW` permission in the `requestPermissions` field of the `module.json5` file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
To create a floating window (of the **WindowType.TYPE_FLOAT** type), you must configure the **ohos.permission.SYSTEM_FLOAT_WINDOW** permission in the **requestPermissions** field of the **module.json5** file. For details about the file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md).
> **NOTE** > **NOTE**
>
> If the task for creating the floating window is reclaimed by the system, the floating window will no longer be displayed. If you want the floating window to be displayed in such a case, apply for a [continuous task](../task-management/background-task-overview.md). > If the task for creating the floating window is reclaimed by the system, the floating window will no longer be displayed. If you want the floating window to be displayed in such a case, apply for a [continuous task](../task-management/background-task-overview.md).
```json ```json
{ {
"module": { "module": {
...@@ -324,17 +324,20 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -324,17 +324,20 @@ A floating window is created based on an existing task. It is always displayed i
``` ```
2. Create a floating window. 2. Create a floating window.
Call `window.create` to create a floating window.
Call **window.create** to create a floating window.
3. Set properties for the floating window. 3. Set properties for the floating window.
After the floating window is created, you can set its properties, such as the size, position, background color, and brightness. After the floating window is created, you can set its properties, such as the size, position, background color, and brightness.
4. Load content for the floating window and show it. 4. Load content for the floating window and show it.
Call `loadContent` and `show` to load and display the content in the floating window.
Call **loadContent** and **show** to load and display the content in the floating window.
5. Destroy the floating window. 5. Destroy the floating window.
When the floating window is no longer needed, you can call `destroy` to destroy it. When the floating window is no longer needed, you can call **destroy** to destroy it.
```ts ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
...@@ -397,4 +400,4 @@ A floating window is created based on an existing task. It is always displayed i ...@@ -397,4 +400,4 @@ A floating window is created based on an existing task. It is always displayed i
}); });
} }
}; };
``` ```
\ No newline at end of file
# Drivers # Drivers
- [Driver Overview](driver-overview-foundation.md)
- HDF - HDF
- [HDF Overview](driver-hdf-overview.md) - [HDF Overview](driver-hdf-overview.md)
- [Driver Development](driver-hdf-development.md) - [Driver Development](driver-hdf-development.md)
......
# Driver Overview
## Introduction
OpenHarmony uses the multi-kernel (Linux kernel and LiteOS) design and can be deployed on devices with different resource capacities. How to smoothly adapt device drivers to different kernels on the same hardware and minimize the workloads on driver code porting and maintenance is an important issue to address in the OpenHarmony driver subsystem.
The OpenHarmony driver subsystem provides the following features and capabilities to shorten the driver development period and simplify third-party device driver integration:
- Elastic framework capabilities
Based on the traditional driver framework, the OpenHarmony driver subsystem builds elastic framework capabilities to enable deployment on terminal products with memory of hundreds KB to hundreds MB.
- Standardized driver interfaces
The OpenHarmony driver subsystem provides stable driver APIs compatible with the APIs of future-proof smartphones, tablets, smart TVs.
- Component-based driver model
The OpenHarmony driver subsystem provides the component-based driver model to implement more refined driver management. You can add or reduce components as required and focus on the interaction between the hardware and driver. The subsystem also presets some template-based driver model components, such as the network device model.
- Normalized configuration UI
The OpenHarmony driver subsystem provides a unified configuration tool that supports cross-platform configuration conversion and generation, enabling seamless switchover across platforms.
## HDF
The Hardware Driver Foundation (HDF) provides driver framework capabilities, including driver loading, driver service management, and driver messaging mechanism. It strives to build a unified driver platform to back up a more precise and efficient environment for one-time development for multi-device deployment.
The HDF is built in an object-oriented programming model in C language. It provides a unified platform base to support different kernels through platform decoupling and kernel decoupling. The figure below shows the HDF architecture.
**Figure 1** HDF architecture
![](figures/HDF-architecture.png)
The HDF consists of the following:
- Hardware Device Interface (HDI) layer: provides unified and stable APIs for hardware operations.
- HDF: provides unified hardware resource management, driver loading management, device node management, device power management, and driver service model. It consists of the device management, service management, Device Host, and PnPManager modules.
- Unified configuration interface (DevEco): supports abstract description of hardware resources, shields hardware differences, and enables development of universal driver code that is not bound to configuration information. You can use HC-Gen to quickly create configuration files. This unified configuration interface improves development and porting efficiency.
- Operating system abstraction layer (OSAL): provides encapsulated kernel operation APIs, including the APIs for the memory, locks, threads, and semaphores, to shield operation differences between different systems.
- Platform driver: provides unified APIs for peripheral drivers to operate board hardware, such as I2C, SPI, and UART buses, and uniformly abstracts the APIs for board hardware operations.
- Peripheral driver model: provides common driver abstraction models for peripheral drivers to provide standard device drivers and implement driver model abstraction. With standard device driver models, you can deploy drivers through configuration without independent development. The driver model abstraction makes the drivers more general by shielding the interaction between drivers and different system components.
## Driver Development
### Platform Drivers
The OpenHarmony platform drivers provide APIs for accessing the operating system and peripheral drivers. The platform devices refer to buses, such as I2C and UART, and specific hardware resources, such as GPIO and RTC. The platform driver framework is an important part of the OpenHarmony driver framework. Based on the HDF, OSAL, and driver configuration and management mechanism, the platform driver framework provides standard models for implementing a variety of platform device drivers. The platform driver framework provides standard platform device access APIs for peripherals regardless of difference in underlying hardware. It also provides unified adaptation APIs for platform device drivers, focusing only their own hardware control.
The platform driver framework provides the following features:
- Unified platform device access interface: encapsulates platform device operation APIs in a unified manner to shield hardware differences between SoC platforms and differences between OSs.
- Unified platform driver adaptation interface: provides unified adaptation APIs for platform device drivers. You only need to focus on the hardware control the driver, without caring about device management and common service processes.
- Common capabilities irrelevant to SoCs, such as device registration, management, and access control.
Currently, the platform driver framework supports devices, including the ADC, DAC, GPIO, HDMI, I2C, I3C, MIPI CSI, MIPI DSI, MMC, pin, PWM, regulator, RTC, SDIO, SPI, UART, and watchdog.
### Peripheral Drivers
Based on the HDF and platform driver framework, OpenHarmony provides common driver models for peripheral drivers. Standard peripheral device drivers help reduce repeated development. In addition, the unified abstraction of peripheral driver models shields the interaction between drivers and different system devices, making the drivers more general for use.
Currently, OpenHarmony supports peripherals covering audio, cameras, codecs, LCD, lights, motion, sensors, touchscreens, vibrators, USB, WLAN, face authentication, fingerprint authentication, PIN authentication, and user authentication.
### Driver Code Repositories
The table below describes the code repositories of the HDF.
**Table 1** HDF code repositories
| Repository| Description|
| -------- | -------- |
| drivers/hdf_core/framework | Provides platform-independent frameworks:<br>- **framework/core**:<br> - Provides capabilities of loading and starting drivers.<br> - Implements elastic deployment and expansion of the driver framework through the object manager.<br>- **framework/model**:<br> Provides driver models, such as the network device model.<br>- **framework/ability**<br> Provides basic driver ability models, such as the I/O communication model.<br>- **framework/tools**:<br> Provides tools for HDI API conversion, and driver configuration and compilation.<br>- **framework/support**<br> Provides platform driver APIs and system APIs with normalized abstraction capabilities.|
| drivers/hdf_core/adapter | Provides adaptation code and build scripts related to LiteOS-M and LiteOS-A kernels and user-mode interface libraries.|
| drivers/hdf_core//adapter/khdf/linux | Provides adaptation code and build scripts related to Linux.|
| drivers/peripheral | Provides the hardware abstraction layer for peripheral modules, such as the display, input, sensor, WLAN, audio, and camera.|
| drivers/interface | Defines the HDI APIs of peripheral modules, such as the display, input, sensor, WLAN, audio, and camera.|
### How to Use
- To adapt the OpenHarmony driver to a new platform device, use the standard models and APIs provided by the OpenHarmony platform driver framework. You only need to focus on hardware control, without caring about the device management and common service processes. For details, see **Platform Driver Development**.
- After the platform driver adaptation, you can use the APIs provided by the OpenHarmony platform driver framework for the system and peripheral drivers to further develop services and applications. For details, see **Platform Driver Usage**.
- The OpenHarmony HDF provides a variety of standard peripheral driver models. These models shield hardware differences and provide stable and standard APIs for upper-layer services. You can use these models to develop peripheral drivers. For details, see **Peripheral Driver Usage**.
...@@ -2,7 +2,9 @@ ...@@ -2,7 +2,9 @@
- Kernel - Kernel
- Mini-System Kernel - Mini-System Kernel
- [Kernel Overview](kernel-mini-overview.md) - [Kernel Overview](kernel-overview.md)
- Mini-System Kernel (LiteOS-M)
- [LiteOS-M Overview](kernel-mini-overview.md)
- Basic Kernel - Basic Kernel
- [Interrupt Management](kernel-mini-basic-interrupt.md) - [Interrupt Management](kernel-mini-basic-interrupt.md)
- [Task Management](kernel-mini-basic-task.md) - [Task Management](kernel-mini-basic-task.md)
...@@ -16,7 +18,7 @@ ...@@ -16,7 +18,7 @@
- [Software Timer](kernel-mini-basic-soft.md) - [Software Timer](kernel-mini-basic-soft.md)
- Extended Components - Extended Components
- [C++ Support](kernel-mini-extend-support.md) - [C++ Support](kernel-mini-extend-support.md)
- [PUP](kernel-mini-extend-cpup.md) - [CPUP](kernel-mini-extend-cpup.md)
- [Dynamic Loading](kernel-mini-extend-dynamic-loading.md) - [Dynamic Loading](kernel-mini-extend-dynamic-loading.md)
- [File System](kernel-mini-extend-file.md) - [File System](kernel-mini-extend-file.md)
- Kernel Debugging - Kernel Debugging
...@@ -28,7 +30,7 @@ ...@@ -28,7 +30,7 @@
- [Kernel Coding Specification](kernel-mini-appx-code.md) - [Kernel Coding Specification](kernel-mini-appx-code.md)
- [Doubly Linked List](kernel-mini-appx-data-list.md) - [Doubly Linked List](kernel-mini-appx-data-list.md)
- [Standard Libraries](kernel-mini-appx-lib.md) - [Standard Libraries](kernel-mini-appx-lib.md)
- Small-System Kernel - Small-System Kernel (LiteOS-A)
- [Kernel Overview](kernel-small-overview.md) - [Kernel Overview](kernel-small-overview.md)
- Kernel Startup - Kernel Startup
- [Startup in Kernel Space](kernel-small-start-kernel.md) - [Startup in Kernel Space](kernel-small-start-kernel.md)
...@@ -149,7 +151,8 @@ ...@@ -149,7 +151,8 @@
- [Doubly Linked List](kernel-small-apx-dll.md) - [Doubly Linked List](kernel-small-apx-dll.md)
- [Bitwise Operation](kernel-small-apx-bitwise.md) - [Bitwise Operation](kernel-small-apx-bitwise.md)
- [Standard Library](kernel-small-apx-library.md) - [Standard Library](kernel-small-apx-library.md)
- Standard-System Kernel - [Kernel Coding Specification](kernel-mini-appx-code.md)
- Standard-System Kernel (Linux)
- [Linux Kernel Overview](kernel-standard-overview.md) - [Linux Kernel Overview](kernel-standard-overview.md)
- [Applying Patches on Development Boards](kernel-standard-patch.md) - [Applying Patches on Development Boards](kernel-standard-patch.md)
- [Compiling and Building the Linux Kernel](kernel-standard-build.md) - [Compiling and Building the Linux Kernel](kernel-standard-build.md)
......
# Kernel Overview # LiteOS-M Overview
## Overview ## Overview
...@@ -9,7 +9,7 @@ The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and ...@@ -9,7 +9,7 @@ The OpenHarmony LiteOS-M kernel architecture consists of the hardware layer and
**Figure 1** Kernel architecture **Figure 1** Kernel architecture
![](figures/kernel-architecture.png "kernel-architecture") ![](figures/Liteos-m-architecture.png "kernel-architecture")
## CPU Architecture Support ## CPU Architecture Support
......
此差异已折叠。
# Kernel Overview # LiteOS-A Overview
## Overview ## Overview
...@@ -33,7 +31,7 @@ To keep pace with the rapid development of the IoT industry, the OpenHarmony lig ...@@ -33,7 +31,7 @@ To keep pace with the rapid development of the IoT industry, the OpenHarmony lig
The lightweight kernel consists of the basic kernel, extended components, HDF, and POSIX APIs. Different from the microkernel which is running in the user mode, the extended functions, such as the file system and network protocols, of the lightweight kernel are running in the kernel address space. The direct function calling between components is much faster than inter-process communication \(IPC\) or remote procedure calls \(RPCs\). The lightweight kernel consists of the basic kernel, extended components, HDF, and POSIX APIs. Different from the microkernel which is running in the user mode, the extended functions, such as the file system and network protocols, of the lightweight kernel are running in the kernel address space. The direct function calling between components is much faster than inter-process communication \(IPC\) or remote procedure calls \(RPCs\).
**Figure 1** Architecture of the OpenHarmony LiteOS-A kernel<a name="fig10235830103519"></a> **Figure 1** Architecture of the OpenHarmony LiteOS-A kernel<a name="fig10235830103519"></a>
![](figures/architecture-of-the-openharmony-liteos-a-kernel.png "architecture-of-the-openharmony-liteos-a-kernel") ![](figures/Liteos-a-architecture.png "architecture-of-the-openharmony-liteos-a-kernel")
- The basic kernel implements basic kernel mechanisms, such as scheduling, memory management, and interrupts. - The basic kernel implements basic kernel mechanisms, such as scheduling, memory management, and interrupts.
- Extended components include file systems, network protocols, permission management, and more. - Extended components include file systems, network protocols, permission management, and more.
......
# 设备使用信息统计 # 设备使用信息统计
- [设备使用信息统计概述](device-usage-statistics-overview.md) - [设备使用信息统计概述](device-usage-statistics-overview.md)
- [设备使用信息统计开发指导(API7)](device-usage-statistics-dev-guide.md) - [设备使用信息统计开发指导](device-usage-statistics-use-guide.md)
- [设备使用信息统计开发指导(API9)](device-usage-statistics-use-guide.md) \ No newline at end of file
\ No newline at end of file
# 设备使用信息统计(API7)
## 场景介绍
设备使用信息统计,包括app usage/notification usage/system usage等使用统计。例如应用使用信息统计,用于保存和查询应用使用详情(app usage)、事件日志数据(event log)、应用分组(bundle group)情况。
部件缓存的应用记录(使用历史统计和使用事件记录)会在事件上报后30分钟内刷新到数据库持久化保存。
根据设备的使用信息统计接口,开发者可以开发出健康管理类应用来实现个人设备健康使用功能,并向用户展示其个人设备的使用记录。
## 接口说明
注册相关接口包导入:
```js
import stats from '@ohos.bundleState';
```
**表1** 设备使用信息统计主要接口
| 接口名 | 描述 |
| -------- | -------- |
| function queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveState&gt;&gt;): void | 通过指定起始和结束时间查询所有应用的事件集合。 |
| function queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback&lt;BundleActiveInfoResponse&gt;): void | 通过指定起始和结束时间查询应用使用时长统计信息。 |
| function queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveState&gt;&gt;): void | 通过指定起始和结束时间查询当前应用的事件集合。 |
| function queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleStateInfo&gt;&gt;): void | 通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息。 |
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | 查询当前应用的使用优先级群组。callback形式。 |
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | 查询当前应用的使用优先级群组。promise形式。 |
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | 判断指定Bundle Name的应用当前是否是空闲状态。 |
## 开发步骤
1. 获取设备使用信息之前,需要检查是否已经配置请求相应的权限。
系统提供的设备使用信息统计的权限是ohos.permission.BUNDLE_ACTIVE_INFO
具体配置方式请参考[权限申请声明](../security/accesstoken-guidelines.md)
2. 通过指定起始和结束时间查询所有应用的事件集合,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```js
import stats from '@ohos.bundleState'
stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
});
```
3. 通过指定起始和结束时间查询应用使用时长统计信息,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```js
import stats from '@ohos.bundleState'
stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1;
for (let key in res){
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++;
}
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
});
```
4. 通过指定起始和结束时间查询当前应用的事件集合,不需要配置权限。
```js
import stats from '@ohos.bundleState'
stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
}
}).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
});
```
5. 通过指定时间段间隔(天、周、月、年)查询应用使用时长统计信息,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```js
import stats from '@ohos.bundleState'
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
}
}).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
});
```
6. 查询(无参)当前调用者应用的使用优先级群组,不需要配置权限。
```js
import stats from '@ohos.bundleState'
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
```
7. 判断指定Bundle Name的应用当前是否是空闲状态,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限,三方应用只能查询自身的空闲状态。
```js
import stats from '@ohos.bundleState'
stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
});
```
## 相关实例
针对设备使用信息统计,有以下相关实例可供参考:
- [`DeviceUsageStatistics`:设备使用信息统计(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics)
...@@ -95,7 +95,6 @@ ...@@ -95,7 +95,6 @@
- [@ohos.mediaquery (媒体查询)](js-apis-mediaquery.md) - [@ohos.mediaquery (媒体查询)](js-apis-mediaquery.md)
- [@ohos.promptAction (弹窗)](js-apis-promptAction.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)
- 图形图像 - 图形图像
- [@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)
......
...@@ -604,10 +604,10 @@ try { ...@@ -604,10 +604,10 @@ try {
| 名称 | 参数类型 | 必填 | 说明 | | 名称 | 参数类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderType | ReminderType | 是 | 指明提醒类型。 | | reminderType | [ReminderType](#remindertype) | 是 | 指明提醒类型。 |
| actionButton | [ActionButton?,&nbsp;ActionButton?] | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 | | actionButton | [ActionButton](#actionbutton) | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 |
| wantAgent | WantAgent | 否 | 点击通知后需要跳转的目标ability信息。 | | wantAgent | [WantAgent](#wantagent) | 否 | 点击通知后需要跳转的目标ability信息。 |
| maxScreenWantAgent | MaxScreenWantAgent | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 | | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 |
| ringDuration | number | 否 | 指明响铃时长。 | | ringDuration | number | 否 | 指明响铃时长。 |
| snoozeTimes | number | 否 | 指明延迟提醒次数。 | | snoozeTimes | number | 否 | 指明延迟提醒次数。 |
| timeInterval | number | 否 | 执行延迟提醒间隔。 | | timeInterval | number | 否 | 执行延迟提醒间隔。 |
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册