“20b320bc0f2eeed458b2e66d751e378c2ffa0dab”上不存在“...sun/nio/git@gitcode.net:openanolis/dragonwell8_jdk.git”
提交 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.
......
...@@ -10,6 +10,7 @@ System applications can call the APIs to do the following: ...@@ -10,6 +10,7 @@ System applications can call the APIs to do the following:
- Query the trusted device list. - Query the trusted device list.
- Query local device information, including the device name, type, and ID. - Query local device information, including the device name, type, and ID.
- Publish device information for discovery purposes. - Publish device information for discovery purposes.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -18,7 +19,7 @@ System applications can call the APIs to do the following: ...@@ -18,7 +19,7 @@ System applications can call the APIs to do the following:
## Modules to Import ## Modules to Import
``` ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
``` ```
...@@ -32,23 +33,37 @@ Creates a **DeviceManager** instance. ...@@ -32,23 +33,37 @@ Creates a **DeviceManager** instance.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ------------------------------------ | | Name | Type | Mandatory | Description |
| bundleName | string | Yes | Bundle name of an application. | | ---------- | ---------------------------------------- | ---- | ------------------------------------ |
| callback | AsyncCallback&lt;[DeviceManager](#devicemanager)&gt; | Yes | Callback used to return the **DeviceManager** instance created.| | bundleName | string | Yes | Bundle name of an application. |
| callback | AsyncCallback&lt;[DeviceManager](#devicemanager)&gt; | Yes | Callback used to return the **DeviceManager** instance created.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
| 11600102 | Failed to obtain the service. |
**Example** **Example**
``` ```js
deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { try {
if (err) { deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => {
console.info("createDeviceManager err:" + JSON.stringify(err)); if (err) {
console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
return; return;
} }
console.info("createDeviceManager success"); console.info("createDeviceManager success");
let dmInstance = data; let dmInstance = data;
}); });
``` } catch(err) {
console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
}
```
## DeviceInfo ## DeviceInfo
...@@ -191,7 +206,7 @@ Defines published device information. ...@@ -191,7 +206,7 @@ Defines published device information.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------- | --------------------------------- | ---- | ----------------- | | ------------- | --------------------------------- | ---- | ----------------- |
| publishId | number | Yes | ID used to identify a publication period.| | publishId | number | Yes | ID used to identify a publication period.|
| mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. | | mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. |
...@@ -202,7 +217,6 @@ Defines published device information. ...@@ -202,7 +217,6 @@ Defines published device information.
Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**.
### release ### release
release(): void release(): void
...@@ -211,12 +225,23 @@ Releases this **DeviceManager** instance when it is no longer used. ...@@ -211,12 +225,23 @@ Releases this **DeviceManager** instance when it is no longer used.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Example** **Error codes**
```js For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
dmInstance.release();
``` | ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example**
```js
try {
dmInstance.release();
} catch (err) {
console.error("release errCode:" + err.code + ",errMessage:" + err.message);
}
```
### getTrustedDeviceListSync ### getTrustedDeviceListSync
...@@ -228,16 +253,27 @@ Obtains all trusted devices synchronously. ...@@ -228,16 +253,27 @@ Obtains all trusted devices synchronously.
**Return value** **Return value**
| Name | Description | | Name | Description |
| -------------------------------------- | --------- | | -------------------------------------- | --------- |
| Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of trusted devices obtained.| | Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of trusted devices obtained.|
**Example** **Error codes**
```js For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
var deviceInfoList = dmInstance.getTrustedDeviceListSync();
```
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example**
```js
try {
var deviceInfoList = dmInstance.getTrustedDeviceListSync();
} catch (err) {
console.error("getTrustedDeviceListSync errCode:" + err.code + ",errMessage:" + err.message);
}
```
### getTrustedDeviceList<sup>8+</sup> ### getTrustedDeviceList<sup>8+</sup>
...@@ -248,17 +284,33 @@ Obtains all trusted devices. This API uses an asynchronous callback to return th ...@@ -248,17 +284,33 @@ Obtains all trusted devices. This API uses an asynchronous callback to return th
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------- | | Name | Type | Mandatory | Description |
| callback | AsyncCallback&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Yes | Callback used to return the list of trusted devices.| | -------- | ---------------------------------------- | ---- | --------------------- |
| callback | AsyncCallback&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Yes | Callback used to return the list of trusted devices.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
dmInstance.getTrustedDeviceList((err, data) => { try {
console.log("getTrustedDeviceList err: " + JSON.stringify(err)); dmInstance.getTrustedDeviceList((err, data) => {
if (err) {
console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
return;
}
console.log('get trusted device info: ' + JSON.stringify(data)); console.log('get trusted device info: ' + JSON.stringify(data));
} });
); } catch (err) {
console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### getTrustedDeviceList<sup>8+</sup> ### getTrustedDeviceList<sup>8+</sup>
...@@ -270,16 +322,26 @@ Obtains all trusted devices. This API uses a promise to return the result. ...@@ -270,16 +322,26 @@ Obtains all trusted devices. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Return value** **Return value**
| Type | Description |
| ---------------------------------------- | --------------------- | | Type | Description |
| Promise&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Promise used to return the list of trusted devices.| | ---------------------------------------- | --------------------- |
| Promise&lt;Array&lt;[DeviceInfo](#deviceinfo)&gt;&gt; | Promise used to return the list of trusted devices.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
dmInstance.getTrustedDeviceList().then((data) => { dmInstance.getTrustedDeviceList().then((data) => {
console.log('get trusted device info: ' + JSON.stringify(data)); console.log('get trusted device info: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log("getTrustedDeviceList err: " + JSON.stringify(err)); console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message);
}); });
``` ```
...@@ -292,16 +354,29 @@ Obtains local device information synchronously. ...@@ -292,16 +354,29 @@ Obtains local device information synchronously.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Return value** **Return value**
| Name | Description |
| -------------------------------------- | --------- | | Name | Description |
| Array&lt;[DeviceInfo](#deviceinfo)&gt; | List of local devices obtained.| | ------------------------- | ---------------- |
| [DeviceInfo](#deviceinfo) | List of local devices obtained.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
var deviceInfo = dmInstance.getLocalDeviceInfoSync(); try {
var deviceInfo = dmInstance.getLocalDeviceInfoSync();
} catch (err) {
console.error("getLocalDeviceInfoSync errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### getLocalDeviceInfo<sup>8+</sup> ### getLocalDeviceInfo<sup>8+</sup>
getLocalDeviceInfo(callback:AsyncCallback&lt;DeviceInfo&gt;): void getLocalDeviceInfo(callback:AsyncCallback&lt;DeviceInfo&gt;): void
...@@ -311,17 +386,33 @@ Obtains local device information. This API uses an asynchronous callback to retu ...@@ -311,17 +386,33 @@ Obtains local device information. This API uses an asynchronous callback to retu
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------- | | Name | Type | Mandatory | Description |
| callback | AsyncCallback&lt;[DeviceInfo](#deviceinfo)&gt; | Yes | Callback used to return the local device information.| | -------- | ---------------------------------------- | ---- | --------- |
| callback | AsyncCallback&lt;[DeviceInfo](#deviceinfo)&gt; | Yes | Callback used to return the local device information.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
dmInstance.getLocalDeviceInfo((err, data) => { try {
console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); dmInstance.getLocalDeviceInfo((err, data) => {
console.log('get local device info: ' + JSON.stringify(data)); if (err) {
console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
return;
} }
); console.log('get local device info: ' + JSON.stringify(data));
});
} catch (err) {
console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### getLocalDeviceInfo<sup>8+</sup> ### getLocalDeviceInfo<sup>8+</sup>
...@@ -333,16 +424,26 @@ Obtains local device information. This API uses a promise to return the result. ...@@ -333,16 +424,26 @@ Obtains local device information. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Return value** **Return value**
| Type | Description |
| ---------------------------------------- | --------------------- | | Type | Description |
| Promise&lt;[DeviceInfo](#deviceinfo)&gt; | Promise used to return the local device information.| | ---------------------------------------- | --------------------- |
| Promise&lt;[DeviceInfo](#deviceinfo)&gt; | Promise used to return the local device information.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| ------- | --------------------------------------------------------------- |
| 11600101| Failed to execute the function. |
**Example** **Example**
```js ```js
dmInstance.getLocalDeviceInfo().then((data) => { dmInstance.getLocalDeviceInfo().then((data) => {
console.log('get local device info: ' + JSON.stringify(data)); console.log('get local device info: ' + JSON.stringify(data));
}).catch((err) => { }).catch((err) => {
console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message);
}); });
``` ```
...@@ -355,11 +456,22 @@ Starts to discover peripheral devices. ...@@ -355,11 +456,22 @@ Starts to discover peripheral devices.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ------------- | ------------------------------- | ---- | ----- | | Name | Type | Mandatory| Description |
| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| | ------------- | ------------------------------- | ---- | ----- |
| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
| 11600104 | Discovery invalid. |
**Example** **Example**
```js ```js
// Automatically generate a unique subscription ID. // Automatically generate a unique subscription ID.
var subscribeId = Math.floor(Math.random() * 10000 + 1000); var subscribeId = Math.floor(Math.random() * 10000 + 1000);
...@@ -372,7 +484,11 @@ Starts to discover peripheral devices. ...@@ -372,7 +484,11 @@ Starts to discover peripheral devices.
"isWakeRemote": false, "isWakeRemote": false,
"capability": 1 "capability": 1
}; };
dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. try {
dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered.
} catch (err) {
console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### startDeviceDiscovery9+</sup> ### startDeviceDiscovery9+</sup>
...@@ -384,10 +500,20 @@ Starts to discover peripheral devices and filters discovered devices. ...@@ -384,10 +500,20 @@ Starts to discover peripheral devices and filters discovered devices.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ------------- | ------------------------------- | ---- | ----- | | Name | Type | Mandatory | Description |
| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| | ------------- | ------------------------------- | ---- | ----- |
| filterOptions | string | No | Options for filtering discovered devices.| | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.|
| filterOptions | string | No | Options for filtering discovered devices.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
| 11600104 | Discovery invalid. |
**Example** **Example**
...@@ -412,7 +538,11 @@ Starts to discover peripheral devices and filters discovered devices. ...@@ -412,7 +538,11 @@ Starts to discover peripheral devices and filters discovered devices.
} }
] ]
}; };
dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered. try {
dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered.
} catch (err) {
console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### stopDeviceDiscovery ### stopDeviceDiscovery
...@@ -424,14 +554,28 @@ Stops device discovery. ...@@ -424,14 +554,28 @@ Stops device discovery.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | ----- | | Name | Type | Mandatory | Description |
| subscribeId | number | Yes | Subscription ID.| | ----------- | ------ | ---- | ----- |
| subscribeId | number | Yes | Subscription ID.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
// The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery.
dmInstance.stopDeviceDiscovery(subscribeId); try {
dmInstance.stopDeviceDiscovery(subscribeId);
} catch (err) {
console.error("stopDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### publishDeviceDiscovery9+</sup> ### publishDeviceDiscovery9+</sup>
...@@ -443,11 +587,22 @@ Publishes device information for discovery purposes. ...@@ -443,11 +587,22 @@ Publishes device information for discovery purposes.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------- | ---- | ----- | | Name | Type | Mandatory| Description |
| publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.| | ------------- | ------------------------------- | ---- | ----- |
| publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
| 11600105 | Publish invalid. |
**Example** **Example**
```js ```js
// Automatically generate a unique subscription ID. // Automatically generate a unique subscription ID.
var publishId = Math.floor(Math.random() * 10000 + 1000); var publishId = Math.floor(Math.random() * 10000 + 1000);
...@@ -457,9 +612,13 @@ Publishes device information for discovery purposes. ...@@ -457,9 +612,13 @@ Publishes device information for discovery purposes.
"freq": 2, // High frequency "freq": 2, // High frequency
"ranging": 1 // The device supports reporting the distance to the discovery initiator. "ranging": 1 // The device supports reporting the distance to the discovery initiator.
}; };
dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. try {
dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published.
} catch (err) {
console.error("publishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### unPublishDeviceDiscovery9+</sup> ### unPublishDeviceDiscovery9+</sup>
unPublishDeviceDiscovery(publishId: number): void unPublishDeviceDiscovery(publishId: number): void
...@@ -470,14 +629,27 @@ Stops publishing device information. ...@@ -470,14 +629,27 @@ Stops publishing device information.
**Parameters** **Parameters**
| Name | Type| Mandatory| Description | | Name | Type| Mandatory| Description |
| ----------- | -------- | ---- | ----- | | ----------- | -------- | ---- | ----- |
| publishId | number | Yes | Publish ID.| | publishId | number | Yes | Publish ID.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
// The publishId input must be the same as that automatically generated in publishDeviceDiscovery. // The publishId input must be the same as that automatically generated in publishDeviceDiscovery.
dmInstance.unPublishDeviceDiscovery(publishId); try {
dmInstance.unPublishDeviceDiscovery(publishId);
} catch (err) {
console.error("unPublishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### authenticateDevice ### authenticateDevice
...@@ -489,13 +661,24 @@ Authenticates a device. ...@@ -489,13 +661,24 @@ Authenticates a device.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ------- | | Name | Type | Mandatory | Description |
| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | | ---------- | ---------------------------------------- | ---- | ------- |
| authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. |
| callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. |
| callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
| 11600103 | Authentication invalid. |
**Example** **Example**
```js ```js
// Information about the device to authenticate. The information can be obtained from the device discovery result. // Information about the device to authenticate. The information can be obtained from the device discovery result.
var deviceInfo ={ var deviceInfo ={
...@@ -507,14 +690,18 @@ Authenticates a device. ...@@ -507,14 +690,18 @@ Authenticates a device.
"authType": 1, // Authentication type. The value 1 means no account PIN authentication. "authType": 1, // Authentication type. The value 1 means no account PIN authentication.
"extraInfo": {} "extraInfo": {}
} }
dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { try {
dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => {
if (err) { if (err) {
console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message);
return; return;
} }
console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); console.info("authenticateDevice result:" + JSON.stringify(data));
token = data.pinToken; let token = data.pinToken;
}); });
} catch (err) {
console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### unAuthenticateDevice<sup>8+</sup> ### unAuthenticateDevice<sup>8+</sup>
...@@ -527,16 +714,28 @@ Deauthenticates a device. ...@@ -527,16 +714,28 @@ Deauthenticates a device.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------- | ---- | ----- | | ---------- | ------------------------- | ---- | ----- |
| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
dmInstance.unAuthenticateDevice(deviceInfo); try {
dmInstance.unAuthenticateDevice(deviceInfo);
} catch (err) {
console.error("unAuthenticateDevice errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### verifyAuthInfo ### verifyAuthInfo
verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void
...@@ -546,27 +745,132 @@ Verifies authentication information. ...@@ -546,27 +745,132 @@ Verifies authentication information.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------- | | Name | Type | Mandatory | Description |
| authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | | -------- | ---------------------------------------- | ---- | ------- |
| authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. |
| callback | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.|
**Error codes**
For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md).
| ID| Error Message |
| -------- | --------------------------------------------------------------- |
| 11600101 | Failed to execute the function. |
**Example** **Example**
```js ```js
let authInfo = { let authInfo = {
"authType": 1, "authType": 1,
"token": xxxxxx, "token": xxxxxx,
"extraInfo": {} "extraInfo": {}
} }
dmInstance.verifyAuthInfo(authInfo, (err, data) => { try {
dmInstance.verifyAuthInfo(authInfo, (err, data) => {
if (err) { if (err) {
console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message);
return; return;
} }
console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); console.info("verifyAuthInfo result:" + JSON.stringify(data));
});
} catch (err) {
console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message);
}
```
### setUserOperation9+</sup>
setUserOperation(operateAction: number, params: string): void;
Sets a user operation action.
**System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------------- | --------------- | ---- | ------------------- |
| operateAction | number | Yes | User operation action. |
| params | string | Yes | Input parameters of the user.|
**Example**
```js
try {
/*
operateAction = 0 - Grant the permission.
operateAction = 1 - Revoke the permission.
operateAction = 2 - The user operation in the permission request dialog box times out.
operateAction = 3 - Cancel the display of the PIN box.
operateAction = 4 - Cancel the display of the PIN text box.
operateAction = 5 - Confirm in the pin text box.
*/
let operation = 0;
this.dmInstance.setUserOperation(operation, "extra")
} catch (err) {
console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message);
}
```
### on('uiStateChange')9+</sup>
on(type: 'uiStateChange', callback: Callback<{ param: string}>): void;
Subscribes to UI status changes.
**System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------ |
| type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.|
| callback | Callback&lt;{&nbsp;param: string}&gt; | Yes | Callback used to return the UI status. |
**Example**
```js
try {
dmInstance.on('uiStateChange', (data) => {
console.log("uiStateChange executed, dialog closed" + JSON.stringify(data))
var tmpStr = JSON.parse(data.param)
this.isShow = tmpStr.verifyFailed
console.log("uiStateChange executed, dialog closed" + this.isShow)
if (!this.isShow) {
this.destruction()
}
}); });
} catch (err) {
console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('uiStateChange')9+</sup>
off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void;
Unsubscribes from UI status changes.
**System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.|
| callback | Callback&lt;{&nbsp;param: string}&gt; | Yes | Callback used to return the UI status.|
**Example**
```js
try {
dmInstance.off('uiStateChange');
} catch (err) {
console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
```
### on('deviceStateChange') ### on('deviceStateChange')
...@@ -577,20 +881,24 @@ Subscribes to changes in the device state. ...@@ -577,20 +881,24 @@ Subscribes to changes in the device state.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------ | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| | -------- | ---------------------------------------- | ---- | ------------------------------ |
| callback | Callback&lt;{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }&gt; | Yes | Callback invoked to return the device information and state. | | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.|
| callback | Callback&lt;{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }&gt; | Yes | Callback used to return the device information and state. |
**Example** **Example**
```js ```js
dmInstance.on('deviceStateChange', (data) => { try {
console.info("deviceStateChange on:" + JSON.stringify(data)); dmInstance.on('deviceStateChange', (data) => {
} console.info("deviceStateChange on:" + JSON.stringify(data));
); });
} catch (err) {
console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('deviceStateChange') ### off('deviceStateChange')
off(type: 'deviceStateChange', callback?: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void off(type: 'deviceStateChange', callback?: Callback&lt;{ action: DeviceStateChangeAction, device: DeviceInfo }&gt;): void
...@@ -600,20 +908,23 @@ Unsubscribes from changes in the device state. ...@@ -600,20 +908,23 @@ Unsubscribes from changes in the device state.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | | -------- | ---------------------------------------- | ---- | --------------------------- |
| callback | Callback&lt;{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }&gt; | Yes | Callback invoked to return the device information and state.| | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. |
| callback | Callback&lt;{&nbsp;action:&nbsp;[DeviceStateChangeAction](#devicestatechangeaction),&nbsp;device:&nbsp;[DeviceInfo](#deviceinfo)&nbsp;&nbsp;}&gt; | Yes | Callback used to return the device information and state.|
**Example** **Example**
```js ```js
dmInstance.off('deviceStateChange', (data) => { try {
dmInstance.off('deviceStateChange', (data) => {
console.info('deviceStateChange' + JSON.stringify(data)); console.info('deviceStateChange' + JSON.stringify(data));
} });
); } catch (err) {
``` console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message);
}
```
### on('deviceFound') ### on('deviceFound')
...@@ -624,17 +935,22 @@ Subscribes to device discovery events. ...@@ -624,17 +935,22 @@ Subscribes to device discovery events.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | -------------------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| | -------- | ---------------------------------------- | ---- | -------------------------- |
| callback | Callback&lt;{ subscribeId: number, device: DeviceInfo }&gt; | Yes | Callback used for device discovery. | | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.|
| callback | Callback&lt;{&nbsp;subscribeId: number, device: DeviceInfo&nbsp;}&gt; | Yes | Callback used for device discovery. |
**Example** **Example**
```js ```js
dmInstance.on('deviceFound', (data) => { try {
console.info("deviceFound:" + JSON.stringify(data)); dmInstance.on('deviceFound', (data) => {
} console.info("deviceFound:" + JSON.stringify(data));
); });
} catch (err) {
console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('deviceFound') ### off('deviceFound')
...@@ -646,17 +962,22 @@ Unsubscribes from device discovery events. ...@@ -646,17 +962,22 @@ Unsubscribes from device discovery events.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | | -------- | ---------------------------------------- | ---- | --------------------------- |
| callback | Callback&lt;{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }&gt; | Yes | Callback invoked to return the device information and state.| | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. |
| callback | Callback&lt;{&nbsp;subscribeId: number, device: [DeviceInfo](#deviceinfo)&nbsp;}&gt; | Yes | Callback used to return the device information and state.|
**Example** **Example**
```js ```js
dmInstance.off('deviceFound', (data) => { try {
console.info('deviceFound' + JSON.stringify(data)); dmInstance.off('deviceFound', (data) => {
} console.info('deviceFound' + JSON.stringify(data));
); });
} catch (err) {
console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### on('discoverFail') ### on('discoverFail')
...@@ -668,17 +989,22 @@ Subscribes to device discovery failures. ...@@ -668,17 +989,22 @@ Subscribes to device discovery failures.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------------------------ | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| | -------- | ---------------------------------------- | ---- | ------------------------------ |
| callback | Callback&lt;{ subscribeId: number, reason: number }&gt; | Yes | Callback used for the device discovery failure. | | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.|
| callback | Callback&lt;{&nbsp;subscribeId: number, reason: number&nbsp;}&gt; | Yes | Callback used for the device discovery failure. |
**Example** **Example**
```js ```js
dmInstance.on('discoverFail', (data) => { try {
this.log("discoverFail on:" + JSON.stringify(data)); dmInstance.on('discoverFail', (data) => {
} console.info("discoverFail on:" + JSON.stringify(data));
); });
} catch (err) {
console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('discoverFail') ### off('discoverFail')
...@@ -690,17 +1016,22 @@ Unsubscribes from device discovery failures. ...@@ -690,17 +1016,22 @@ Unsubscribes from device discovery failures.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | | -------- | ---------------------------------------- | ---- | ----------------- |
| callback | Callback&lt;{ subscribeId: number, reason: number }&gt; | Yes | Callback used for the device discovery failure.| | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. |
| callback | Callback&lt;{&nbsp;subscribeId: number, reason: number&nbsp;}&gt; | Yes | Callback used for the device discovery failure.|
**Example** **Example**
```js ```js
dmInstance.off('deviceFound', (data) => { try {
console.info('deviceFound' + JSON.stringify(data)); dmInstance.off('discoverFail', (data) => {
} console.info('discoverFail' + JSON.stringify(data));
); });
} catch (err) {
console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### on('publishSuccess')9+</sup> ### on('publishSuccess')9+</sup>
...@@ -712,18 +1043,24 @@ Subscribes to device information publication success events. ...@@ -712,18 +1043,24 @@ Subscribes to device information publication success events.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | -------------------------- | | Name | Type | Mandatory| Description |
| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.| | -------- | ---------------------------------------- | ---- | -------------------------- |
| callback | Callback&lt;{ publishId: number }&gt; | Yes | Callback invoked to return the publish ID. | | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.|
| callback | Callback&lt;{ publishId: number }&gt; | Yes | Callback used to return the publish ID. |
**Example** **Example**
```js
dmInstance.on('publishSuccess', (data) => { ```js
try {
dmInstance.on('publishSuccess', (data) => {
console.info("publishSuccess:" + JSON.stringify(data)); console.info("publishSuccess:" + JSON.stringify(data));
} });
); } catch (err) {
``` console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message);
}
```
### off('publishSuccess')9+</sup> ### off('publishSuccess')9+</sup>
...@@ -734,17 +1071,22 @@ Unsubscribes from device information publication success events. ...@@ -734,17 +1071,22 @@ Unsubscribes from device information publication success events.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------- | ---- | --------------------------- | | Name | Type | Mandatory| Description |
| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. | | -------- | ---------------------------------------- | ---- | --------------------------- |
| callback | Callback&lt;{ publishId: number }&gt; | Yes | Callback used to return the publish ID.| | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. |
| callback | Callback&lt;{ publishId: number }&gt; | Yes | Callback used to return the publish ID.|
**Example** **Example**
```js ```js
dmInstance.off('publishSuccess', (data) => { try {
console.info('publishSuccess' + JSON.stringify(data)); dmInstance.off('publishSuccess', (data) => {
} console.info('publishSuccess' + JSON.stringify(data));
); });
} catch (err) {
console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### on('publishFail')9+</sup> ### on('publishFail')9+</sup>
...@@ -756,17 +1098,22 @@ Subscribes to device information publication failures. ...@@ -756,17 +1098,22 @@ Subscribes to device information publication failures.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | ------------------------------ | | Name | Type | Mandatory| Description |
| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.| | -------- | ----------------------------------------------------- | ---- | ------------------------------ |
| callback | Callback&lt;{ publishId: number, reason: number }&gt; | Yes | Callback used for the publication failure. | | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.|
| callback | Callback&lt;{ publishId: number, reason: number }&gt; | Yes | Callback used for the publication failure. |
**Example** **Example**
```js ```js
dmInstance.on('publishFail', (data) => { try {
this.log("publishFail on:" + JSON.stringify(data)); dmInstance.on('publishFail', (data) => {
} console.info("publishFail on:" + JSON.stringify(data));
); });
} catch (err) {
console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('publishFail')9+</sup> ### off('publishFail')9+</sup>
...@@ -778,17 +1125,22 @@ Unsubscribes from device information publication failures. ...@@ -778,17 +1125,22 @@ Unsubscribes from device information publication failures.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | ----------------- | | Name | Type | Mandatory| Description |
| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. | | -------- | ----------------------------------------------------- | ---- | ----------------- |
| callback | Callback&lt;{ publishId: number, reason: number }&gt; | Yes | Callback used for the device discovery failure.| | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. |
| callback | Callback&lt;{ publishId: number, reason: number }&gt; | Yes | Callback used for the device discovery failure.|
**Example** **Example**
```js ```js
dmInstance.off('publishFail', (data) => { try {
console.info('publishFail' + JSON.stringify(data)); dmInstance.off('publishFail', (data) => {
} console.info('publishFail' + JSON.stringify(data));
); });
} catch (err) {
console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### on('serviceDie') ### on('serviceDie')
...@@ -800,20 +1152,24 @@ Subscribes to dead events of the **DeviceManager** service. ...@@ -800,20 +1152,24 @@ Subscribes to dead events of the **DeviceManager** service.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | ---- | ---------------------------------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| | -------- | ----------------------- | ---- | ---------------------------------------- |
| callback | () =&gt; void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. | | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
| callback | ()&nbsp;=&gt;&nbsp;void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. |
**Example** **Example**
```js ```js
dmInstance.on("serviceDie", () => { try {
console.info("serviceDie on"); dmInstance.on("serviceDie", () => {
} console.info("serviceDie on");
); });
} catch (err) {
console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
### off('serviceDie') ### off('serviceDie')
off(type: 'serviceDie', callback?: () =&gt; void): void off(type: 'serviceDie', callback?: () =&gt; void): void
...@@ -823,15 +1179,20 @@ Unsubscribes from dead events of the **DeviceManager** service. ...@@ -823,15 +1179,20 @@ Unsubscribes from dead events of the **DeviceManager** service.
**System capability**: SystemCapability.DistributedHardware.DeviceManager **System capability**: SystemCapability.DistributedHardware.DeviceManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| -------- | ----------------------- | ---- | ---------------------------------------- | | Name | Type | Mandatory | Description |
| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| | -------- | ----------------------- | ---- | ---------------------------------------- |
| callback | () =&gt; void | No | Callback used to return the dead event of the **DeviceManager** service. | | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.|
| callback | ()&nbsp;=&gt;&nbsp;void | No | Callback used to return the dead event of the **DeviceManager** service. |
**Example** **Example**
```js ```js
dmInstance.off("serviceDie", () => { try {
console.info("serviceDie off"); dmInstance.off("serviceDie", () => {
} console.info("serviceDie off");
); });
} catch (err) {
console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message);
}
``` ```
...@@ -44,7 +44,7 @@ Subscribes to data of the acceleration sensor. ...@@ -44,7 +44,7 @@ Subscribes to data of the acceleration sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -84,7 +84,7 @@ Subscribes to data of the uncalibrated acceleration sensor. ...@@ -84,7 +84,7 @@ Subscribes to data of the uncalibrated acceleration sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -125,7 +125,7 @@ Subscribes to data of the ambient light sensor. ...@@ -125,7 +125,7 @@ Subscribes to data of the ambient light sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -161,7 +161,7 @@ Subscribes to data of the ambient temperature sensor. ...@@ -161,7 +161,7 @@ Subscribes to data of the ambient temperature sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -197,7 +197,7 @@ Subscribes to data of the barometer sensor. ...@@ -197,7 +197,7 @@ Subscribes to data of the barometer sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -233,7 +233,7 @@ Subscribes to data of the gravity sensor. ...@@ -233,7 +233,7 @@ Subscribes to data of the gravity sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -273,7 +273,7 @@ Subscribes to data of the gyroscope sensor. ...@@ -273,7 +273,7 @@ Subscribes to data of the gyroscope sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -314,7 +314,7 @@ Subscribes to data of the uncalibrated gyroscope sensor. ...@@ -314,7 +314,7 @@ Subscribes to data of the uncalibrated gyroscope sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -355,7 +355,7 @@ Subscribes to data of the Hall effect sensor. ...@@ -355,7 +355,7 @@ Subscribes to data of the Hall effect sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -393,7 +393,7 @@ Subscribes to data of the heart rate sensor. ...@@ -393,7 +393,7 @@ Subscribes to data of the heart rate sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -429,7 +429,7 @@ Subscribes to data of the humidity sensor. ...@@ -429,7 +429,7 @@ Subscribes to data of the humidity sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -447,7 +447,7 @@ try { ...@@ -447,7 +447,7 @@ try {
} }
``` ```
### LINEAR_ACCELERATION<sup>9+</sup> ### LINEAR_ACCELEROMETER<sup>9+</sup>
on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback&lt;LinearAccelerometerResponse&gt;, on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback&lt;LinearAccelerometerResponse&gt;,
options?: Options): void options?: Options): void
...@@ -468,7 +468,7 @@ Subscribes to data of the linear acceleration sensor. ...@@ -468,7 +468,7 @@ Subscribes to data of the linear acceleration sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -506,7 +506,7 @@ Subscribes to data of the magnetic field sensor. ...@@ -506,7 +506,7 @@ Subscribes to data of the magnetic field sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -544,7 +544,7 @@ Subscribes to data of the uncalibrated magnetic field sensor. ...@@ -544,7 +544,7 @@ Subscribes to data of the uncalibrated magnetic field sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -577,7 +577,7 @@ Subscribes to data of the orientation sensor. ...@@ -577,7 +577,7 @@ Subscribes to data of the orientation sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -617,7 +617,7 @@ Subscribes to data of the pedometer sensor. ...@@ -617,7 +617,7 @@ Subscribes to data of the pedometer sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -664,7 +664,7 @@ Subscribe to data of the pedometer detection sensor. ...@@ -664,7 +664,7 @@ Subscribe to data of the pedometer detection sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -700,7 +700,7 @@ Subscribes to data of the proximity sensor. ...@@ -700,7 +700,7 @@ Subscribes to data of the proximity sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -737,7 +737,7 @@ Subscribes to data of the rotation vector sensor. ...@@ -737,7 +737,7 @@ Subscribes to data of the rotation vector sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -777,7 +777,7 @@ Subscribes to data of the significant motion sensor. ...@@ -777,7 +777,7 @@ Subscribes to data of the significant motion sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -814,7 +814,7 @@ Subscribes to data of the wear detection sensor. ...@@ -814,7 +814,7 @@ Subscribes to data of the wear detection sensor.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -853,7 +853,7 @@ Subscribes to data of the acceleration sensor once. ...@@ -853,7 +853,7 @@ Subscribes to data of the acceleration sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -893,7 +893,7 @@ Subscribes to data of the uncalibrated acceleration sensor once. ...@@ -893,7 +893,7 @@ Subscribes to data of the uncalibrated acceleration sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -934,7 +934,7 @@ Subscribes to data of the ambient light sensor once. ...@@ -934,7 +934,7 @@ Subscribes to data of the ambient light sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -970,7 +970,7 @@ Subscribes to data of the ambient temperature sensor once. ...@@ -970,7 +970,7 @@ Subscribes to data of the ambient temperature sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1006,7 +1006,7 @@ Subscribes to data of the barometer sensor once. ...@@ -1006,7 +1006,7 @@ Subscribes to data of the barometer sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1042,7 +1042,7 @@ Subscribes to data of the gravity sensor once. ...@@ -1042,7 +1042,7 @@ Subscribes to data of the gravity sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1082,7 +1082,7 @@ Subscribes to data of the gyroscope sensor once. ...@@ -1082,7 +1082,7 @@ Subscribes to data of the gyroscope sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1122,7 +1122,7 @@ Subscribes to data of the uncalibrated gyroscope sensor once. ...@@ -1122,7 +1122,7 @@ Subscribes to data of the uncalibrated gyroscope sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1163,7 +1163,7 @@ Subscribes to data of the Hall effect sensor once. ...@@ -1163,7 +1163,7 @@ Subscribes to data of the Hall effect sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1201,7 +1201,7 @@ Subscribes to data of the heart rate sensor once. ...@@ -1201,7 +1201,7 @@ Subscribes to data of the heart rate sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1237,7 +1237,7 @@ Subscribes to data of the humidity sensor once. ...@@ -1237,7 +1237,7 @@ Subscribes to data of the humidity sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1256,7 +1256,7 @@ try { ...@@ -1256,7 +1256,7 @@ try {
} }
``` ```
### LINEAR_ACCELERATION<sup>9+</sup> ### LINEAR_ACCELEROMETER<sup>9+</sup>
once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback&lt;LinearAccelerometerResponse&gt;): void once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback&lt;LinearAccelerometerResponse&gt;): void
...@@ -1275,7 +1275,7 @@ Subscribes to data of the linear acceleration sensor once. ...@@ -1275,7 +1275,7 @@ Subscribes to data of the linear acceleration sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1313,7 +1313,7 @@ Subscribes to data of the magnetic field sensor once. ...@@ -1313,7 +1313,7 @@ Subscribes to data of the magnetic field sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1351,7 +1351,7 @@ Subscribes to data of the uncalibrated magnetic field sensor once. ...@@ -1351,7 +1351,7 @@ Subscribes to data of the uncalibrated magnetic field sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1392,7 +1392,7 @@ Subscribes to data of the orientation sensor once. ...@@ -1392,7 +1392,7 @@ Subscribes to data of the orientation sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1432,7 +1432,7 @@ Subscribes to data of the pedometer sensor once. ...@@ -1432,7 +1432,7 @@ Subscribes to data of the pedometer sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1470,7 +1470,7 @@ Subscribe to data of the pedometer detection sensor once. ...@@ -1470,7 +1470,7 @@ Subscribe to data of the pedometer detection sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1506,7 +1506,7 @@ Subscribes to data of the proximity sensor once. ...@@ -1506,7 +1506,7 @@ Subscribes to data of the proximity sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1542,7 +1542,7 @@ Subscribes to data of the rotation vector sensor once. ...@@ -1542,7 +1542,7 @@ Subscribes to data of the rotation vector sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1581,7 +1581,7 @@ Subscribes to data of the significant motion sensor once. ...@@ -1581,7 +1581,7 @@ Subscribes to data of the significant motion sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -1617,7 +1617,7 @@ Subscribes to data of the wear detection sensor once. ...@@ -1617,7 +1617,7 @@ Subscribes to data of the wear detection sensor once.
**Error code** **Error code**
For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md).
| Error Code ID| Error Message | | Error Code ID| Error Message |
| -------- | ------------------ | | -------- | ------------------ |
...@@ -3652,37 +3652,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.LI ...@@ -3652,37 +3652,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.LI
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | | callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
### LINEAR_ACCELEROMETER<sup>9+</sup>
on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback&lt;LinearAccelerometerResponse&gt;,
options?: Options): void
Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect.
**Required permissions**: ohos.permission.ACCELEROMETER
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. |
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example**
```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){
console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z);
},
{interval: 10000000}
);
```
### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup> ### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup>
on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback&lt;AccelerometerUncalibratedResponse&gt;, options?: Options): void on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback&lt;AccelerometerUncalibratedResponse&gt;, options?: Options): void
...@@ -3704,7 +3673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AC ...@@ -3704,7 +3673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AC
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -3737,7 +3705,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GR ...@@ -3737,7 +3705,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GR
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -3769,7 +3736,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY ...@@ -3769,7 +3736,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -3801,7 +3767,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY ...@@ -3801,7 +3767,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -3834,7 +3799,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.SI ...@@ -3834,7 +3799,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.SI
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(data){
console.info('Scalar data: ' + data.scalar); console.info('Scalar data: ' + data.scalar);
...@@ -3864,7 +3828,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE ...@@ -3864,7 +3828,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(data){
console.info('Scalar data: ' + data.scalar); console.info('Scalar data: ' + data.scalar);
...@@ -3894,7 +3857,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE ...@@ -3894,7 +3857,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(data){
console.info('Steps: ' + data.steps); console.info('Steps: ' + data.steps);
...@@ -3929,7 +3891,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AM ...@@ -3929,7 +3891,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AM
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### MAGNETIC_FIELD<sup>(deprecated)</sup> ### MAGNETIC_FIELD<sup>(deprecated)</sup>
...@@ -3960,7 +3921,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA ...@@ -3960,7 +3921,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup> ### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -3982,7 +3942,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA ...@@ -3982,7 +3942,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -3994,7 +3953,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA ...@@ -3994,7 +3953,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### PROXIMITY<sup>(deprecated)</sup> ### PROXIMITY<sup>(deprecated)</sup>
...@@ -4016,14 +3974,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PR ...@@ -4016,14 +3974,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PR
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(data){
console.info('Distance: ' + data.distance); console.info('Distance: ' + data.distance);
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### HUMIDITY<sup>(deprecated)</sup> ### HUMIDITY<sup>(deprecated)</sup>
...@@ -4052,7 +4008,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HU ...@@ -4052,7 +4008,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HU
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### BAROMETER<sup>(deprecated)</sup> ### BAROMETER<sup>(deprecated)</sup>
...@@ -4081,7 +4036,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.BA ...@@ -4081,7 +4036,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.BA
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### HALL<sup>(deprecated)</sup> ### HALL<sup>(deprecated)</sup>
...@@ -4103,14 +4057,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HA ...@@ -4103,14 +4057,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HA
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(data){
console.info('Status: ' + data.status); console.info('Status: ' + data.status);
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### AMBIENT_LIGHT<sup>(deprecated)</sup> ### AMBIENT_LIGHT<sup>(deprecated)</sup>
...@@ -4160,7 +4112,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR ...@@ -4160,7 +4112,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(data){
console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the X axis: ' + data.beta);
...@@ -4169,7 +4120,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR ...@@ -4169,7 +4120,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
### HEART_RATE<sup>(deprecated)</sup> ### HEART_RATE<sup>(deprecated)</sup>
...@@ -4178,7 +4128,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRateRe ...@@ -4178,7 +4128,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRateRe
Subscribes to only one data change of the heart rate sensor. Subscribes to only one data change of the heart rate sensor.
This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_BEAT_RATE](#heart_beat_rate9) instead. This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_RATE](#heart_rate9) instead.
**Required permissions**: ohos.permission.HEALTH_DATA **Required permissions**: ohos.permission.HEALTH_DATA
...@@ -4191,35 +4141,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HE ...@@ -4191,35 +4141,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HE
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | | type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | | callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
### HEART_BEAT_RATE<sup>9+</sup>
on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRateResponse&gt;,
options?: Options): void
Subscribes to only one data change of the heart rate sensor.
**Required permissions**: ohos.permission.HEALTH_DATA
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
**Example**
```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){
console.info("Heart rate: " + data.heartRate);
},
{interval: 10000000}
);
```
### ROTATION_VECTOR<sup>(deprecated)</sup> ### ROTATION_VECTOR<sup>(deprecated)</sup>
on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback&lt;RotationVectorResponse&gt;,options?: Options): void on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback&lt;RotationVectorResponse&gt;,options?: Options): void
...@@ -4239,7 +4160,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.RO ...@@ -4239,7 +4160,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.RO
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4270,14 +4190,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.WE ...@@ -4270,14 +4190,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.WE
| options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. | | options | [Options](#options) | No | Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns. |
**Example** **Example**
```js ```js
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(data){
console.info('Wear status: ' + data.value); console.info('Wear status: ' + data.value);
}, },
{interval: 10000000} {interval: 10000000}
); );
``` ```
## sensor.once<sup>(deprecated)</sup> ## sensor.once<sup>(deprecated)</sup>
...@@ -4302,7 +4220,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4302,7 +4220,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[AccelerometerResponse](#accelerometerresponse)&gt; | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. | | callback | Callback&lt;[AccelerometerResponse](#accelerometerresponse)&gt; | Yes | One-shot callback used to return the acceleration sensor data. The reported data type in the callback is **AccelerometerResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){ sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(data){
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4310,7 +4227,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4310,7 +4227,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
); );
``` ```
### LINEAR_ACCELERATION<sup>(deprecated)</sup> ### LINEAR_ACCELERATION<sup>(deprecated)</sup>
...@@ -4319,7 +4235,7 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback&lt;Li ...@@ -4319,7 +4235,7 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback&lt;Li
Subscribes to only one data change of the linear acceleration sensor. Subscribes to only one data change of the linear acceleration sensor.
This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9-1) instead.
**Required permissions**: ohos.permission.ACCELERATION **Required permissions**: ohos.permission.ACCELERATION
...@@ -4332,35 +4248,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4332,35 +4248,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | | type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. |
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | | callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
### LINEAR_ACCELEROMETER<sup>9+</sup>
once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback&lt;LinearAccelerometerResponse&gt;): void
Subscribes to only one data change of the linear acceleration sensor.
**Required permissions**: ohos.permission.ACCELERATION
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. |
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
**Example**
```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) {
console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z);
}
);
```
### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup> ### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup>
once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback&lt;AccelerometerUncalibratedResponse&gt;): void once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback&lt;AccelerometerUncalibratedResponse&gt;): void
...@@ -4381,7 +4268,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4381,7 +4268,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. | | callback | Callback&lt;[AccelerometerUncalibratedResponse](#accelerometeruncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is **AccelerometerUncalibratedResponse**. |
**Example** **Example**
``` ```
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4392,7 +4278,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4392,7 +4278,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate bias: ' + data.biasZ); console.info('Z-coordinate bias: ' + data.biasZ);
} }
); );
``` ```
### GRAVITY<sup>(deprecated)</sup> ### GRAVITY<sup>(deprecated)</sup>
...@@ -4413,7 +4298,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4413,7 +4298,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[GravityResponse](#gravityresponse)&gt; | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. | | callback | Callback&lt;[GravityResponse](#gravityresponse)&gt; | Yes | One-shot callback used to return the gravity sensor data. The reported data type in the callback is **GravityResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4421,7 +4305,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4421,7 +4305,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
); );
``` ```
### GYROSCOPE<sup>(deprecated)</sup> ### GYROSCOPE<sup>(deprecated)</sup>
...@@ -4444,7 +4327,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4444,7 +4327,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[GyroscopeResponse](#gyroscoperesponse)&gt; | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. | | callback | Callback&lt;[GyroscopeResponse](#gyroscoperesponse)&gt; | Yes | One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is **GyroscopeResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4452,7 +4334,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4452,7 +4334,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
); );
``` ```
### GYROSCOPE_UNCALIBRATED<sup>(deprecated)</sup> ### GYROSCOPE_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -4475,7 +4356,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4475,7 +4356,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. | | callback | Callback&lt;[GyroscopeUncalibratedResponse](#gyroscopeuncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is **GyroscopeUncalibratedResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4486,7 +4366,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4486,7 +4366,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate bias: ' + data.biasZ); console.info('Z-coordinate bias: ' + data.biasZ);
} }
); );
``` ```
### SIGNIFICANT_MOTION<sup>(deprecated)</sup> ### SIGNIFICANT_MOTION<sup>(deprecated)</sup>
...@@ -4507,13 +4386,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4507,13 +4386,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[SignificantMotionResponse](#significantmotionresponse)&gt; | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. | | callback | Callback&lt;[SignificantMotionResponse](#significantmotionresponse)&gt; | Yes | One-shot callback used to return the significant motion sensor data. The reported data type in the callback is **SignificantMotionResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(data) {
console.info('Scalar data: ' + data.scalar); console.info('Scalar data: ' + data.scalar);
} }
); );
``` ```
### PEDOMETER_DETECTION<sup>(deprecated)</sup> ### PEDOMETER_DETECTION<sup>(deprecated)</sup>
...@@ -4536,13 +4413,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4536,13 +4413,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[PedometerDetectionResponse](#pedometerdetectionresponse)&gt; | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. | | callback | Callback&lt;[PedometerDetectionResponse](#pedometerdetectionresponse)&gt; | Yes | One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is **PedometerDetectionResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(data) {
console.info('Scalar data: ' + data.scalar); console.info('Scalar data: ' + data.scalar);
} }
); );
``` ```
### PEDOMETER<sup>(deprecated)</sup> ### PEDOMETER<sup>(deprecated)</sup>
...@@ -4565,7 +4440,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4565,7 +4440,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[PedometerResponse](#pedometerresponse)&gt; | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. | | callback | Callback&lt;[PedometerResponse](#pedometerresponse)&gt; | Yes | One-shot callback used to return the pedometer sensor data. The reported data type in the callback is **PedometerResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(data) {
console.info('Steps: ' + data.steps); console.info('Steps: ' + data.steps);
...@@ -4591,13 +4465,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4591,13 +4465,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[AmbientTemperatureResponse](#ambienttemperatureresponse)&gt; | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. | | callback | Callback&lt;[AmbientTemperatureResponse](#ambienttemperatureresponse)&gt; | Yes | One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is **AmbientTemperatureResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(data) {
console.info('Temperature: ' + data.temperature); console.info('Temperature: ' + data.temperature);
} }
); );
``` ```
### MAGNETIC_FIELD<sup>(deprecated)</sup> ### MAGNETIC_FIELD<sup>(deprecated)</sup>
...@@ -4618,7 +4490,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4618,7 +4490,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[MagneticFieldResponse](#magneticfieldresponse)&gt; | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. | | callback | Callback&lt;[MagneticFieldResponse](#magneticfieldresponse)&gt; | Yes | One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is **MagneticFieldResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4626,7 +4497,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4626,7 +4497,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
); );
``` ```
### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup> ### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -4647,7 +4517,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4647,7 +4517,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. | | callback | Callback&lt;[MagneticFieldUncalibratedResponse](#magneticfielduncalibratedresponse)&gt; | Yes | One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is **MagneticFieldUncalibratedResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4658,7 +4527,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4658,7 +4527,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Z-coordinate bias: ' + data.biasZ); console.info('Z-coordinate bias: ' + data.biasZ);
} }
); );
``` ```
### PROXIMITY<sup>(deprecated)</sup> ### PROXIMITY<sup>(deprecated)</sup>
...@@ -4679,7 +4547,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4679,7 +4547,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[ProximityResponse](#proximityresponse)&gt; | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. | | callback | Callback&lt;[ProximityResponse](#proximityresponse)&gt; | Yes | One-shot callback used to return the proximity sensor data. The reported data type in the callback is **ProximityResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(data) {
console.info('Distance: ' + data.distance); console.info('Distance: ' + data.distance);
...@@ -4705,13 +4572,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4705,13 +4572,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[HumidityResponse](#humidityresponse)&gt; | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. | | callback | Callback&lt;[HumidityResponse](#humidityresponse)&gt; | Yes | One-shot callback used to return the humidity sensor data. The reported data type in the callback is **HumidityResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(data) {
console.info('Humidity: ' + data.humidity); console.info('Humidity: ' + data.humidity);
} }
); );
``` ```
### BAROMETER<sup>(deprecated)</sup> ### BAROMETER<sup>(deprecated)</sup>
...@@ -4732,13 +4597,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4732,13 +4597,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[BarometerResponse](#barometerresponse)&gt; | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. | | callback | Callback&lt;[BarometerResponse](#barometerresponse)&gt; | Yes | One-shot callback used to return the barometer sensor data. The reported data type in the callback is **BarometerResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(data) {
console.info('Atmospheric pressure: ' + data.pressure); console.info('Atmospheric pressure: ' + data.pressure);
} }
); );
``` ```
### HALL<sup>(deprecated)</sup> ### HALL<sup>(deprecated)</sup>
...@@ -4759,13 +4622,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4759,13 +4622,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[HallResponse](#hallresponse)&gt; | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. | | callback | Callback&lt;[HallResponse](#hallresponse)&gt; | Yes | One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is **HallResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(data) {
console.info('Status: ' + data.status); console.info('Status: ' + data.status);
} }
); );
``` ```
### AMBIENT_LIGHT<sup>(deprecated)</sup> ### AMBIENT_LIGHT<sup>(deprecated)</sup>
...@@ -4792,7 +4653,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4792,7 +4653,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info(' Illumination: ' + data.intensity); console.info(' Illumination: ' + data.intensity);
} }
); );
``` ```
### ORIENTATION<sup>(deprecated)</sup> ### ORIENTATION<sup>(deprecated)</sup>
...@@ -4813,7 +4673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4813,7 +4673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[OrientationResponse](#orientationresponse)&gt; | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. | | callback | Callback&lt;[OrientationResponse](#orientationresponse)&gt; | Yes | One-shot callback used to return the orientation sensor data. The reported data type in the callback is **OrientationResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(data) {
console.info('The device rotates at an angle around the X axis: ' + data.beta); console.info('The device rotates at an angle around the X axis: ' + data.beta);
...@@ -4821,7 +4680,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4821,7 +4680,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('The device rotates at an angle around the Z axis: ' + data.alpha); console.info('The device rotates at an angle around the Z axis: ' + data.alpha);
} }
); );
``` ```
### ROTATION_VECTOR<sup>(deprecated)</sup> ### ROTATION_VECTOR<sup>(deprecated)</sup>
...@@ -4842,7 +4700,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4842,7 +4700,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[RotationVectorResponse](#rotationvectorresponse)&gt; | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. | | callback | Callback&lt;[RotationVectorResponse](#rotationvectorresponse)&gt; | Yes | One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is **RotationVectorResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(data) {
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
...@@ -4851,7 +4708,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4851,7 +4708,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
console.info('Scalar quantity: ' + data.w); console.info('Scalar quantity: ' + data.w);
} }
); );
``` ```
### HEART_RATE<sup>(deprecated)</sup> ### HEART_RATE<sup>(deprecated)</sup>
...@@ -4860,7 +4716,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRate ...@@ -4860,7 +4716,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRate
Subscribes to only one data change of the heart rate sensor. Subscribes to only one data change of the heart rate sensor.
This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_BEAT_RATE](#heart_beat_rate9) instead. This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_RATE](#heart_rate9-1) instead.
**Required permissions**: ohos.permission.HEART_RATE **Required permissions**: ohos.permission.HEART_RATE
...@@ -4873,33 +4729,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4873,33 +4729,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. | | type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | | callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
### HEART_BEAT_RATE<sup>9+</sup>
once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback&lt;HeartRateResponse&gt;): void
Subscribes to only one data change of the heart rate sensor.
**Required permissions**: ohos.permission.HEART_RATE
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to subscribe to, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
**Example**
```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) {
console.info("Heart rate: " + data.heartRate);
}
);
```
### WEAR_DETECTION<sup>(deprecated)</sup> ### WEAR_DETECTION<sup>(deprecated)</sup>
once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback&lt;WearDetectionResponse&gt;): void once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback&lt;WearDetectionResponse&gt;): void
...@@ -4918,13 +4747,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. ...@@ -4918,13 +4747,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once.
| callback | Callback&lt;[WearDetectionResponse](#weardetectionresponse)&gt; | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. | | callback | Callback&lt;[WearDetectionResponse](#weardetectionresponse)&gt; | Yes | One-shot callback used to return the wear detection sensor data. The reported data type in the callback is **WearDetectionResponse**. |
**Example** **Example**
```js ```js
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) { sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(data) {
console.info("Wear status: "+ data.value); console.info("Wear status: "+ data.value);
} }
); );
``` ```
## sensor.off<sup>(deprecated)</sup> ## sensor.off<sup>(deprecated)</sup>
...@@ -4957,7 +4784,6 @@ function callback(data) { ...@@ -4957,7 +4784,6 @@ function callback(data) {
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback);
``` ```
### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup> ### ACCELEROMETER_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -4991,7 +4817,6 @@ function callback(data) { ...@@ -4991,7 +4817,6 @@ function callback(data) {
console.info('Z-coordinate bias: ' + data.biasZ); console.info('Z-coordinate bias: ' + data.biasZ);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback);
``` ```
### AMBIENT_LIGHT<sup>(deprecated)</sup> ### AMBIENT_LIGHT<sup>(deprecated)</sup>
...@@ -5018,7 +4843,6 @@ function callback(data) { ...@@ -5018,7 +4843,6 @@ function callback(data) {
console.info(' Illumination: ' + data.intensity); console.info(' Illumination: ' + data.intensity);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback);
``` ```
### AMBIENT_TEMPERATURE<sup>(deprecated)</sup> ### AMBIENT_TEMPERATURE<sup>(deprecated)</sup>
...@@ -5045,7 +4869,6 @@ function callback(data) { ...@@ -5045,7 +4869,6 @@ function callback(data) {
console.info('Temperature: ' + data.temperature); console.info('Temperature: ' + data.temperature);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback);
``` ```
### BAROMETER<sup>(deprecated)</sup> ### BAROMETER<sup>(deprecated)</sup>
...@@ -5130,7 +4953,6 @@ function callback(data) { ...@@ -5130,7 +4953,6 @@ function callback(data) {
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback);
``` ```
### GYROSCOPE_UNCALIBRATED<sup>(deprecated)</sup> ### GYROSCOPE_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -5161,7 +4983,6 @@ function callback(data) { ...@@ -5161,7 +4983,6 @@ function callback(data) {
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback);
``` ```
### HALL<sup>(deprecated)</sup> ### HALL<sup>(deprecated)</sup>
...@@ -5188,7 +5009,6 @@ function callback(data) { ...@@ -5188,7 +5009,6 @@ function callback(data) {
console.info('Status: ' + data.status); console.info('Status: ' + data.status);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback);
``` ```
### HEART_RATE<sup>(deprecated)</sup> ### HEART_RATE<sup>(deprecated)</sup>
...@@ -5197,7 +5017,7 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback&lt;HeartRate ...@@ -5197,7 +5017,7 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback&lt;HeartRate
Unsubscribes from sensor data changes. Unsubscribes from sensor data changes.
This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_BEAT_RATE](#heart_beat_rate9) instead. This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_RATE](#heart_rate9-2) instead.
**Required permissions**: ohos.permission.HEALTH_DATA **Required permissions**: ohos.permission.HEALTH_DATA
...@@ -5210,33 +5030,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.H ...@@ -5210,33 +5030,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.H
| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. | | type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. | | callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
### HEART_BEAT_RATE<sup>9+</sup>
off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback&lt;HeartRateResponse&gt;): void
Unsubscribes from sensor data changes.
**Required permissions**: ohos.permission.HEALTH_DATA
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_HEART_BEAT_RATE**. |
| callback | Callback&lt;[HeartRateResponse](#heartrateresponse)&gt; | Yes | One-shot callback used to return the heart rate sensor data. The reported data type in the callback is **HeartRateResponse**. |
**Example**
```js
function callback(data) {
console.info("Heart rate: " + data.heartRate);
}
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback);
```
### HUMIDITY<sup>(deprecated)</sup> ### HUMIDITY<sup>(deprecated)</sup>
off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback&lt;HumidityResponse&gt;): void off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback&lt;HumidityResponse&gt;): void
...@@ -5261,7 +5054,6 @@ function callback(data) { ...@@ -5261,7 +5054,6 @@ function callback(data) {
console.info('Humidity: ' + data.humidity); console.info('Humidity: ' + data.humidity);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback);
``` ```
### LINEAR_ACCELERATION<sup>(deprecated)</sup> ### LINEAR_ACCELERATION<sup>(deprecated)</sup>
...@@ -5270,7 +5062,7 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback&lt; ...@@ -5270,7 +5062,7 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback&lt;
Unsubscribes from sensor data changes. Unsubscribes from sensor data changes.
This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9) instead. This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9-2) instead.
**Required permissions**: ohos.permission.ACCELEROMETER **Required permissions**: ohos.permission.ACCELEROMETER
...@@ -5283,35 +5075,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.L ...@@ -5283,35 +5075,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.L
| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. | | type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELERATION**. |
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. | | callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the linear acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
### LINEAR_ACCELEROMETER<sup>9+</sup>
off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback?:Callback&lt;LinearAccelerometerResponse&gt;): void
Unsubscribes from sensor data changes.
**Required permissions**: ohos.permission.ACCELEROMETER
**System capability**: SystemCapability.Sensors.Sensor
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
| type | [SensorType](#sensortype) | Yes | Type of the sensor to unsubscribe from, which is **SENSOR_TYPE_ID_LINEAR_ACCELEROMETER**. |
| callback | Callback&lt;[LinearAccelerometerResponse](#linearaccelerometerresponse)&gt; | Yes | Callback used to return the acceleration sensor data. The reported data type in the callback is **LinearAccelerometerResponse**. |
**Example**
```js
function callback(data) {
console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z);
}
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback);
```
### MAGNETIC_FIELD<sup>(deprecated)</sup> ### MAGNETIC_FIELD<sup>(deprecated)</sup>
off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback&lt;MagneticFieldResponse&gt;): void off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback&lt;MagneticFieldResponse&gt;): void
...@@ -5338,7 +5101,6 @@ function callback(data) { ...@@ -5338,7 +5101,6 @@ function callback(data) {
console.info('Z-coordinate component: ' + data.z); console.info('Z-coordinate component: ' + data.z);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback);
``` ```
### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup> ### MAGNETIC_FIELD_UNCALIBRATED<sup>(deprecated)</sup>
...@@ -5370,7 +5132,6 @@ function callback(data) { ...@@ -5370,7 +5132,6 @@ function callback(data) {
console.info('Z-coordinate bias: ' + data.biasZ); console.info('Z-coordinate bias: ' + data.biasZ);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback);
``` ```
### ORIENTATION<sup>(deprecated)</sup> ### ORIENTATION<sup>(deprecated)</sup>
...@@ -5399,7 +5160,6 @@ function callback(data) { ...@@ -5399,7 +5160,6 @@ function callback(data) {
console.info('The device rotates at an angle around the Z axis: ' + data.alpha); console.info('The device rotates at an angle around the Z axis: ' + data.alpha);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback);
``` ```
### PEDOMETER<sup>(deprecated)</sup> ### PEDOMETER<sup>(deprecated)</sup>
...@@ -5428,7 +5188,6 @@ function callback(data) { ...@@ -5428,7 +5188,6 @@ function callback(data) {
console.info('Steps: ' + data.steps); console.info('Steps: ' + data.steps);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback);
``` ```
### PEDOMETER_DETECTION<sup>(deprecated)</sup> ### PEDOMETER_DETECTION<sup>(deprecated)</sup>
...@@ -5512,7 +5271,6 @@ function callback(data) { ...@@ -5512,7 +5271,6 @@ function callback(data) {
console.info('Scalar quantity: ' + data.w); console.info('Scalar quantity: ' + data.w);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback);
``` ```
### SIGNIFICANT_MOTION<sup>(deprecated)</sup> ### SIGNIFICANT_MOTION<sup>(deprecated)</sup>
...@@ -5539,7 +5297,6 @@ function callback(data) { ...@@ -5539,7 +5297,6 @@ function callback(data) {
console.info('Scalar data: ' + data.scalar); console.info('Scalar data: ' + data.scalar);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback);
``` ```
### WEAR_DETECTION<sup>(deprecated)</sup> ### WEAR_DETECTION<sup>(deprecated)</sup>
...@@ -5566,7 +5323,6 @@ function accCallback(data) { ...@@ -5566,7 +5323,6 @@ function accCallback(data) {
console.info('Wear status: ' + data.value); console.info('Wear status: ' + data.value);
} }
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback);
``` ```
## sensor.transformCoordinateSystem<sup>(deprecated)</sup> ## sensor.transformCoordinateSystem<sup>(deprecated)</sup>
...@@ -5600,9 +5356,7 @@ sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, functi ...@@ -5600,9 +5356,7 @@ sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, functi
console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]);
} }
}) })
``` ```
## sensor.transformCoordinateSystem<sup>(deprecated)</sup> ## sensor.transformCoordinateSystem<sup>(deprecated)</sup>
transformCoordinateSystem(inRotationVector: Array&lt;number&gt;, coordinates: CoordinatesOptions): Promise&lt;Array&lt;number&gt;&gt; transformCoordinateSystem(inRotationVector: Array&lt;number&gt;, coordinates: CoordinatesOptions): Promise&lt;Array&lt;number&gt;&gt;
...@@ -5638,7 +5392,6 @@ const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x ...@@ -5638,7 +5392,6 @@ const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x
}).catch((err) => { }).catch((err) => {
console.info("Operation failed"); console.info("Operation failed");
}) })
``` ```
## sensor.getGeomagneticField<sup>(deprecated)</sup> ## sensor.getGeomagneticField<sup>(deprecated)</sup>
...@@ -5660,7 +5413,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe ...@@ -5660,7 +5413,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe
| callback | AsyncCallback&lt;[GeomagneticResponse](#geomagneticresponse)&gt; | Yes | Callback used to return the geomagnetic field. | | callback | AsyncCallback&lt;[GeomagneticResponse](#geomagneticresponse)&gt; | Yes | Callback used to return the geomagnetic field. |
**Example** **Example**
```js ```js
sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) { sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000, function(err, data) {
if (err) { if (err) {
...@@ -5671,9 +5423,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000 ...@@ -5671,9 +5423,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000
data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle +
',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity);
}); });
``` ```
## sensor.getGeomagneticField<sup>(deprecated)</sup> ## sensor.getGeomagneticField<sup>(deprecated)</sup>
getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise&lt;GeomagneticResponse&gt; getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise&lt;GeomagneticResponse&gt;
...@@ -5698,7 +5448,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe ...@@ -5698,7 +5448,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe
| Promise&lt;[GeomagneticResponse](#geomagneticresponse)&gt; | Promise used to return the geomagnetic field. | | Promise&lt;[GeomagneticResponse](#geomagneticresponse)&gt; | Promise used to return the geomagnetic field. |
**Example** **Example**
```js ```js
const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000); const promise = sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000);
promise.then((data) => { promise.then((data) => {
...@@ -5708,7 +5457,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe ...@@ -5708,7 +5457,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe
}).catch((reason) => { }).catch((reason) => {
console.info('Operation failed.'); console.info('Operation failed.');
}) })
``` ```
## sensor.getAltitude<sup>(deprecated)</sup> ## sensor.getAltitude<sup>(deprecated)</sup>
...@@ -5740,7 +5488,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe ...@@ -5740,7 +5488,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe
} }
console.info("Successed to get getAltitude interface get data: " + data); console.info("Successed to get getAltitude interface get data: " + data);
}); });
``` ```
## sensor.getAltitude<sup>(deprecated)</sup> ## sensor.getAltitude<sup>(deprecated)</sup>
...@@ -5775,7 +5522,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe ...@@ -5775,7 +5522,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe
}).catch((err) => { }).catch((err) => {
console.error("Operation failed"); console.error("Operation failed");
}) })
``` ```
...@@ -5873,7 +5619,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getAn ...@@ -5873,7 +5619,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getAn
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
}) })
``` ```
...@@ -5945,7 +5690,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo ...@@ -5945,7 +5690,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
}) })
``` ```
...@@ -5983,7 +5727,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo ...@@ -5983,7 +5727,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo
}).catch((reason) => { }).catch((reason) => {
console.info("promise::catch", reason); console.info("promise::catch", reason);
}) })
``` ```
...@@ -6017,7 +5760,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getQu ...@@ -6017,7 +5760,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getQu
console.info("data[" + i + "]: " + data[i]); console.info("data[" + i + "]: " + data[i]);
} }
}) })
``` ```
...@@ -6089,7 +5831,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getOr ...@@ -6089,7 +5831,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getOr
console.info("sensor_getDirection_callback" + data[i]); console.info("sensor_getDirection_callback" + data[i]);
} }
}) })
``` ```
...@@ -6194,5 +5935,3 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo ...@@ -6194,5 +5935,3 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo
console.info('promise failed'); console.info('promise failed');
}) })
``` ```
<!--no_check-->
\ No newline at end of file
...@@ -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
### Overview
The interface through which you interact with an operating system (OS) is the outermost layer of the OS. The most important tasks, like hardware management and system resource allocation, are handled by a module at the core of the OS. This module is called the kernel of the OS.
### Working Principles
An OS is a system software located between applications and hardware. It provides program interfaces and running environments for upper-layer applications and manages underlying hardware resources. Located at a lower layer of the OS, the kernel provides concurrent management of hardware resources for the upper-layer program framework.
**Figure 1** OS architecture
![](figures/OS_architecture.png)
### Multi-Kernel Architecture
There are many kernels in the industry. However, each kernel must have the basic units that provide the following functions:
- Implements data persistence and enables applications to easily access the file system of the persistent data.
- Manages the memory of the process address space.
- Manages multiple processes or tasks.
- Provides the "network" for communication between the OS and another OS.
OpenHarmony supports Linux and LiteOS. You can select OpenHarmony based on product specifications. Both Linux and LiteOS have the basic units, but the implementations are different. The Kernel Abstraction Layer (KAL) provides unified standard APIs for upper-layer applications, shielding the difference between kernels.
The kernel subsystem is located at the lower layer of OpenHarmony. Since OpenHarmony is oriented to devices with different CPUs and storage space, the kernel subsystem supports use of the optimal OS kernel for devices of different resource levels. The KAL shields differences between kernels and provides basic kernel capabilities for the upper layer.
**Figure 2** OpenHarmony architecture
![](figures/openharmony_architecture.png)
### OpenHarmony Types
OpenHarmony can be classified into the following types based on the supported devices:
- Mini system
The mini system fits into the devices that come with MCU processors, such as Arm Cortex-M and 32-bit RISC-V, and memory greater than or equal to 128 KiB. This system provides a variety of lightweight network protocols, a lightweight graphics framework, and a wide range of read/write components with the Internet of Things (IoT) bus. The mini system applies to smart home products such as LinkIoT module devices and sensors.
- Small system
The small system fits into the devices that come with application processors, such as Arm Cortex-A, and memory greater than or equal to 1 MiB. This system provides higher security capabilities, a standard graphics framework, and video encoding and decoding capabilities. The small system applies to smart home products such as IP cameras, peephole cameras, and routers as well as smart travel products such as event data recorders (EDRs).
- Standard system
The standard system fits into the devices that come with application processors, such as Arm Cortex-A, and memory greater than or equal to 128 MiB. This system provides a complete application framework supporting enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. The standard system applies to high-end refrigerator displays.
Different OpenHarmony systems use kernels of different forms. LiteOS applies to mini and small systems. Linux applies to small and standard systems. The table below lists the kernels and applicable systems.
**Table 1** Kernels and applicable systems
| Level| Mini System| Small System| Standard System|
| -------- | -------- | -------- | -------- |
| LiteOS-M | √ | × | × |
| LiteOS-A | × | √ | √ |
| Linux | × | √ | √ |
## LiteOS-M
### Kernel Architecture
OpenHarmony LiteOS-M is a lightweight OS kernel designed for the IoT field. It features small footprint, low power consumption, and high performance. It has a simple code structure, including the minimum kernel function set, kernel abstraction layer, optional components, and project directory. The LiteOS-M kernel is divided into the hardware layer and hardware-irrelevant layers. The hardware layer provides a unified HAL interface for easier hardware adaptation. A range of compilation toolchains can be used with different chip architectures to meet the expansion of diversified hardware and compilation toolchains in the Artificial Intelligence of Things (AIoT) field.
**Figure 3** LiteOS-M architecture
![](figures/Liteos-m-architecture.png "kernel-architecture")
### How to Use
For details about how to use LiteOS-M, see "Usage" in LiteOS-M [Kernel Overview](kernel-mini-overview.md).
## LiteOS-A
### Kernel Architecture
The LiteOS-A kernel mainly applies to small-sized systems. It is oriented to devices with M-level memory and supports memory management unit (MMU) isolation. Similar kernels in the industry include Zircon and Darwin.
To keep pace with the rapid development of the IoT industry, the OpenHarmony lightweight kernel is continuously optimized and expanded to provide application developers with friendly development experience and unified and open ecosystem capabilities. LiteOS-A has the following new features:
- Diversified kernel mechanisms
- Mechanisms such as virtual memory, system call, multi-core, lightweight Inter-Process Communication (IPC), and Discretionary Access Control (DAC) enrich kernel capabilities.
- LiteOS-A supports multiple processes, which allows application memory isolation and improves system robustness.
- Unified HDF
The HDF provides unified driver standards and access mode for device vendors. This simplifies porting of drivers and allows one-time development for multi-device deployment.
- 1200+ standard POSIX APIs
LiteOS-A supports more Portable Operating System Interface (POSIX) APIs, which facilitate software development and porting and improve developers' experience.
- Decoupling between the kernel and hardware
LiteOS-A is highly decoupled from the hardware. New boards can be added without modifying the kernel code.
**Figure 4** LiteOS-A kernel architecture
![](figures/architecture-of-the-openharmony-liteos-a-kernel.png "architecture-of-the-openharmony-liteos-a-kernel")
### How to Use
For details about how to use LiteOS-A, see "Usage" in LiteOS-A [Kernel Overview](kernel-small-overview.md).
## Linux
### Linux Kernel
Evolved from the open-source Linux kernel LTS 4.19.y and 5.10.y, the OpenHarmony Linux kernel has incorporated CVE patches and OpenHarmony features as the kernel baseline. Vendors can complete the kernel adaptation by applying the driver patches for boards.
- For more information about Linux LTS 4.19.y, visit the [official kernel website](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/log/?h=linux-4.19.y).
- For more information about Linux LTS 5.10.y, visit the [official kernel website](https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/log/?h=linux-5.10.y).
During the build process, you can merge the driver code based on the chip platform and build the kernel image. All patches are licensed under GNU General Public License (GPL) 2.0.
### Enhanced Kernel Features
OpenHarmony provides the enhanced swap (ESwap), related thread group (RTG), and lightweight CPU isolation features for the Linux kernel.
ESwap
Enhanced Swap (ESwap) allows a custom partition to serve as a swap partition and uses a resident process zswapd to encrypt and swap the anonymous pages compressed by [zram](https://gitee.com/link?target=https%3A%2F%2Fwww.kernel.org%2Fdoc%2Fhtml%2Flatest%2Fadmin-guide%2Fblockdev%2Fzram.html) to the ESwap partition. In this way, a block of memory can be completely released to ensure the available memory (Memavailable) waterline. In addition to this reclaiming mechanism, the entire memory framework is enhanced to improve the reclaiming efficiency of anonymous pages and file pages and streamline the reclaiming ratio of these two types of pages to prevent refaults caused by excessive reclamation.
**RTG**
The RTG provides optimized scheduling of a group of important threads. The load of an RTG can be collected and predicted separately and the preferred CPU cluster can be set to allow the important threads to run on the optimal CPU and the kernel to select a proper CPU frequency based on the group loads.
**Lightweight CPU Isolation**
Lightweight CPU isolation enables dynamic CPU isolation based on the system load and user configuration. The kernel migrates the tasks and interrupts from the isolated CPU to other CPUs for execution. The isolated CPU enters the idle state, which reduces the power consumption. In addition, user-mode configuration and query APIs are provided for better system optimization.
### How to Use
1. Apply HDF patches.
Apply the HDF kernel patches matching your kernel version. For details, see the method in **kernel.mk** in the **kernel/linux/build** repository.
```
$(OHOS_BUILD_HOME)/drivers/hdf_core/adapter/khdf/linux/patch_hdf.sh $(OHOS_BUILD_HOME) $(KERNEL_SRC_TMP_PATH) $(KERNEL_PATCH_PATH) $(DEVICE_NAME)
```
2. Apply the chip driver patches.
The following uses Hi3516D V300 as an example.
Place the patches for the chip component in the corresponding path based on the path and naming rules for the patches of the chip component in **kernel.mk** in the **kernel/linux/build** repository.
```
DEVICE_PATCH_DIR := $(OHOS_BUILD_HOME)/kernel/linux/patches/${KERNEL_VERSION}/$(DEVICE_NAME)_patch
DEVICE_PATCH_FILE := $(DEVICE_PATCH_DIR)/$(DEVICE_NAME).patch
```
3. Modify the **config** file to build.
Place the **config** file for the chip component in the corresponding path based on the path and naming rules of the chip component in **kernel.mk** in the **kernel/linux/build** repository.
```
KERNEL_CONFIG_PATH := $(OHOS_BUILD_HOME)/kernel/linux/config/${KERNEL_VERSION}DEFCONFIG_FILE := $(DEVICE_NAME)_$(BUILD_TYPE)_defconfig
```
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**<br>
> In the OpenHarmony project build process, patches are installed after "kernel/linux/linux-\*.\*" is copied. Before using the version-level build command of OpenHarmony, ensure that the "kernel/linux/linux-\*.\*" source code is available.
>
> After the build is complete, the kernel is generated in the kernel directory in the **out** directory. Modify the **config** file based on the kernel generated, and copy the generated **.config** file to the corresponding path in the **config** repository. Then, the configuration takes effect.
# 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)
...@@ -51,8 +51,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -51,8 +51,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.queryBundleEvents(0, 20000000000000).then( res => { usageStatistics.queryBundleEvents(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryBundleEvents promise success.'); console.log('BUNDLE_ACTIVE queryBundleEvents promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleEvents promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleEvents promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -65,9 +65,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -65,9 +65,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryBundleEvents(0, 20000000000000, (err, res) => { usageStatistics.queryBundleEvents(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleEvents callback success.'); console.log('BUNDLE_ACTIVE queryBundleEvents callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i]));
...@@ -90,9 +90,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -90,9 +90,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise success.');
let i = 1; let i = 1;
for(let key in res){ for(let key in res){
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -105,9 +105,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -105,9 +105,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryBundleStatsInfos(0, 20000000000000, (err, res) => { usageStatistics.queryBundleStatsInfos(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback success.');
let i = 1; let i = 1;
for(let key in res){ for(let key in res){
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback number : ' + i);
...@@ -131,8 +131,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -131,8 +131,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.queryCurrentBundleEvents(0, 20000000000000).then( res => { usageStatistics.queryCurrentBundleEvents(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -145,9 +145,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -145,9 +145,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryCurrentBundleEvents(0, 20000000000000, (err, res) => { usageStatistics.queryCurrentBundleEvents(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i]));
...@@ -169,8 +169,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -169,8 +169,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( res => { usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -183,9 +183,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -183,9 +183,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000, (err, res) => { usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback result ' + JSON.stringify(res[i]));
...@@ -197,7 +197,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -197,7 +197,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
6. 查询(无参)当前调用者应用的使用优先级群组,不需要配置权限。 6. 查询当前应用的使用优先级群组,不需要配置权限。
```js ```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -207,7 +207,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -207,7 +207,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.queryAppGroup().then( res => { usageStatistics.queryAppGroup().then( res => {
console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -216,11 +216,11 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -216,11 +216,11 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
// callback方式 // callback方式
try{ try{
usageStatistics.queryAppGroup((err, res) => { usageStatistics.queryAppGroup((err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -237,7 +237,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -237,7 +237,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.isIdleState("com.ohos.camera").then( res => { usageStatistics.isIdleState("com.ohos.camera").then( res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE isIdleState promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -246,11 +246,11 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -246,11 +246,11 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
// 异步方法callback方式 // 异步方法callback方式
try{ try{
usageStatistics.isIdleState("com.ohos.camera", (err, res) => { usageStatistics.isIdleState("com.ohos.camera", (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE isIdleState callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE isIdleState callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res));
} }
}); });
} catch(error) { } catch(error) {
console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -271,7 +271,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -271,7 +271,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise result ' + JSON.stringify(res[i]));
} }
}).catch( err=> { }).catch( err=> {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -295,15 +295,15 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -295,15 +295,15 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
// 异步方法callback方式 // 异步方法callback方式
try{ try{
usageStatistics.queryModuleUsageRecords(1000, (err, res) => { usageStatistics.queryModuleUsageRecords(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.'); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i]));
}
} }
}
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -348,10 +348,10 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -348,10 +348,10 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryNotificationEventStats(0, 20000000000000, (err, res) => { usageStatistics.queryNotificationEventStats(0, 20000000000000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback success.'); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback success.');
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
...@@ -380,10 +380,10 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -380,10 +380,10 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.queryDeviceEventStats(0, 20000000000000, (err, res) => { usageStatistics.queryDeviceEventStats(0, 20000000000000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback success.'); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback success.');
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
...@@ -391,7 +391,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -391,7 +391,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
11. 查询(无参)当前调用者应用的使用优先级群组,config.json中不需要配置权限。查询(有参)指定应用的使用优先级群组,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。 11. 查询指定bundleName的应用的使用优先级群组,返回查询的优先级分组结果,需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```js ```js
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -402,28 +402,28 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -402,28 +402,28 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.queryAppGroup(bundleName).then( res => { usageStatistics.queryAppGroup(bundleName).then( res => {
console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
// 有bundleName异步方法callback方式 // 有bundleName异步方法callback方式
let bundleName = "com.ohos.camera"; let bundleName = "com.ohos.camera";
try{ try{
usageStatistics.queryAppGroup(bundleName, (err, res) => { usageStatistics.queryAppGroup(bundleName, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
``` ```
11. 给应用名是bundleName的应用分组设置成newGroup,返回设置结果是否成功, 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。 12. 给指定bundleName的应用的优先级分组设置成newGroup。 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```javascript ```javascript
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -436,7 +436,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -436,7 +436,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.setAppGroup(bundleName, newGroup).then( () => { usageStatistics.setAppGroup(bundleName, newGroup).then( () => {
console.log('BUNDLE_ACTIVE setAppGroup promise succeeded.'); console.log('BUNDLE_ACTIVE setAppGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE setAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE setAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE setAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE setAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -449,9 +449,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -449,9 +449,9 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
try{ try{
usageStatistics.setAppGroup(bundleName, newGroup, (err) => { usageStatistics.setAppGroup(bundleName, newGroup, (err) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE setAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE setAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE setAppGroup callback succeeded.'); console.log('BUNDLE_ACTIVE setAppGroup callback succeeded.');
} }
}); });
} catch (error) { } catch (error) {
...@@ -459,7 +459,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -459,7 +459,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
12. 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息, 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限 13. 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息, 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限
```javascript ```javascript
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
...@@ -477,7 +477,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -477,7 +477,7 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( () => { usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( () => {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -493,8 +493,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -493,8 +493,8 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName);
}; };
try{ try{
usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, error => { usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, err => {
if(error) { if(err) {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback success.');
...@@ -505,33 +505,33 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics'; ...@@ -505,33 +505,33 @@ import usageStatistics from '@ohos.resourceschedule.usageStatistics';
} }
``` ```
13. 解除应用分组监听回调, 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限 14. 解除应用分组监听回调, 需要配置ohos.permission.BUNDLE_ACTIVE_INFO权限。
```javascript ```javascript
import usageStatistics from '@ohos.resourceschedule.usageStatistics' import usageStatistics from '@ohos.resourceschedule.usageStatistics'
// promise // promise
try{ try{
usageStatistics.unRegisterAppGroupCallBack().then( () => { usageStatistics.unregisterAppGroupCallBack().then( () => {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
// callback // callback
try{ try{
usageStatistics.unRegisterAppGroupCallBack(error => { usageStatistics.unregisterAppGroupCallBack(err => {
if(error) { if(err) {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback success.');
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE unRegisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
} }
``` ```
## 相关实例 ## 相关实例
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Native Drawing模块提供了一系列的接口用于基本图形和字体的绘制。常见的应用场景举例: Native Drawing模块提供了一系列的接口用于基本图形和字体的绘制。常见的应用场景举例:
* 2D图形绘制。 * 2D图形绘制。
* 文本绘制和显示 * 文本绘制。
## 接口说明 ## 接口说明
...@@ -138,7 +138,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ...@@ -138,7 +138,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘
OH_Drawing_BitmapDestory(cBitmap); OH_Drawing_BitmapDestory(cBitmap);
``` ```
## 文本绘制显示开发步骤 ## 文本绘制开发步骤
以下步骤描述了在OpenHarmony中,如何使用**Native Drawing**模块的文字显示功能: 以下步骤描述了在OpenHarmony中,如何使用**Native Drawing**模块的文字显示功能:
1. **创建画布和bitmap实例** 1. **创建画布和bitmap实例**
...@@ -182,7 +182,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ...@@ -182,7 +182,7 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘
OH_Drawing_SetTextStyleLocale(txtStyle, "en"); OH_Drawing_SetTextStyleLocale(txtStyle, "en");
``` ```
4. **生成最终文显示效果** 4. **生成最终文显示效果**
```c++ ```c++
OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle, OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle,
...@@ -196,8 +196,9 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ...@@ -196,8 +196,9 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘
// 设置页面最大宽度 // 设置页面最大宽度
double maxWidth = 800.0; double maxWidth = 800.0;
OH_Drawing_TypographyLayout(typography, maxWidth); OH_Drawing_TypographyLayout(typography, maxWidth);
// 设置文字显示起始位置 // 设置文本在画布上绘制的起始位置
double position[2] = {10.0, 15.0}; double position[2] = {10.0, 15.0};
// 将文本绘制到画布上
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
``` ```
...@@ -205,4 +206,4 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘 ...@@ -205,4 +206,4 @@ Native Drawing模块提供了一系列的接口用于基本图形和字体的绘
针对Drawing模块的使用,有以下相关实例可供参考: 针对Drawing模块的使用,有以下相关实例可供参考:
* [Drawing模块2D图形绘制](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp) * [Drawing模块2D图形绘制](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Drawing模块文本绘制显示](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp) * [Drawing模块文本绘制](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
# 资源分类与访问 # 资源分类与访问
## 资源分类 应用开发过程中,经常需要用到颜色、字体、间距、图片等资源,在不同的设备或配置中,这些资源的值可能不同。
- 应用资源:借助资源文件能力,开发者在应用中自定义资源,自行管理这些资源在不同的设备或配置中的表现。
- 系统资源:开发者直接使用系统预置的资源定义(即[分层参数](../key-features/multi-device-app-dev/visual-basics.md),同一资源ID在设备类型、深浅色等不同配置下有不同的取值)。
应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。 ## 资源分类
### resources目录 ### resources目录
resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类为rawfile目录。stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。 应用开发中使用的各类资源文件,需要放入特定子目录中存储管理。resources目录包括三大类目录,一类为base目录,一类为限定词目录,还有一类为rawfile目录。stage模型多工程情况下共有的资源文件放到AppScope下的resources目录。
base目录默认存在,而限定词目录需要开发者自行创建。应用使用某资源时,系统会根据当前设备状态优先从相匹配的限定词目录中寻找该资源。只有当resources目录中没有与设备状态匹配的限定词目录,或者在限定词目录中找不到该资源时,才会去base目录中查找。rawfile是原始文件目录,不会根据设备状态去匹配不同的资源。
资源目录示例: 资源目录示例:
``` ```
resources resources
...@@ -266,9 +272,17 @@ Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下 ...@@ -266,9 +272,17 @@ Image($rawfile('newDir/newTest.png')) // rawfile$r引用rawfile目录下
系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。 系统资源包含色彩、圆角、字体、间距、字符串及图片等。通过使用系统资源,不同的开发者可以开发出具有相同视觉风格的应用。
开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。 开发者可以通过```“$r('sys.type.resource_id')”```的形式引用系统资源。sys代表是系统资源;type代表资源类型,可以取“color”、“float”、“string”、“media”;resource_id代表资源id。
可以查看[应用UX设计中关于资源的介绍](../key-features/multi-device-app-dev/design-resources.md),获取OpenHarmony支持的系统资源ID及其在不同配置下的取值。
> **说明:**
>
> - 仅声明式开发范式支持使用系统资源,类Web开发范式不支持。
>
> - 可以查看[OpenHarmony/resources代码仓](https://gitee.com/openharmony/resources/tree/master/systemres/main/resources)了解系统预置资源的实现,这里的目录结构与工程中的resources目录类似,也是通过资源限定词匹配不同的设备或设备状态。
> - 系统资源的使用场景、id、参数详细对照表详见[OpenHarmony_系统资源分层设计表_V1.0.xlsm](../key-features/multi-device-app-dev/OpenHarmony_系统资源分层设计表_V1.0.xlsm)
```ts ```ts
Text('Hello') Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize')) .fontColor($r('sys.color.ohos_id_color_emphasize'))
......
...@@ -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)
......
...@@ -235,7 +235,9 @@ cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapab ...@@ -235,7 +235,9 @@ cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapab
isCameraMuted(): boolean isCameraMuted(): boolean
查询相机是否被禁用,通过返回值返回结果。 查询相机当前的禁用状态(禁用/未禁用)。
在此之前,需要通过[isCameraMuteSupported](#iscameramutesupported)确认当前设备支持禁用相机。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -255,7 +257,7 @@ let ismuted = await cameraManager.isCameraMuted(); ...@@ -255,7 +257,7 @@ let ismuted = await cameraManager.isCameraMuted();
isCameraMuteSupported(): boolean isCameraMuteSupported(): boolean
查询相机是否能被禁用,通过返回值返回结果。 查询当前设备是否支持禁用相机,通过返回值返回结果。
**系统能力:** SystemCapability.Multimedia.Camera.Core **系统能力:** SystemCapability.Multimedia.Camera.Core
...@@ -3303,7 +3305,7 @@ isMirrorSupported(callback: AsyncCallback<boolean\>): void ...@@ -3303,7 +3305,7 @@ isMirrorSupported(callback: AsyncCallback<boolean\>): void
**示例:** **示例:**
```js ```js
captureSession.isMirrorSupported((err, isSupported) => { photoOutput.isMirrorSupported((err, isSupported) => {
if (err) { if (err) {
console.error(`Failed to check mirror is supported ${err.message}`); console.error(`Failed to check mirror is supported ${err.message}`);
return; return;
...@@ -3329,7 +3331,7 @@ isMirrorSupported(): Promise<boolean\> ...@@ -3329,7 +3331,7 @@ isMirrorSupported(): Promise<boolean\>
**示例:** **示例:**
```js ```js
captureSession.isMirrorSupported().then((isSupported) => { photoOutput.isMirrorSupported().then((isSupported) => {
console.log(`Promise returned with mirror supported: ${isSupported}`); console.log(`Promise returned with mirror supported: ${isSupported}`);
}) })
``` ```
......
...@@ -655,11 +655,7 @@ openSync(path: string, flags?: number, mode?: number): number ...@@ -655,11 +655,7 @@ openSync(path: string, flags?: number, mode?: number): number
## fileio.read ## fileio.read
read(fd: number, buffer: ArrayBuffer, options?: { read(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): Promise&lt;ReadOut&gt;
offset?: number;
length?: number;
position?: number;
}): Promise&lt;ReadOut&gt;
从文件读取数据,使用Promise异步回调。 从文件读取数据,使用Promise异步回调。
...@@ -696,11 +692,7 @@ read(fd: number, buffer: ArrayBuffer, options?: { ...@@ -696,11 +692,7 @@ read(fd: number, buffer: ArrayBuffer, options?: {
## fileio.read ## fileio.read
read(fd: number, buffer: ArrayBuffer, options: { read(fd: number, buffer: ArrayBuffer, options: { offset?: number; length?: number; position?: number; }, callback: AsyncCallback&lt;ReadOut&gt;): void
offset?: number;
length?: number;
position?: number;
}, callback: AsyncCallback&lt;ReadOut&gt;): void
从文件读取数据,使用callback异步回调。 从文件读取数据,使用callback异步回调。
...@@ -732,11 +724,7 @@ read(fd: number, buffer: ArrayBuffer, options: { ...@@ -732,11 +724,7 @@ read(fd: number, buffer: ArrayBuffer, options: {
## fileio.readSync ## fileio.readSync
readSync(fd: number, buffer: ArrayBuffer, options?: { readSync(fd: number, buffer: ArrayBuffer, options?: { offset?: number; length?: number; position?: number; }): number
offset?: number;
length?: number;
position?: number;
}): number
以同步方法从文件读取数据。 以同步方法从文件读取数据。
...@@ -927,12 +915,7 @@ unlinkSync(path: string): void ...@@ -927,12 +915,7 @@ unlinkSync(path: string): void
## fileio.write ## fileio.write
write(fd: number, buffer: ArrayBuffer | string, options?: { write(fd: number, buffer: ArrayBuffer | string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): Promise&lt;number&gt;
offset?: number;
length?: number;
position?: number;
encoding?: string;
}): Promise&lt;number&gt;
将数据写入文件,使用Promise异步回调。 将数据写入文件,使用Promise异步回调。
...@@ -967,12 +950,7 @@ write(fd: number, buffer: ArrayBuffer | string, options?: { ...@@ -967,12 +950,7 @@ write(fd: number, buffer: ArrayBuffer | string, options?: {
## fileio.write ## fileio.write
write(fd: number, buffer: ArrayBuffer | string, options: { write(fd: number, buffer: ArrayBuffer | string, options: { offset?: number; length?: number; position?: number; encoding?: string; }, callback: AsyncCallback&lt;number&gt;): void
offset?: number;
length?: number;
position?: number;
encoding?: string;
}, callback: AsyncCallback&lt;number&gt;): void
将数据写入文件,使用callback异步回调。 将数据写入文件,使用callback异步回调。
...@@ -1002,12 +980,7 @@ write(fd: number, buffer: ArrayBuffer | string, options: { ...@@ -1002,12 +980,7 @@ write(fd: number, buffer: ArrayBuffer | string, options: {
## fileio.writeSync ## fileio.writeSync
writeSync(fd: number, buffer: ArrayBuffer | string, options?: { writeSync(fd: number, buffer: ArrayBuffer | string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number
offset?: number;
length?: number;
position?: number;
encoding?: string;
}): number
以同步方法将数据写入文件。 以同步方法将数据写入文件。
...@@ -1441,11 +1414,7 @@ truncateSync(path: string, len?: number): void ...@@ -1441,11 +1414,7 @@ truncateSync(path: string, len?: number): void
## fileio.readText<sup>7+</sup> ## fileio.readText<sup>7+</sup>
readText(filePath: string, options?: { readText(filePath: string, options?: { position?: number; length?: number; encoding?: string; }): Promise&lt;string&gt;
position?: number;
length?: number;
encoding?: string;
}): Promise&lt;string&gt;
基于文本方式读取文件(即直接读取文件的文本内容),使用Promise异步回调。 基于文本方式读取文件(即直接读取文件的文本内容),使用Promise异步回调。
...@@ -1478,11 +1447,7 @@ readText(filePath: string, options?: { ...@@ -1478,11 +1447,7 @@ readText(filePath: string, options?: {
## fileio.readText<sup>7+</sup> ## fileio.readText<sup>7+</sup>
readText(filePath: string, options: { readText(filePath: string, options: { position?: number; length?: number; encoding?: string; }, callback: AsyncCallback&lt;string&gt;): void
position?: number;
length?: number;
encoding?: string;
}, callback: AsyncCallback&lt;string&gt;): void
基于文本方式读取文件(即直接读取文件的文本内容),使用callback异步回调。 基于文本方式读取文件(即直接读取文件的文本内容),使用callback异步回调。
...@@ -1508,11 +1473,7 @@ readText(filePath: string, options: { ...@@ -1508,11 +1473,7 @@ readText(filePath: string, options: {
## fileio.readTextSync<sup>7+</sup> ## fileio.readTextSync<sup>7+</sup>
readTextSync(filePath: string, options?: { readTextSync(filePath: string, options?: { position?: number; length?: number; encoding?: string; }): string
position?: number;
length?: number;
encoding?: string;
}): string
以同步方法基于文本方式读取文件(即直接读取文件的文本内容)。 以同步方法基于文本方式读取文件(即直接读取文件的文本内容)。
...@@ -2995,12 +2956,7 @@ flushSync(): void ...@@ -2995,12 +2956,7 @@ flushSync(): void
### write<sup>7+</sup> ### write<sup>7+</sup>
write(buffer: ArrayBuffer | string, options?: { write(buffer: ArrayBuffer | string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): Promise&lt;number&gt;
offset?: number;
length?: number;
position?: number;
encoding?: string;
}): Promise&lt;number&gt;
将数据写入流文件,使用Promise异步回调。 将数据写入流文件,使用Promise异步回调。
...@@ -3034,12 +2990,7 @@ write(buffer: ArrayBuffer | string, options?: { ...@@ -3034,12 +2990,7 @@ write(buffer: ArrayBuffer | string, options?: {
### write<sup>7+</sup> ### write<sup>7+</sup>
write(buffer: ArrayBuffer | string, options: { write(buffer: ArrayBuffer | string, options: { offset?: number; length?: number; position?: number; encoding?: string; }, callback: AsyncCallback&lt;number&gt;): void
offset?: number;
length?: number;
position?: number;
encoding?: string;
}, callback: AsyncCallback&lt;number&gt;): void
将数据写入流文件,使用callback异步回调。 将数据写入流文件,使用callback异步回调。
...@@ -3069,12 +3020,7 @@ write(buffer: ArrayBuffer | string, options: { ...@@ -3069,12 +3020,7 @@ write(buffer: ArrayBuffer | string, options: {
### writeSync<sup>7+</sup> ### writeSync<sup>7+</sup>
writeSync(buffer: ArrayBuffer | string, options?: { writeSync(buffer: ArrayBuffer | string, options?: { offset?: number; length?: number; position?: number; encoding?: string; }): number
offset?: number;
length?: number;
position?: number;
encoding?: string;
}): number
以同步方法将数据写入流文件。 以同步方法将数据写入流文件。
...@@ -3104,11 +3050,7 @@ writeSync(buffer: ArrayBuffer | string, options?: { ...@@ -3104,11 +3050,7 @@ writeSync(buffer: ArrayBuffer | string, options?: {
### read<sup>7+</sup> ### read<sup>7+</sup>
read(buffer: ArrayBuffer, options?: { read(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }): Promise&lt;ReadOut&gt;
position?: number;
offset?: number;
length?: number;
}): Promise&lt;ReadOut&gt;
从流文件读取数据,使用Promise异步回调。 从流文件读取数据,使用Promise异步回调。
...@@ -3143,11 +3085,7 @@ read(buffer: ArrayBuffer, options?: { ...@@ -3143,11 +3085,7 @@ read(buffer: ArrayBuffer, options?: {
### read<sup>7+</sup> ### read<sup>7+</sup>
read(buffer: ArrayBuffer, options: { read(buffer: ArrayBuffer, options: { position?: number; offset?: number; length?: number; }, callback: AsyncCallback&lt;ReadOut&gt;): void
position?: number;
offset?: number;
length?: number;
}, callback: AsyncCallback&lt;ReadOut&gt;): void
从流文件读取数据,使用callback异步回调。 从流文件读取数据,使用callback异步回调。
...@@ -3177,11 +3115,7 @@ read(buffer: ArrayBuffer, options: { ...@@ -3177,11 +3115,7 @@ read(buffer: ArrayBuffer, options: {
### readSync<sup>7+</sup> ### readSync<sup>7+</sup>
readSync(buffer: ArrayBuffer, options?: { readSync(buffer: ArrayBuffer, options?: { position?: number; offset?: number; length?: number; }): number
position?: number;
offset?: number;
length?: number;
}): number
以同步方法从流文件读取数据。 以同步方法从流文件读取数据。
......
...@@ -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 | 否 | 执行延迟提醒间隔。 |
......
...@@ -57,15 +57,14 @@ isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void ...@@ -57,15 +57,14 @@ isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void
| 10000006 | Get application info failed. | | 10000006 | Get application info failed. |
**示例** **示例**
```js
```
try{ try{
usageStatistics.isIdleState("com.ohos.camera", (err, res) => { usageStatistics.isIdleState("com.ohos.camera", (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE isIdleState callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE isIdleState callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState callback succeeded, result: ' + JSON.stringify(res));
} }
}); });
} catch(error) { } catch(error) {
console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -111,7 +110,7 @@ isIdleState(bundleName: string): Promise&lt;boolean&gt; ...@@ -111,7 +110,7 @@ isIdleState(bundleName: string): Promise&lt;boolean&gt;
usageStatistics.isIdleState("com.ohos.camera").then( res => { usageStatistics.isIdleState("com.ohos.camera").then( res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE isIdleState promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE isIdleState throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -193,11 +192,11 @@ queryAppGroup(callback: AsyncCallback&lt;number&gt;): void ...@@ -193,11 +192,11 @@ queryAppGroup(callback: AsyncCallback&lt;number&gt;): void
```javascript ```javascript
try{ try{
usageStatistics.queryAppGroup((err, res) => { usageStatistics.queryAppGroup((err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -243,15 +242,15 @@ queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback&lt;Bun ...@@ -243,15 +242,15 @@ queryBundleStatsInfos(begin: number, end: number, callback: AsyncCallback&lt;Bun
try{ try{
usageStatistics.queryBundleStatsInfos(0, 20000000000000, (err, res) => { usageStatistics.queryBundleStatsInfos(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback success.');
let i = 1; let i = 1;
for(let key in res){ for(let key in res){
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStatsInfos callback result ' + JSON.stringify(res[key]));
i++; i++;
} }
} }
}); });
} catch (error) { } catch (error) {
...@@ -305,9 +304,9 @@ queryBundleStatsInfos(begin: number, end: number): Promise&lt;BundleStatsMap&gt; ...@@ -305,9 +304,9 @@ queryBundleStatsInfos(begin: number, end: number): Promise&lt;BundleStatsMap&gt;
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise success.');
let i = 1; let i = 1;
for(let key in res){ for(let key in res){
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise number : ' + i); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise number : ' + i);
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfos promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -357,13 +356,13 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num ...@@ -357,13 +356,13 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num
try{ try{
usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000, (err, res) => { usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval callback result ' + JSON.stringify(res[i]));
} }
} }
}); });
} catch (error) { } catch (error) {
...@@ -417,8 +416,8 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num ...@@ -417,8 +416,8 @@ queryBundleStatsInfoByInterval(byInterval: IntervalType, begin: number, end: num
usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( res => { usageStatistics.queryBundleStatsInfoByInterval(0, 0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleStatsInfoByInterval promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -467,13 +466,13 @@ queryBundleEvents(begin: number, end: number, callback: AsyncCallback&lt;Array&l ...@@ -467,13 +466,13 @@ queryBundleEvents(begin: number, end: number, callback: AsyncCallback&lt;Array&l
try{ try{
usageStatistics.queryBundleEvents(0, 20000000000000, (err, res) => { usageStatistics.queryBundleEvents(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryBundleEvents callback success.'); console.log('BUNDLE_ACTIVE queryBundleEvents callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleEvents callback result ' + JSON.stringify(res[i]));
} }
} }
}); });
} catch (error) { } catch (error) {
...@@ -526,8 +525,8 @@ queryBundleEvents(begin: number, end: number): Promise&lt;Array&lt;BundleEvents& ...@@ -526,8 +525,8 @@ queryBundleEvents(begin: number, end: number): Promise&lt;Array&lt;BundleEvents&
usageStatistics.queryBundleEvents(0, 20000000000000).then( res => { usageStatistics.queryBundleEvents(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryBundleEvents promise success.'); console.log('BUNDLE_ACTIVE queryBundleEvents promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleEvents promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleEvents promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleEvents promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -572,13 +571,13 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback&lt; ...@@ -572,13 +571,13 @@ queryCurrentBundleEvents(begin: number, end: number, callback: AsyncCallback&lt;
try{ try{
usageStatistics.queryCurrentBundleEvents(0, 20000000000000, (err, res) => { usageStatistics.queryCurrentBundleEvents(0, 20000000000000, (err, res) => {
if (err) { if (err) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents callback result ' + JSON.stringify(res[i]));
} }
} }
}); });
} catch (error) { } catch (error) {
...@@ -627,8 +626,8 @@ queryCurrentBundleEvents(begin: number, end: number): Promise&lt;Array&lt;Bundle ...@@ -627,8 +626,8 @@ queryCurrentBundleEvents(begin: number, end: number): Promise&lt;Array&lt;Bundle
usageStatistics.queryCurrentBundleEvents(0, 20000000000000).then( res => { usageStatistics.queryCurrentBundleEvents(0, 20000000000000).then( res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryCurrentBundleEvents promise failed. code is: ' + err.code + ',message is: ' + err.message);
...@@ -831,15 +830,15 @@ queryModuleUsageRecords(maxNum: number, callback: AsyncCallback&lt;Array&lt;HapM ...@@ -831,15 +830,15 @@ queryModuleUsageRecords(maxNum: number, callback: AsyncCallback&lt;Array&lt;HapM
```js ```js
try{ try{
usageStatistics.queryModuleUsageRecords(1000, (err, res) => { usageStatistics.queryModuleUsageRecords(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.'); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback succeeded.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryModuleUsageRecords callback result ' + JSON.stringify(res[i]));
}
} }
}
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryModuleUsageRecords throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -893,7 +892,7 @@ queryAppGroup(bundleName : string): Promise&lt;number&gt; ...@@ -893,7 +892,7 @@ queryAppGroup(bundleName : string): Promise&lt;number&gt;
usageStatistics.queryAppGroup(bundleName).then( res => { usageStatistics.queryAppGroup(bundleName).then( res => {
console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -939,11 +938,11 @@ queryAppGroup(bundleName : string, callback: AsyncCallback&lt;number&gt;): void ...@@ -939,11 +938,11 @@ queryAppGroup(bundleName : string, callback: AsyncCallback&lt;number&gt;): void
let bundleName = "com.ohos.camera"; let bundleName = "com.ohos.camera";
try{ try{
usageStatistics.queryAppGroup(bundleName, (err, res) => { usageStatistics.queryAppGroup(bundleName, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE queryAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -999,7 +998,7 @@ setAppGroup(bundleName: string, newGroup: GroupType): Promise&lt;void&gt; ...@@ -999,7 +998,7 @@ setAppGroup(bundleName: string, newGroup: GroupType): Promise&lt;void&gt;
usageStatistics.setAppGroup(bundleName, newGroup).then( () => { usageStatistics.setAppGroup(bundleName, newGroup).then( () => {
console.log('BUNDLE_ACTIVE setAppGroup promise succeeded.'); console.log('BUNDLE_ACTIVE setAppGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE setAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE setAppGroup promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE setAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE setAppGroup throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -1048,9 +1047,9 @@ setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback&lt; ...@@ -1048,9 +1047,9 @@ setAppGroup(bundleName: string, newGroup: GroupType, callback: AsyncCallback&lt;
try{ try{
usageStatistics.setAppGroup(bundleName, newGroup, (err) => { usageStatistics.setAppGroup(bundleName, newGroup, (err) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE setAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE setAppGroup callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE setAppGroup callback succeeded.'); console.log('BUNDLE_ACTIVE setAppGroup callback succeeded.');
} }
}); });
} catch (error) { } catch (error) {
...@@ -1109,7 +1108,7 @@ registerAppGroupCallBack(groupCallback: Callback&lt;AppGroupCallbackInfo&gt;): P ...@@ -1109,7 +1108,7 @@ registerAppGroupCallBack(groupCallback: Callback&lt;AppGroupCallbackInfo&gt;): P
usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( () => { usageStatistics.registerAppGroupCallBack(onBundleGroupChanged).then( () => {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack promise failed. code is: ' + err.code + ',message is: ' + err.message);
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -1160,12 +1159,12 @@ registerAppGroupCallBack(groupCallback: Callback&lt;AppGroupCallbackInfo&gt;, ca ...@@ -1160,12 +1159,12 @@ registerAppGroupCallBack(groupCallback: Callback&lt;AppGroupCallbackInfo&gt;, ca
console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE registerAppGroupCallBack result bundleName is : ' + res.bundleName);
}; };
try{ try{
usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, error => { usageStatistics.registerAppGroupCallBack(onBundleGroupChanged, err => {
if(error) { if(err) {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE registerAppGroupCallBack callback success.');
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE registerAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -1252,12 +1251,12 @@ unregisterAppGroupCallBack(callback: AsyncCallback&lt;void&gt;): void; ...@@ -1252,12 +1251,12 @@ unregisterAppGroupCallBack(callback: AsyncCallback&lt;void&gt;): void;
```javascript ```javascript
try{ try{
usageStatistics.unregisterAppGroupCallBack(error => { usageStatistics.unregisterAppGroupCallBack(err => {
if(error) { if(err) {
console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack callback success.');
} }
}); });
} catch (error) { } catch (error) {
console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message); console.log('BUNDLE_ACTIVE unregisterAppGroupCallBack throw error, code is: ' + error.code + ',message is: ' + error.message);
...@@ -1356,10 +1355,10 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback&lt;Arr ...@@ -1356,10 +1355,10 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback&lt;Arr
try{ try{
usageStatistics.queryDeviceEventStats(0, 20000000000000, (err, res) => { usageStatistics.queryDeviceEventStats(0, 20000000000000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback success.'); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback success.');
console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryDeviceEventStats callback result ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
...@@ -1459,10 +1458,10 @@ queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback& ...@@ -1459,10 +1458,10 @@ queryNotificationEventStats(begin: number, end: number, callback: AsyncCallback&
try{ try{
usageStatistics.queryNotificationEventStats(0, 20000000000000, (err, res) => { usageStatistics.queryNotificationEventStats(0, 20000000000000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback failed. code is: ' + err.code + ',message is: ' + err.message);
} else { } else {
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback success.'); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback success.');
console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryNotificationEventStats callback result ' + JSON.stringify(res));
} }
}); });
} catch (error) { } catch (error) {
......
...@@ -6139,7 +6139,7 @@ isObjectDead(): boolean ...@@ -6139,7 +6139,7 @@ isObjectDead(): boolean
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 参数名 | 值 | 说明 | | 名称 | 值 | 说明 |
| --------------------- | ----------------------- | --------------------------------- | | --------------------- | ----------------------- | --------------------------------- |
| PING_TRANSACTION | 1599098439 (0x5f504e47) | 内部指令码,用于测试IPC服务正常。 | | PING_TRANSACTION | 1599098439 (0x5f504e47) | 内部指令码,用于测试IPC服务正常。 |
| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | 内部指令码,获取Binder内部状态。 | | DUMP_TRANSACTION | 1598311760 (0x5f444d50) | 内部指令码,获取Binder内部状态。 |
...@@ -6963,12 +6963,12 @@ isObjectDead(): boolean ...@@ -6963,12 +6963,12 @@ isObjectDead(): boolean
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 参数名 | 值 | 说明 | | 名称 | 值 | 说明 |
| ------------- | ---- | ----------------------------------------------------------- | | ------------- | ---- | ----------------------------------------------------------- |
| TF_SYNC | 0 | 同步调用。 | | TF_SYNC | 0 | 同步调用标识。 |
| TF_ASYNC | 1 | 异步调用。 | | TF_ASYNC | 1 | 异步调用标识。 |
| TF_ACCEPT_FDS | 0x10 | 指示sendMessageRequest<sup>9+</sup>接口可以返回文件描述符。 | | TF_ACCEPT_FDS | 0x10 | 指示sendMessageRequest<sup>9+</sup>接口可以返回文件描述符。 |
| TF_WAIT_TIME | 8 | 等待时间。单位秒。 | | TF_WAIT_TIME | 8 | 默认等待时间(单位/秒)。 |
### constructor<sup>9+</sup> ### constructor<sup>9+</sup>
...@@ -8412,7 +8412,7 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void ...@@ -8412,7 +8412,7 @@ attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
**系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。 **系统能力**:以下各项对应的系统能力均为SystemCapability.Communication.IPC.Core。
| 参数名 | 值 | 说明 | | 名称 | 值 | 说明 |
| ---------- | --- | ------------------ | | ---------- | --- | ------------------ |
| PROT_EXEC | 4 | 映射的内存可执行 | | PROT_EXEC | 4 | 映射的内存可执行 |
| PROT_NONE | 0 | 映射的内存不可访问 | | PROT_NONE | 0 | 映射的内存不可访问 |
......
# 用户界面外观
用户界面外观提供管理系统外观的一些基础能力,目前仅包括深浅色模式配置。
> **说明:**
>
> 从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
>
> 本模块接口为系统接口。
## 导入模块
```ts
import uiAppearance from '@ohos.uiAppearance'
```
## DarkMode
深色模式枚举。
**系统能力:** SystemCapability.ArkUI.UiAppearance
| 名称 | 值 | 说明 |
| -- | -- | -- |
| ALWAYS_DARK | 0 | 系统始终为深色。 |
| ALWAYS_LIGHT | 1 | 系统始终为浅色。 |
## uiAppearance.setDarkMode
setDarkMode(mode: DarkMode, callback: AsyncCallback\<void>): void
设置系统深色模式。
**需要权限:** ohos.permission.UPDATE_CONFIGURATION
**系统能力:** SystemCapability.ArkUI.UiAppearance
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | 是 | 指定系统的深色模式配置 |
| callback | AsyncCallback\<void>| 是 | 配置深色模式的异步回调 |
**示例:**
```ts
uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK, (err) => {
console.info(`${err}`);
})
```
## uiAppearance.setDarkMode
setDarkMode(mode: DarkMode): Promise\<void>;
设置系统深色模式。
**需要权限:** ohos.permission.UPDATE_CONFIGURATION
**系统能力:** SystemCapability.ArkUI.UiAppearance
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -- | -- | -- | -- |
| mode | [DarkMode](#darkmode) | 是 | 指定系统深色模式配置 |
**返回值:**
| 类型 | 说明 |
| ------ | ------------------------------ |
| Promise\<void> | Promise对象。无返回结果的Promise对象。|
**示例:**
```ts
uiAppearance.setDarkMode(uiAppearance.DarkMode.ALWAYS_DARK).then(() => {
console.log('Set dark-mode successfully.');
}).catch((err) => {
console.log(`Set dark-mode failed, ${err}`);
});
```
## uiAppearance.getDarkMode
getDarkMode(): DarkMode;
获取当前的深色模式配置。
**需要权限:** ohos.permission.UPDATE_CONFIGURATION
**系统能力:** SystemCapability.ArkUI.UiAppearance
**返回值:**
| 类型 | 说明 |
| -- | -- |
|[DarkMode](#darkmode) | 系统当前的深色模式配置 |
**示例:**
```ts
let darkMode = uiAppearance.getDarkMode();
console.log(`Get dark-mode ${darkMode}`);
```
\ No newline at end of file
...@@ -26,7 +26,7 @@ import web_webview from '@ohos.web.webview'; ...@@ -26,7 +26,7 @@ import web_webview from '@ohos.web.webview';
close(): void close(): void
关闭该息端口。 关闭该息端口。
**系统能力:** **系统能力:**
SystemCapability.Web.Webview.Core SystemCapability.Web.Webview.Core
...@@ -59,7 +59,7 @@ struct WebComponent { ...@@ -59,7 +59,7 @@ struct WebComponent {
postMessageEvent(message: string): void postMessageEvent(message: string): void
发送消息。 发送消息。完整示例代码参考[postMessage](#postmessage)
**系统能力:** **系统能力:**
SystemCapability.Web.Webview.Core SystemCapability.Web.Webview.Core
...@@ -112,7 +112,7 @@ struct WebComponent { ...@@ -112,7 +112,7 @@ struct WebComponent {
onMessageEvent(callback: (result: string) => void): void onMessageEvent(callback: (result: string) => void): void
注册回调函数,接收HTML5侧发送过来的消息。 注册回调函数,接收HTML5侧发送过来的消息。完整示例代码参考[postMessage](#postmessage)
**系统能力:** **系统能力:**
SystemCapability.Web.Webview.Core SystemCapability.Web.Webview.Core
...@@ -1293,7 +1293,7 @@ struct WebComponent { ...@@ -1293,7 +1293,7 @@ struct WebComponent {
createWebMessagePorts(): Array\<WebMessagePort> createWebMessagePorts(): Array\<WebMessagePort>
创建Web息端口。 创建Web息端口。
**系统能力:** **系统能力:**
SystemCapability.Web.Webview.Core SystemCapability.Web.Webview.Core
...@@ -1302,7 +1302,7 @@ SystemCapability.Web.Webview.Core ...@@ -1302,7 +1302,7 @@ SystemCapability.Web.Webview.Core
| 类型 | 说明 | | 类型 | 说明 |
| ---------------------- | ----------------- | | ---------------------- | ----------------- |
| Array\<WebMessagePort> | web息端口列表。 | | Array\<WebMessagePort> | web息端口列表。 |
**错误码** **错误码**
...@@ -1345,7 +1345,7 @@ struct WebComponent { ...@@ -1345,7 +1345,7 @@ struct WebComponent {
postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void
发送Web息端口到HTML5。 发送Web息端口到HTML5。
**系统能力:** **系统能力:**
SystemCapability.Web.Webview.Core SystemCapability.Web.Webview.Core
...@@ -1354,9 +1354,9 @@ SystemCapability.Web.Webview.Core ...@@ -1354,9 +1354,9 @@ SystemCapability.Web.Webview.Core
| 参数名 | 类型 | 必填 | 默认值 | 说明 | | 参数名 | 类型 | 必填 | 默认值 | 说明 |
| ------ | ---------------------- | ---- | ------ | :------------------------------- | | ------ | ---------------------- | ---- | ------ | :------------------------------- |
| name | string | 是 | - | 要发送的信息,包含数据和信息端口 | | name | string | 是 | - | 要发送的消息,包含数据和消息端口。 |
| ports | Array\<WebMessagePort> | 是 | - | 接收该息的URI。 | | ports | Array\<WebMessagePort> | 是 | - | 接收该息的URI。 |
| uri | string | 是 | - | 接收该息的URI。 | | uri | string | 是 | - | 接收该息的URI。 |
**错误码** **错误码**
......
...@@ -30,7 +30,7 @@ CheckboxGroup(options?: { group?: string }) ...@@ -30,7 +30,7 @@ CheckboxGroup(options?: { group?: string })
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| selectAll | boolean | 设置是否全选。<br/>默认值:false | | selectAll | boolean | 设置是否全选。<br/>默认值:false,若同组的Checkbox显式设置select,则Checkbox的优先级高。 |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置被选中或部分选中状态的颜色。 | | selectedColor | [ResourceColor](ts-types.md#resourcecolor) | 设置被选中或部分选中状态的颜色。 |
## 事件 ## 事件
......
...@@ -3597,14 +3597,14 @@ getCookieManager(): WebCookie ...@@ -3597,14 +3597,14 @@ getCookieManager(): WebCookie
createWebMessagePorts(): Array\<WebMessagePort\> createWebMessagePorts(): Array\<WebMessagePort\>
创建Web息端口。 创建Web息端口。
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| ------------------------------- | ------------- | | ------------------------------- | ------------- |
| Array\<[WebMessagePort](#webmessageport9)\> | web息端口列表。 | | Array\<[WebMessagePort](#webmessageport9)\> | web息端口列表。 |
**示例:** **示例:**
...@@ -3632,14 +3632,14 @@ createWebMessagePorts(): Array\<WebMessagePort\> ...@@ -3632,14 +3632,14 @@ createWebMessagePorts(): Array\<WebMessagePort\>
postMessage(options: { message: WebMessageEvent, uri: string}): void postMessage(options: { message: WebMessageEvent, uri: string}): void
发送Web息端口到HTML5。 发送Web息端口到HTML5。
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| ---------- | --------------- | ---- | ---- | ------------------------- | | ---------- | --------------- | ---- | ---- | ------------------------- |
| message | [WebMessageEvent](#webmessageevent9) | 是 | - |要发送的信息,包含数据和信息端口 。 | | message | [WebMessageEvent](#webmessageevent9) | 是 | - |要发送的消息,包含数据和消息端口。 |
| uri | string | 是 | - | 接收该息的URI。 | | uri | string | 是 | - | 接收该息的URI。 |
**示例:** **示例:**
...@@ -5361,7 +5361,7 @@ storeWebArchive(baseName: string, autoName: boolean): Promise<string> ...@@ -5361,7 +5361,7 @@ storeWebArchive(baseName: string, autoName: boolean): Promise<string>
### close<sup>9+</sup> ### close<sup>9+</sup>
close(): void close(): void
关闭该息端口。 关闭该息端口。
### postMessageEvent<sup>9+</sup> ### postMessageEvent<sup>9+</sup>
postMessageEvent(message: WebMessageEvent): void postMessageEvent(message: WebMessageEvent): void
......
...@@ -38,7 +38,7 @@ AlphabetIndexer(value: {arrayValue: Array&lt;string&gt;, selected: number}) ...@@ -38,7 +38,7 @@ AlphabetIndexer(value: {arrayValue: Array&lt;string&gt;, selected: number})
| selectedFont | [Font](ts-types.md#font) | 设置选中项文字样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} | | selectedFont | [Font](ts-types.md#font) | 设置选中项文字样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} |
| popupFont | [Font](ts-types.md#font) | 设置提示弹窗字体样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} | | popupFont | [Font](ts-types.md#font) | 设置提示弹窗字体样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} |
| font | [Font](ts-types.md#font) | 设置字母索引条默认字体样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} | | font | [Font](ts-types.md#font) | 设置字母索引条默认字体样式。<br/>默认值:<br/>{<br/>fontSize:10,<br/> fontStyle:FontStyle.Normal,<br/> fontWeight:FontWeight.Normal,<br/> fontFamily:HarmonyOS Sans<br/>} |
| itemSize | string&nbsp;\|&nbsp;number | 设置字母索引条字母区域大小,字母区域为正方形,即正方形边长。<br/>默认值:24.0。 | | itemSize | string&nbsp;\|&nbsp;number | 设置字母索引条字母区域大小,字母区域为正方形,即正方形边长。不支持设置为百分比。<br/>默认值:24.0。 |
| alignStyle | IndexerAlign | 设置字母索引条弹框的对齐样式,支持弹窗显示在索引条右侧和左侧。<br/>默认值:IndexerAlign.Right。 | | alignStyle | IndexerAlign | 设置字母索引条弹框的对齐样式,支持弹窗显示在索引条右侧和左侧。<br/>默认值:IndexerAlign.Right。 |
| selected | number | 设置选中项索引值。<br/>默认值:0。 | | selected | number | 设置选中项索引值。<br/>默认值:0。 |
| popupPosition | [Position](ts-types.md#position8) | 设置弹出窗口相对于索引器条上边框中点的位置。<br/>默认值:{x:96.0, y:48.0}。 | | popupPosition | [Position](ts-types.md#position8) | 设置弹出窗口相对于索引器条上边框中点的位置。<br/>默认值:{x:96.0, y:48.0}。 |
......
...@@ -70,7 +70,7 @@ struct PanelExample { ...@@ -70,7 +70,7 @@ struct PanelExample {
@State show: boolean = false @State show: boolean = false
build() { build() {
Stack() { Column() {
Text('2021-09-30 Today Calendar: 1.afternoon......Click for details') Text('2021-09-30 Today Calendar: 1.afternoon......Click for details')
.width('90%').height(50).borderRadius(10) .width('90%').height(50).borderRadius(10)
.backgroundColor(0xFFFFFF).padding({ left: 20 }) .backgroundColor(0xFFFFFF).padding({ left: 20 })
......
...@@ -91,7 +91,7 @@ Invalid string length of the event parameter. ...@@ -91,7 +91,7 @@ Invalid string length of the event parameter.
**错误描述** **错误描述**
在调用write接口进行应用事件打点时,由于事件参数值传入了超长的字符串,超出长度的字符将被丢弃 在调用write接口进行应用事件打点时,由于事件参数值传入了超长的字符串,系统将忽略相关事件参数
**可能原因** **可能原因**
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
**错误信息** **错误信息**
``${messageInfo}`` mode is not support in current device. The ``${messageInfo}`` is not supported.
**可能原因** **可能原因**
支持API,但是不支持API内部某些子特性(功能),如算法参数。 支持API,但是不支持API内部某些子特性(功能),如算法参数。
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
## 12000002 缺少密钥算法参数 ## 12000002 缺少密钥算法参数
**错误信息** **错误信息**
Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param set. Failed to obtain the ``${messageInfo}``. It is not set in ParamSet.
**可能原因** **可能原因**
...@@ -31,7 +31,7 @@ Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param ...@@ -31,7 +31,7 @@ Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param
**错误信息** **错误信息**
``${messageInfo}`` argument is invalid. User should make sure using the correct value. Invalid ``${messageInfo}``.
**可能原因** **可能原因**
...@@ -46,7 +46,12 @@ Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param ...@@ -46,7 +46,12 @@ Check get ``${messageInfo}`` failed. User should add ``${messageInfo}`` in param
**错误信息** **错误信息**
Read file failed. or Write file failed. 可能为以下的其中一种:
- Insufficient storage space.
- Invalid file size.
- Failed to ``${messageInfo}``.
**可能原因** **可能原因**
...@@ -61,7 +66,10 @@ Read file failed. or Write file failed. ...@@ -61,7 +66,10 @@ Read file failed. or Write file failed.
**错误信息** **错误信息**
IPC communication timeout. or Receive message from IPC failed. 可能为以下的其中一种:
- Failed to get messages from IPC.
- IPC ``${messageInfo}``.
**可能原因** **可能原因**
...@@ -75,7 +83,7 @@ IPC communication timeout. or Receive message from IPC failed. ...@@ -75,7 +83,7 @@ IPC communication timeout. or Receive message from IPC failed.
**错误信息** **错误信息**
Error occured in crypto engine. Crypto engine error.
**可能原因** **可能原因**
...@@ -93,7 +101,7 @@ Error occured in crypto engine. ...@@ -93,7 +101,7 @@ Error occured in crypto engine.
**错误信息** **错误信息**
This credential is already invalidated permanently. This credential is invalidated permanently.
**可能原因** **可能原因**
...@@ -111,7 +119,7 @@ This credential is already invalidated permanently. ...@@ -111,7 +119,7 @@ This credential is already invalidated permanently.
**错误信息** **错误信息**
Verify authtoken failed. The authentication token verification failed.
**可能原因** **可能原因**
...@@ -126,7 +134,7 @@ Verify authtoken failed. ...@@ -126,7 +134,7 @@ Verify authtoken failed.
**错误信息** **错误信息**
This authtoken is already timeout. This authentication token timed out.
**可能原因** **可能原因**
...@@ -140,7 +148,7 @@ This authtoken is already timeout. ...@@ -140,7 +148,7 @@ This authtoken is already timeout.
**错误信息** **错误信息**
The number of session has reached limit. The number of key operation sessions has reached the limit.
**可能原因** **可能原因**
...@@ -155,7 +163,7 @@ The number of session has reached limit. ...@@ -155,7 +163,7 @@ The number of session has reached limit.
**错误信息** **错误信息**
Queried entity does not exist. The entity does not exist.
**可能原因** **可能原因**
...@@ -170,7 +178,7 @@ Queried entity does not exist. ...@@ -170,7 +178,7 @@ Queried entity does not exist.
**错误信息** **错误信息**
External error ``${messageInfo}``. System external error.
**可能原因** **可能原因**
...@@ -184,7 +192,7 @@ External error ``${messageInfo}``. ...@@ -184,7 +192,7 @@ External error ``${messageInfo}``.
**错误信息** **错误信息**
Queried credential does not exist. The credential does not exist.
**可能原因** **可能原因**
...@@ -198,7 +206,11 @@ Queried credential does not exist. ...@@ -198,7 +206,11 @@ Queried credential does not exist.
**错误信息** **错误信息**
Memory is insufficient. 可能为以下的其中一种:
- Insufficient memory.
- Malloc failed.
**可能原因** **可能原因**
...@@ -212,7 +224,7 @@ Memory is insufficient. ...@@ -212,7 +224,7 @@ Memory is insufficient.
**错误信息** **错误信息**
Call ``${messageInfo}`` service to do ``${messageInfo}`` failed. Failed to obtain the ``${messageInfo}`` information via UserIAM.
**可能原因** **可能原因**
......
...@@ -22,8 +22,7 @@ ...@@ -22,8 +22,7 @@
- [弹性布局](ui-ts-layout-flex.md) - [弹性布局](ui-ts-layout-flex.md)
- [网格布局](ui-ts-layout-grid.md) - [网格布局](ui-ts-layout-grid.md)
- 响应式布局 - 响应式布局
- [栅格布局(新)](ui-ts-layout-grid-container-new.md) - [栅格布局](ui-ts-layout-grid-container-new.md)
- [栅格布局](ui-ts-layout-grid-container.md)
- [媒体查询](ui-ts-layout-mediaquery.md) - [媒体查询](ui-ts-layout-mediaquery.md)
- [自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md) - [自定义组件的生命周期](ui-ts-custom-component-lifecycle-callbacks.md)
- [Web组件开发指导](ui-ts-components-web.md) - [Web组件开发指导](ui-ts-components-web.md)
......
# 栅格布局 # 栅格布局
栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)[GridCol](../reference/arkui-ts/ts-container-gridcol.md) 栅格系统作为一种辅助布局的定位工具,在平面设计和网站设计都起到了很好的作用,对移动设备的界面设计有较好的借鉴作用。总结栅格系统对于移动设备的优势主要有:
相对于[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)提供了更灵活、更全面的栅格系统实现方案。GridRow为栅格容器组件,只与栅格子组件GridCol在栅格布局场景中使用。
1. 给布局提供一种可循的规律,解决多尺寸多设备的动态布局问题。
2. 给系统提供一种统一的定位标注,保证各模块各设备的布局一致性。
3. 给应用提供一种灵活的间距调整方法,满足特殊场景布局调整的可能性。
推荐使用栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)[GridCol](../reference/arkui-ts/ts-container-gridcol.md)来实现栅格布局效果,
相对于目前已废弃的[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)组件,GridRow和GridCol提供了更灵活、更全面的栅格系统实现方案。GridRow为栅格容器组件,只能与栅格子组件GridCol在栅格布局场景中使用。
## 栅格容器GridRow ## 栅格容器GridRow
...@@ -18,8 +24,8 @@ ...@@ -18,8 +24,8 @@
### 栅格系统断点 ### 栅格系统断点
断点以设备宽度为基准,将应用宽度分成了几个不同的区间,即不同的断点。开发者根据需求在不同的区间实现不同的页面布局效果。 栅格系统以设备的水平宽度(屏幕密度像素值,单位vp)作为断点依据,定义设备的宽度类型,形成了一套断点规则。开发者可根据需求在不同的断点区间实现不同的页面布局效果。
[栅格系统默认断点](ui-ts-layout-grid-container.md#系统栅格断点)将设备宽度分为xs、sm、md、lg四类,尺寸范围如下: 栅格系统默认断点将设备宽度分为xs、sm、md、lg四类,尺寸范围如下:
| 断点名称 | 取值范围(vp)| | 断点名称 | 取值范围(vp)|
| --------| ------ | | --------| ------ |
......
# 栅格布局
栅格系统作为一种辅助布局的定位工具,在平面设计和网站设计都起到了很好的作用,对移动设备的界面设计有较好的借鉴作用。总结栅格系统对于移动设备的优势主要有:
1. 给布局提供一种可循的规律,解决多尺寸多设备的动态布局问题。
2. 给系统提供一种统一的定位标注,保证各模块各设备的布局一致性。
3. 给应用提供一种灵活的间距调整方法,满足特殊场景布局调整的可能性。
为实现栅格布局效果,声明式范式提供了[GridContainer](../reference/arkui-ts/ts-container-gridcontainer.md)栅格容器组件,配合其子组件的通用属性[useSizeType](../reference/arkui-ts/ts-container-grid.md)来实现栅格布局。
## 栅格系统
栅格系统有Column、Margin、Gutter三个概念。
![zh-cn_image_0000001224173302](figures/zh-cn_image_0000001224173302.png)
1. Gutter:
元素之间的距离,决定了内容间的紧密程度。作为栅格布局的统一规范。为了保证较好的视觉效果,通常gutter的取值不会大于margin的取值。
2. Margin:
内容距栅格容器边缘的距离,决定了内容可展示的总宽度。作为栅格布局的统一规范。
3. Column:
栅格布局的主要定位工具。根据设备的不同尺寸,把栅格容器分割成不同的列数,在保证margin和gutter符合规范的情况下,根据总Column的个数计算每个Column列的宽度。
### 系统栅格断点
栅格系统以设备的水平宽度(屏幕密度像素值,vp)作为断点依据,定义设备的宽度类型,设置栅格总列数,间隔,边距,形成了一套断点规则。
不同设备水平宽度下,栅格系统默认总列数(columns),边距(margin),间隔(gutter)定义如下:
| 设备水平宽度断点范围 | 设备宽度类型 | 描述 | columns | gutter | margin |
| ----------------------- | ------ | --------- | ------- | ------ | ------ |
| 0&lt; 水平宽度&lt; 320vp | XS | 最小宽度类型设备。 | 2 | 12vp | 12vp |
| 320vp&lt; =水平宽度&lt; 600vp | SM | 小宽度类型设备。 | 4 | 24vp | 24vp |
| 600vp&lt; =水平宽度&lt; 840vp | MD | 中等宽度类型设备。 | 8 | 24vp | 32vp |
| 840&lt; =水平分辨率 | LG | 大宽度类型设备。 | 12 | 24vp | 48vp |
> **说明:**
>
> ArkUI在API9对栅格组件做了重构,推出新的栅格组件[GridRow](../reference/arkui-ts/ts-container-gridrow.md)和[GridCol](../reference/arkui-ts/ts-container-gridcol.md),API9推荐使用新的栅格组件,参考[新栅格组件用法](ui-ts-layout-grid-container-new.md)
>
## GridContainer栅格组件使用
首先使用栅格容器组件创建栅格布局。
### 栅格容器创建与设置
通过接口 `GridContainer(options?: { columns?: number | 'auto', sizeType?: SizeType, gutter?: Length, margin?: Length})` 创建栅格容器,栅格容器内的所有子组件可以使用栅格布局。
通过参数定义栅格布局的总列数(columns),间隔(gutter),两侧边距(margin)。例如栅格容器总共分为6列,列与列间隔为10vp, 两侧边距为20vp:
```ts
GridContainer({ columns: 6, gutter: 10, margin: 20 }) {}
```
栅格容器不设置参数,或者sizeType设置为SizeType. Auto时使用默认的栅格系统定义,如:
```ts
GridContainer() {}
```
```ts
GridContainer({ sizeType: SizeType.Auto })
```
上述例子中,默认在小宽度类型设备(SizeType. SM)上,栅格容器被分为4列,列与列的间隔为24vp, 两侧边距是24vp。在中等宽度类型设备(SizeType. MD)上,栅格容器被分为8列,列与列的间隔为24vp,两侧边距是32vp。
也可以通过参数sizeType指定此栅格容器内的组件使用此设备宽度类型的栅格设置,如:
```ts
GridContainer({ sizeType: SizeType.SM }) {
Row() {
Text('1')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 3, offset: 0 },
md: { span: 6, offset: 2 },
lg: { span: 8, offset: 2 },
})
}
}
```
上述例子中,不管在任何宽度类型的设备上, Text组件都使用SizeType. SM类型的栅格设置, 即占用3列,放置在第1列。
### 子组件的栅格设置
栅格容器中的组件使用通用属性useSizeType设置不同的设备宽度类型的占用列数和列偏移。其中span表示栅格容器组件占据columns的数量;offset表示列偏移量,指将组件放置在哪一个columns上。 如:
```ts
GridContainer() {
Row() {
Text('1')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 2, offset: 0 },
md: { span: 6, offset: 2 },
lg: { span: 8, offset: 2 },
})
}
}
```
其中 `sm: { span: 2, offset: 0 } ` 指在设备宽度类型为SM的设备上,Text组件占用2列,且放在栅格容器的第1列上。
![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108719.png)
## 场景示例
使用栅格布局可以灵活地在不同的设备宽度类型下呈现合适的效果,不必写大量的代码兼容不同宽度类型的设备。
```ts
@Entry
@Component
struct GridContainerExample {
build() {
Column({ space: 5 }) {
GridContainer({ columns: 6 }) {
Flex({justifyContent:FlexAlign.SpaceAround}) {
Text('1')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 2, offset: 0 },
md: { span: 1, offset: 0 },
lg: { span: 1, offset: 0 },
})
.height(100).backgroundColor(0x4682B4).textAlign(TextAlign.Center)
Text('2')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 2, offset: 0 },
md: { span: 4, offset: 0 },
lg: { span: 4, offset: 0 },
})
.height(100).backgroundColor(0x46F2B4).textAlign(TextAlign.Center)
Text('3')
.useSizeType({
xs: { span: 2, offset: 0 },
sm: { span: 2, offset: 0 },
md: { span: 1, offset: 0 },
lg: { span: 1, offset: 0 },
})
.height(100).backgroundColor(0x46A2B4).textAlign(TextAlign.Center)
}
}.width('80%').backgroundColor('gray')
}.width('100%').margin({ top: 15 })
}
}
```
小宽度类型设备(SizeType. SM)运行效果:
![zh-cn_image_0000001218108718](figures/zh-cn_image_0000001218108718.png)
中等宽度类型设备(SizeType. MD)运行效果:
![zh-cn_image_0000001262748569](figures/zh-cn_image_0000001262748569.png)
...@@ -374,16 +374,13 @@ class MainAbility extends Ability { ...@@ -374,16 +374,13 @@ class MainAbility extends Ability {
console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data));
}); });
}); });
//5.销毁悬浮窗。当不再需要悬浮窗时,可根据具体实现逻辑,使用destroy对其进行销毁,此处以监听窗口区域外的点击事件为例实现悬浮窗的销毁。 //5.销毁悬浮窗。当不再需要悬浮窗时,可根据具体实现逻辑,使用destroy对其进行销毁。
windowClass.on('touchOutside', () => { windowClass.destroy((err, data) => {
console.info('touch outside'); if (err.code) {
windowClass.destroy((err, data) => { console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err));
if (err.code) { return;
console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); }
return; console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data));
}
console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data));
});
}); });
}); });
} }
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## 概述 ## 概述
### 功能简介 ### 功能简介
OpenHarmony Codec HDI驱动框架基于OpenMax实现了视频硬件编解码驱动,提供Codec基础能力接口给上层媒体服务调用,包括获取组件编解码能力、创建组件、参数设置、数据的轮转和控制、以及销毁组件等功能,实现对视频数据的编解码处理(可以将YUV/RGB等格式的视频数据编码成H264/H265等编码格式,也可以将H264/H265等裸流数据解码成YUV/RGB等格式数据)。本文主要介绍基于HDF驱动框架开发的Codec编解码功能。 OpenHarmony Codec HDI(Hardware Device Interface)驱动框架基于OpenMax实现了视频硬件编解码驱动,提供Codec基础能力接口给上层媒体服务调用,包括获取组件编解码能力、创建组件、参数设置、数据的轮转和控制、以及销毁组件等功能,实现对视频数据的编解码处理(可以将YUV/RGB等格式的视频数据编码成H264/H265等编码格式,也可以将H264/H265等裸流数据解码成YUV/RGB等格式数据)。本文主要介绍基于HDF(Hardware Driver Foundation)驱动框架开发的Codec编解码功能。
Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成: Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成:
...@@ -16,7 +16,7 @@ Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成 ...@@ -16,7 +16,7 @@ Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成
- Codec HDI Adapter:HDI 实现层,实现了HDI Interface接口,并与OpenMax IL 对接。 - Codec HDI Adapter:HDI 实现层,实现了HDI Interface接口,并与OpenMax IL 对接。
- OpenMax IL Interface:OpenMax IL接口,Codec HDI驱动直接对接OpenMax IL层。 - OpenMax IL Interface:OpenMax IL接口,Codec HDI驱动直接对接OpenMax IL层。
- Vendor Impl:厂商适配层,各大厂商适配的OpenMax 实现层。 - Vendor Impl:厂商适配层,各大厂商适配的OpenMax 实现层。
- Codec HardWare:硬件解码设备。 - Codec Hardware:硬件解码设备。
### 基本概念 ### 基本概念
在进行开发前,开发者应了解一下基本概念: 在进行开发前,开发者应了解一下基本概念:
...@@ -35,7 +35,7 @@ Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成 ...@@ -35,7 +35,7 @@ Codec HDI驱动框架基于HDF驱动框架实现。Codec HDI驱动架构组成
- 码率 - 码率
视频的码率是指在单位时间内传输的视频数据数量,一般用kbps作为单位。码率越高,视频就越清晰,反之则画面粗糙而多马赛克。 视频的码率是指在单位时间内传输的视频数据数量,一般用kbps作为单位。码率越高,视频就越清晰,反之则画面粗糙而多马赛克。
- 组件 - 组件
...@@ -59,7 +59,7 @@ Codec模块主要完成对视频数据的硬件编解码,将H264等裸流数 ...@@ -59,7 +59,7 @@ Codec模块主要完成对视频数据的硬件编解码,将H264等裸流数
| 接口名称 | 功能描述 | | 接口名称 | 功能描述 |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------| | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------|
| int32_t (*CreateComponent)(struct CodecComponentType **component, uint32_t *componentId, char *compName, int64_t appData, struct CodecCallbackType *callbacks) | 创建Codec组件实例 | | int32_t (*CreateComponent)(struct CodecComponentType **component, uint32_t *componentId, char *compName, int64_t appData, struct CodecCallbackType *callbacks) | 创建Codec组件实例 |
| int32_t (*DestroyComponent)(uint32_t componentId) | 销毁组件实例 | | int32_t (*DestroyComponent)(uint32_t componentId) | 销毁Codec组件实例 |
- codec_component _if.h - codec_component _if.h
...@@ -133,7 +133,7 @@ HDF_INIT(g_codecComponentDriverEntry); // 将Codec HDI的HdfDriverEntry结构体 ...@@ -133,7 +133,7 @@ HDF_INIT(g_codecComponentDriverEntry); // 将Codec HDI的HdfDriverEntry结构体
} }
``` ```
- HdfCodecComponentTypeDriverInit:加载HCS中的属性配置。 - HdfCodecComponentTypeDriverInit:加载HCS(HDF Configuration Source)中的属性配置。
```c ```c
int32_t HdfCodecComponentTypeDriverInit(struct HdfDeviceObject *deviceObject) int32_t HdfCodecComponentTypeDriverInit(struct HdfDeviceObject *deviceObject)
...@@ -172,7 +172,7 @@ HCS配置包括两部分: ...@@ -172,7 +172,7 @@ HCS配置包括两部分:
HCS配置内容包括:驱动节点、加载顺序、服务名称等。HCS语法可参考[配置管理](driver-hdf-manage.md) HCS配置内容包括:驱动节点、加载顺序、服务名称等。HCS语法可参考[配置管理](driver-hdf-manage.md)
标准系统配置文件路径(其它系统暂不涉及): 以RK3568开发板为例,标准系统配置文件路径(其它系统暂不涉及):
vendor/hihope/rk3568/hdf_config/uhdf/ vendor/hihope/rk3568/hdf_config/uhdf/
1. device相关配置 1. device相关配置
...@@ -392,22 +392,22 @@ bool CodecHdiDecode::UseBufferOnPort(enum PortIndex portIndex) ...@@ -392,22 +392,22 @@ bool CodecHdiDecode::UseBufferOnPort(enum PortIndex portIndex)
auto err = client_->GetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)&param, sizeof(param)); auto err = client_->GetParameter(client_, OMX_IndexParamPortDefinition, (int8_t *)&param, sizeof(param));
if (err != HDF_SUCCESS) { if (err != HDF_SUCCESS) {
HDF_LOGE("%{public}s failed to GetParameter with OMX_IndexParamPortDefinition : portIndex[%{public}d]", HDF_LOGE("%{public}s failed to GetParameter with OMX_IndexParamPortDefinition : portIndex[%{public}d]",
__func__, portIndex); __func__, portIndex);
return false; return false;
} }
bufferSize = param.nBufferSize; bufferSize = param.nBufferSize;
bufferCount = param.nBufferCountActual; bufferCount = param.nBufferCountActual;
bPortEnable = param.bEnabled; bPortEnable = param.bEnabled;
HDF_LOGI("buffer index [%{public}d], buffer size [%{public}d], " HDF_LOGI("buffer index [%{public}d], buffer size [%{public}d], "
"buffer count [%{public}d], portEnable[%{public}d], err [%{public}d]", "buffer count [%{public}d], portEnable[%{public}d], err [%{public}d]",
portIndex, bufferSize, bufferCount, bPortEnable, err); portIndex, bufferSize, bufferCount, bPortEnable, err);
{ {
OMX_PARAM_BUFFERSUPPLIERTYPE param; OMX_PARAM_BUFFERSUPPLIERTYPE param;
InitParam(param); InitParam(param);
param.nPortIndex = (uint32_t)portIndex; param.nPortIndex = (uint32_t)portIndex;
auto err = client_->GetParameter(client_, OMX_IndexParamCompBufferSupplier, (int8_t *)&param, sizeof(param)); auto err = client_->GetParameter(client_, OMX_IndexParamCompBufferSupplier, (int8_t *)&param, sizeof(param));
HDF_LOGI("param.eBufferSupplier[%{public}d] isSupply [%{public}d], err [%{public}d]", param.eBufferSupplier, HDF_LOGI("param.eBufferSupplier[%{public}d] isSupply [%{public}d], err [%{public}d]", param.eBufferSupplier,
this->isSupply_, err); this->isSupply_, err);
} }
// 设置端口buffer // 设置端口buffer
UseBufferOnPort(portIndex, bufferCount, bufferSize); UseBufferOnPort(portIndex, bufferCount, bufferSize);
...@@ -536,7 +536,7 @@ while (!this->exit_) { ...@@ -536,7 +536,7 @@ while (!this->exit_) {
client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateIdle, NULL, 0); client_->SendCommand(client_, OMX_CommandStateSet, OMX_StateIdle, NULL, 0);
``` ```
对rk OMX解码时,不支持数据的分帧,所以需要手动分帧,目前简单实现按照起始码0x000001或0x00000001分帧发送到服务端处理。分帧代码如下: 当在rk开发板上进行解码时,由于其OMX的实现不支持数据的分帧,所以需要手动分帧,目前简单实现按照起始码0x000001或0x00000001分帧发送到服务端处理。分帧代码如下:
```cpp ```cpp
// 文件分帧读取实现 // 文件分帧读取实现
...@@ -646,8 +646,7 @@ int32_t OMXCore::onFillBufferDone(struct OmxCodecBuffer* pBuffer) ...@@ -646,8 +646,7 @@ int32_t OMXCore::onFillBufferDone(struct OmxCodecBuffer* pBuffer)
int32_t CodecHdiDecode::OnEvent(struct CodecCallbackType *self, enum OMX_EVENTTYPE event, struct EventInfo *info) int32_t CodecHdiDecode::OnEvent(struct CodecCallbackType *self, enum OMX_EVENTTYPE event, struct EventInfo *info)
{ {
HDF_LOGI("onEvent: appData[0x%{public}p], eEvent [%{public}d], " HDF_LOGI("onEvent: appData[0x%{public}p], eEvent [%{public}d], "
"nData1[%{public}d]", "nData1[%{public}d]", info->appData, event, info->data1);
info->appData, event, info->data1);
switch (event) { switch (event) {
case OMX_EventCmdComplete: { case OMX_EventCmdComplete: {
OMX_COMMANDTYPE cmd = (OMX_COMMANDTYPE)info->data1; OMX_COMMANDTYPE cmd = (OMX_COMMANDTYPE)info->data1;
...@@ -665,7 +664,7 @@ int32_t CodecHdiDecode::OnEvent(struct CodecCallbackType *self, enum OMX_EVENTTY ...@@ -665,7 +664,7 @@ int32_t CodecHdiDecode::OnEvent(struct CodecCallbackType *self, enum OMX_EVENTTY
``` ```
#### 接口去初始化 #### 接口去初始化
组件关闭前,需要将组件状态修改为IDLE,然后开始释放输入输出Buffer,再将组件状态修改为OMX_StateLoaded,最后再调用DestoryComponent去关闭组件。 组件关闭前,需要将组件状态修改为OMX_StateIdle,然后开始释放输入输出Buffer,再将组件状态修改为OMX_StateLoaded,最后再调用DestoryComponent去关闭组件。
##### Buffer释放示例 ##### Buffer释放示例
...@@ -721,7 +720,7 @@ OpenMax不支持分帧。 ...@@ -721,7 +720,7 @@ OpenMax不支持分帧。
**解决办法** **解决办法**
上层在调用EmptyThisBuffer时,需要按照一帧一帧传入。 上层在调用EmptyThisBuffer时,需要按照每次一帧的方式传入。
## 解码过程中全是绿屏 ## 解码过程中全是绿屏
......
...@@ -12,7 +12,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -12,7 +12,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
> 使能ESwap需要在使能ZRAM之前,不需要使用ESwap时, 也可以仅使能ZRAM。如部分设备不包括用于换出的存储设备,也没有新建相应的存储分区,那么可以仅使能ZRAM来通过zswapd进行内存回收。 > 使能ESwap需要在使能ZRAM之前,不需要使用ESwap时, 也可以仅使能ZRAM。如部分设备不包括用于换出的存储设备,也没有新建相应的存储分区,那么可以仅使能ZRAM来通过zswapd进行内存回收。
### 使能ESwap ### 使能ESwap
1. 打开相关配置项及依赖 1. 打开相关配置项及依赖
启用ESwap,需要通过编译内核时打开相应的配置项及依赖,ESwap相关CONFIG如下: 启用ESwap,需要通过编译内核时打开相应的配置项及依赖,ESwap相关CONFIG如下:
...@@ -31,13 +31,13 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -31,13 +31,13 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
同时,开启ESwap需依赖以下CONFIG: 同时,开启ESwap需依赖以下CONFIG:
``` ```
CONFIG_MEMCG=y CONFIG_MEMCG=y // Enable Memory controller
CONFIG_SWAP=y CONFIG_SWAP=y // Enable Support for paging of anonymous memory (swap)
CONFIG_ZSMALLOC=y CONFIG_ZSMALLOC=y // Enable Memory allocator for compressed pages
CONFIG_ZRAM=y CONFIG_ZRAM=y // Enable Compressed RAM block device support
``` ```
2. 创建ESwap设备 2. 创建ESwap设备
可以使用任意block设备作为ESwap交换设备,这里创建一个文件hpdisk挂载为loop6设备: 可以使用任意block设备作为ESwap交换设备,这里创建一个文件hpdisk挂载为loop6设备:
...@@ -48,7 +48,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -48,7 +48,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
losetup /dev/block/loop6 hpdisk losetup /dev/block/loop6 hpdisk
``` ```
3. 配置ESwap 3. 配置ESwap
将2中创建的设备绑定为ESwap换出设备: 将2中创建的设备绑定为ESwap换出设备:
...@@ -59,14 +59,14 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -59,14 +59,14 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
ESwap默认对换出数据使用软件加密,如果2中创建的ESwap设备支持inline加密,可以关闭ESwap的软件加密功能: ESwap默认对换出数据使用软件加密,如果2中创建的ESwap设备支持inline加密,可以关闭ESwap的软件加密功能:
```Bash ```Bash
// 需确认是否支持并开启硬加密,否则不要执行该操作。 // 需咨询开发板厂商是否支持并开启硬加密,否则不要执行该操作。
echo 0 > /proc/sys/kernel/hyperhold/soft_crypt echo 0 > /proc/sys/kernel/hyperhold/soft_crypt
``` ```
> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:** > ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
> 出于安全考虑,所有换出内容均需加密。因此若当前配置ESwap的设备不支持inline加密,或编译时未打开inline加密宏,则在关闭软加密时,ESwap无法enable。 > 出于安全考虑,所有换出内容均需加密。因此若当前配置ESwap的设备不支持inline加密,或编译时未打开inline加密宏,则在关闭软加密时,ESwap无法enable。
4. 使能ESwap 4. 使能ESwap
使能ESwap,使能后无法更改上述配置: 使能ESwap,使能后无法更改上述配置:
...@@ -77,7 +77,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -77,7 +77,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
### 使能ZRAM ### 使能ZRAM
1. 初始化ZRAM 1. 初始化ZRAM
设置ZRAM与ESwap的交互方式,并配置ZRAM的大小。 设置ZRAM与ESwap的交互方式,并配置ZRAM的大小。
...@@ -95,7 +95,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -95,7 +95,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
> - readonly:表示只记录数据的cgroup信息,并不换出; > - readonly:表示只记录数据的cgroup信息,并不换出;
> - readwrite:表示打开ZRAM到eswap的换入换出功能。 > - readwrite:表示打开ZRAM到eswap的换入换出功能。
2. 使能ZRAM 2. 使能ZRAM
启用ZRAM设备为交换分区并将其使能。 启用ZRAM设备为交换分区并将其使能。
...@@ -107,7 +107,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -107,7 +107,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
### 关闭ESwap与ZRAM ### 关闭ESwap与ZRAM
1. 关闭ESwap 1. 关闭ESwap
```Bash ```Bash
echo disable > /proc/sys/kernel/hyperhold/enable echo disable > /proc/sys/kernel/hyperhold/enable
...@@ -121,7 +121,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区 ...@@ -121,7 +121,7 @@ ESwap(Enhanced Swap)提供了自定义新增存储分区作为内存交换分区
> - disable:表示如果ESwap中没有数据,则完全关闭,否则变为只读模式; > - disable:表示如果ESwap中没有数据,则完全关闭,否则变为只读模式;
> - force_disable:表示如果没有数据,完全关闭,否则变为只读模式,并同步等待ESwap中数据完全读出,然后完全关闭。 > - force_disable:表示如果没有数据,完全关闭,否则变为只读模式,并同步等待ESwap中数据完全读出,然后完全关闭。
2. 关闭ZRAM及ZRAM group 2. 关闭ZRAM及ZRAM group
```Bash ```Bash
// 若已经执行过swapon,则需先执行swapoff // 若已经执行过swapon,则需先执行swapoff
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册