“995cfb3882f7bff15f7803cc2061e1d562a4c2dd”上不存在“en/application-dev/ui/js-framework-js-file.md”
提交 c1a1bfc8 编写于 作者: S shawn_he 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into 19576-d

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
...@@ -19,6 +19,8 @@ ...@@ -19,6 +19,8 @@
- master:最新开发版本。 - master:最新开发版本。
- OpenHarmony 3.2 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-release.md)了解版本详情。 - OpenHarmony 3.2 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-release.md)了解版本详情。
该版本已更新至OpenHarmony 3.2.2 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.2.2-release.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
......
# AI
- [Using MindSpore Lite for Model Inference (JS)](mindspore-lite-js-guidelines.md)
# Using MindSpore Lite for Model Inference (JS)
## Scenarios
MindSpore Lite is an AI engine that implements AI model inference for different hardware devices. It has been used in a wide range of fields, such as image classification, target recognition, facial recognition, and character recognition.
This document describes the general development process for implementing MindSpore Lite model inference. For details about how to use native APIs to implement model inference, see [Using MindSpore Lite for Model Inference](../napi/mindspore-lite-guidelines.md).
## Basic Concepts
Before getting started, you need to understand the following basic concepts:
**Tensor**: a special data structure that is similar to arrays and matrices. It is basic data structure used in MindSpore Lite network operations.
**Float16 inference mode**: a mode that uses half-precision inference. Float16 uses 16 bits to represent a number and therefore it is also called half-precision.
## Available APIs
APIs involved in MindSpore Lite model inference are categorized into context APIs, model APIs, and tensor APIs. For more APIs, see [@ohos.ai.mindSporeLite](../reference/apis/js-apis-mindSporeLite.md).
| API | Description |
| ------------------ | ----------------- |
|loadModelFromFile(model: string, options: Context): Promise&lt;Model&gt;|Loads a model from a file.|
|getInputs(): MSTensor[]|Obtains the model input.|
|predict(inputs: MSTensor[]): Promise&lt;MSTensor&gt;|Performs model inference.|
| getData(): ArrayBuffer | Obtains tensor data.|
| setData(inputArray: ArrayBuffer): void | Sets the tensor data.|
## How to Develop
The development process consists of the following main steps:
1. Prepare the required model. You can download the required model directly or obtain the model by using the model conversion tool. The required data is read from the `bin` file.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. This document uses `mnet.caffemodel.ms` as an example.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r2.0/use/downloads.html#1-8-1) to convert it to the `.ms` format.
2. Create a context, and set parameters such as the number of runtime threads and device type.
3. Load the model. In this example, the model is read from the file.
4. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor.
5. Perform inference and print the output. Call the **predict** API to perform model inference.
```js
@State inputName: string = 'mnet_caffemodel_nhwc.bin';
@State T_model_predict: string = 'Test_MSLiteModel_predict'
inputBuffer: any = null;
build() {
Row() {
Column() {
Text(this.T_model_predict)
.focusable(true)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(async () => {
// 1. Prepare for a model.
let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer;
console.log('=========input bin byte length: ' + this.inputBuffer.byteLength)
}).catch(error => {
console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.');
})
// 2. Create a context.
let context: mindSporeLite.Context = {};
context.target = ['cpu'];
context.cpu = {}
context.cpu.threadNum = 1;
context.cpu.threadAffinityMode = 0;
context.cpu.precisionMode = 'enforce_fp32';
// 3. Load the model.
let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms';
let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context);
// 4. Load data.
const modelInputs = msLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer);
// 5. Perform inference and print the output.
console.log('=========MSLITE predict start=====')
msLiteModel.predict(modelInputs).then((modelOutputs) => {
let output0 = new Float32Array(modelOutputs[0].getData());
for (let i = 0; i < output0.length; i++) {
console.log(output0[i].toString());
}
})
console.log('=========MSLITE predict success=====')
})
}
.width('100%')
}
.height('100%')
}
```
## Debugging and Verification
1. Connect to the rk3568 development board on DevEco Studio, click **Run entry**, and compile your own HAP. The following information is displayed:
```shell
Launching com.example.myapptfjs
$ hdc uninstall com.example.myapptfjs
$ hdc install -r "D:\TVOS\JSAPI\MyAppTfjs\entry\build\default\outputs\default\entry-default-signed.hap"
$ hdc shell aa start -a EntryAbility -b com.example.myapptfjs
```
2. Use the hdc tool to connect to the rk3568 development board and push `mnet.caffemodel.ms` to the sandbox directory on the device. `mnet\_caffemodel\_nhwc.bin` is stored in the `rawfile` directory of the local project.
```shell
hdc -t 7001005458323933328a00bcdf423800 file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/
```
3. Click **Test\_MSLiteModel\_predict** on the screen of the rk3568 development board to run the test case. The following information is displayed in the HiLog printing result:
```shell
08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start=====
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.10046602040529252
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.07535600662231445
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.06326554715633392
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: 0.0015114173293113708
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.026745859533548355
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.055590517818927765
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.05325715243816376
08-27 23:25:51.487 31782-31782/? I C03d00/JSAPP: -0.04629542678594589
...
08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.23317644000053404
08-27 23:25:52.881 31782-31782/? I C03d00/JSAPP: 0.17999525368213654
08-27 23:25:50.372 31782-31782/? I C03d00/JSAPP: =========MSLITE predict success=====
```
...@@ -21,7 +21,8 @@ In the following example, two copies of the weather widget are added to the home ...@@ -21,7 +21,8 @@ In the following example, two copies of the weather widget are added to the home
}, },
"colorMode": "auto", "colorMode": "auto",
"isDefault": true, "isDefault": true,
"updateEnabled": true,"scheduledUpdateTime": "07:00", "updateEnabled": true,
"scheduledUpdateTime": "07:00",
"updateDuration": 0, "updateDuration": 0,
"defaultDimension": "2*2", "defaultDimension": "2*2",
"supportDimensions": ["2*2"] "supportDimensions": ["2*2"]
...@@ -103,10 +104,15 @@ In the following example, two copies of the weather widget are added to the home ...@@ -103,10 +104,15 @@ In the following example, two copies of the weather widget are added to the home
let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY]; let isTempCard: boolean = want.parameters[formInfo.FormParam.TEMPORARY_KEY];
if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted. if (isTempCard === false) {// If the widget is a normal one, the widget information is persisted.
console.info('Not temp card, init db for:' + formId); console.info('Not temp card, init db for:' + formId);
let storeDB = dataPreferences.getPreferences(this.context, 'mystore') let promise = dataPreferences.getPreferences(this.context, 'myStore');
storeDB.put('A' + formId, 'false'); promise.then(async (storeDB) => {
storeDB.put('B' + formId, 'false'); console.info("Succeeded to get preferences.");
storeDB.flush(); await storeDB.put('A' + formId, 'false');
await storeDB.put('B' + formId, 'false');
await storeDB.flush();
}).catch((err) => {
console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
})
} }
let formData = {}; let formData = {};
return formBindingData.createFormBindingData(formData); return formBindingData.createFormBindingData(formData);
...@@ -114,54 +120,71 @@ In the following example, two copies of the weather widget are added to the home ...@@ -114,54 +120,71 @@ In the following example, two copies of the weather widget are added to the home
onRemoveForm(formId) { onRemoveForm(formId) {
console.info('onRemoveForm, formId:' + formId); console.info('onRemoveForm, formId:' + formId);
let storeDB = dataPreferences.getPreferences(this.context, 'mystore') let promise = dataPreferences.getPreferences(this.context, 'myStore');
storeDB.delete('A' + formId); promise.then(async (storeDB) => {
storeDB.delete('B' + formId); console.info("Succeeded to get preferences.");
await storeDB.delete('A' + formId);
await storeDB.delete('B' + formId);
}).catch((err) => {
console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
})
} }
// If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one. // If the widget is a temporary one, it is recommended that the widget information be persisted when the widget is converted to a normal one.
onCastToNormalForm(formId) { onCastToNormalForm(formId) {
console.info('onCastToNormalForm, formId:' + formId); console.info('onCastToNormalForm, formId:' + formId);
let storeDB = dataPreferences.getPreferences(this.context, 'myStore') let promise = dataPreferences.getPreferences(this.context, 'myStore');
storeDB.put('A' + formId, 'false'); promise.then(async (storeDB) => {
storeDB.put('B' + formId, 'false'); console.info("Succeeded to get preferences.");
storeDB.flush(); await storeDB.put('A' + formId, 'false');
await storeDB.put('B' + formId, 'false');
await storeDB.flush();
}).catch((err) => {
console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
})
} }
onUpdateForm(formId) { onUpdateForm(formId) {
let storeDB = dataPreferences.getPreferences(this.context, 'myStore') let promise = dataPreferences.getPreferences(this.context, 'myStore');
let stateA = storeDB.get('A' + formId, 'false').toString() promise.then(async (storeDB) => {
let stateB = storeDB.get('B' + formId, 'false').toString() console.info("Succeeded to get preferences.");
// Update textA in state A. let stateA = await storeDB.get('A' + formId, 'false');
if (stateA === 'true') { let stateB = await storeDB.get('B' + formId, 'false');
let formInfo = formBindingData.createFormBindingData({ // Update textA in state A.
'textA': 'AAA' if (stateA === 'true') {
}) let formInfo = formBindingData.createFormBindingData({'textA': 'AAA'});
formProvider.updateForm(formId, formInfo) await formProvider.updateForm(formId, formInfo);
} }
// Update textB in state B. // Update textB in state B.
if (stateB === 'true') { if (stateB === 'true') {
let formInfo = formBindingData.createFormBindingData({ let formInfo = formBindingData.createFormBindingData({'textB': 'BBB'});
'textB': 'BBB' await formProvider.updateForm(formId, formInfo);
}) }
formProvider.updateForm(formId, formInfo) console.info(`Update form success stateA:${stateA} stateB:${stateB}.`);
} }).catch((err) => {
console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
})
} }
onFormEvent(formId, message) { onFormEvent(formId, message) {
// Store the widget state. // Store the widget state.
console.info('onFormEvent formId:' + formId + 'msg:' + message); console.info('onFormEvent formId:' + formId + 'msg:' + message);
let storeDB = dataPreferences.getPreferences(this.context, 'myStore') let promise = dataPreferences.getPreferences(this.context, 'myStore');
let msg = JSON.parse(message) promise.then(async (storeDB) => {
if (msg.selectA != undefined) { console.info("Succeeded to get preferences.");
console.info('onFormEvent selectA info:' + msg.selectA); let msg = JSON.parse(message);
storeDB.put('A' + formId, msg.selectA); if (msg.selectA != undefined) {
} console.info('onFormEvent selectA info:' + msg.selectA);
if (msg.selectB != undefined) { await storeDB.put('A' + formId, msg.selectA);
console.info('onFormEvent selectB info:' + msg.selectB); }
storeDB.put('B' + formId, msg.selectB); if (msg.selectB != undefined) {
} console.info('onFormEvent selectB info:' + msg.selectB);
storeDB.flush(); await storeDB.put('B' + formId, msg.selectB);
}
await storeDB.flush();
}).catch((err) => {
console.info(`Failed to get preferences. ${JSON.stringify(err)}`);
})
} }
}; };
``` ```
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
- [Full SDK Compilation](full-sdk-compile-guide.md) - [Full SDK Compilation](full-sdk-compile-guide.md)
- [Switching to Full SDK](full-sdk-switch-guide.md) - [Switching to Full SDK](full-sdk-switch-guide.md)
- [Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project](howto-migrate-cmake-with-ohosndk.md)
- [Application Model Development](faqs-ability.md) - [Application Model Development](faqs-ability.md)
- ArkUI Development (ArkTS) - ArkUI Development (ArkTS)
- [ArkTS Syntax Usage](faqs-arkui-arkts.md) - [ArkTS Syntax Usage](faqs-arkui-arkts.md)
......
# Using Native APIs (NDK) of the OpenHarmony SDK in a CMake Project
## What Is Native API
For details, see [Native APIs](../reference/native-api-intro.md).
## Downloading the NDK
You download the Native API Development Kit (NDK) by downloading the OHOS SDK, where the NDK is included. To download the OHOS SDK, use any of the following modes:
- (Recommended) Acquire source code from mirrors for an officially released version. For details, see [release notes](../../release-notes/OpenHarmony-v3.2-release.md).
- Download the SDK from the SDK Manager in DevEco Studio.
- Download the SDK from the [daily build](http://ci.openharmony.cn/dailys/dailybuilds), by clicking the download link to the **ohos-sdk-full** component.
![Download from Daily Build](figures/ci_download.png)
## Decompressing the NDK
Place the downloaded NDK in a folder you prefer and decompress it. Below shows the directory structure after decompression.
![SDK Directory Structure](figures/sdk-structure.png)
Configure the Linux environment as follows: (Skip them if the NDK is downloaded from DevEco Studio.)
1. Add the CMake tool that comes with the NDK to the environment variables.
```
# Open the .bashrc file.
vim ~/.bashrc
# Append the custom CMake path to the file. Save the file and exit.
export PATH=~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin:$PATH
# Run the source ~/.bashrc command to make the environment variables take effect.
source ~/.bashrc
```
2. Check the default CMake path.
```
# Run the which cmake command.
which cmake
# The result should be the same as the custom path previously appended to the file.
~/ohos-sdk/ohos-sdk/linux/native/build-tools/cmake/bin/cmake
```
## Using the NDK to Compile a Native Program
You can use the NDK to quickly develop a native program, including native dynamic libraries, static libraries, and executable files. The ArkUI application framework can call the native dynamic libraries through the NAPI framework. The following exemplifies how to use the NDK to compile a C/C++ dynamic library in a C/C++ demo project.
### Folders in the NDK
#### build Folder: ohos.toolchain.cmake file
The **ohos.toolchain.cmake** file contains the attributes of the CMake compilation target. Its path must be specified in the **CMAKE_TOOLCHAIN_FILE** parameter so that it can be located during CMake compilation. For details about the mandatory parameters in the **ohos.toolchain.cmake** file, see [Key Parameters in ohos.toolchain.cmake](#key-parameters-in-ohostoolchaincmake).
#### build-tools folder: Build Tool Provided by the NDK
```
# Run the following command to view the CMake version:
cmake -version
# Result
cmake version 3.16.5
CMake suite maintained and supported by Kitware (kitware.com/cmake).
```
#### llvm Folder: Compiler Provided by the NDK
![](figures/images.png)
### Demo Project for the NDK
#### Demo Project Directory
```
demo
├── CMakeLists.txt
├── include
└── sum.h
└── src
├── CMakeLists.txt
├── sum.cpp
└── hello.cpp
```
#### CMakeLists.txt in the demo Directory
```
# Specify the minimum CMake version.
CMAKE_MINIMUM_REQUIRED(VERSION 3.16)
# Set the project name, which is HELLO in this example.
PROJECT(HELLO)
# Add a subdirectory and build the subdirectory.
ADD_SUBDIRECTORY(src bin)
```
#### CMakeLists.txt in the src Directory
```
SET(LIBHELLO_SRC hello.cpp)
# Set compilation flags.
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")
# Set the link parameter. The value below is only for exemplary purposes.
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--emit-relocs --verbose")
# Add a libsum dynamic library target. If the compilation is successful, a libsum.so file is generated.
ADD_LIBRARY(sum SHARED sum.cpp)
# Add the executable target called Hello. If the compilation is successful, a Hello executable is generated.
ADD_EXECUTABLE(Hello ${LIBHELLO_SRC})
# Specify the path to the include directory of the Hello target.
TARGET_INCLUDE_DIRECTORIES(Hello PUBLIC ../include)
# Specify the name of the library to be linked to the Hello target.
TARGET_LINK_LIBRARIES(Hello PUBLIC sum)
```
For details about CMake, see [CMake Tutorial](https://cmake.org/cmake/help/v3.16/guide/tutorial/).
#### Source Code
**hello.cpp** source code:
```
#include <iostream>
#include "sum.h"
int main(int argc,const char **argv)
{
std::cout<< "hello world!" <<std::endl;
int total = sum(1, 100);
std::cout<< "Sum 1 + 100=" << total << std::endl;
return 0;
}
```
**sum.h** source code:
```
int sum(int a, int b);
```
**sum.cpp** source code:
```
#include <iostream>
int sum(int a, int b)
{
return a + b;
}
```
### Key Parameters in ohos.toolchain.cmake
| Parameter | Type|Description|
|--------|------|------|
|OHOS_STL|c++\_shared/c++\_static|STL to use. The value must be consistent across the native libraries in the same application.<br>**c++\_shared** (default): The shared library of libc++, libc++\_shared.so, is used.<br>**c++\_static**: The static library of libc++, libc++\_static.a, is used.|
|OHOS_ARCH|armeabi-v7a/arm64-v8a/x86_64|ABI to support. Currently, three types of ABI are supported.|
|OHOS_PLATFORM|OHOS|Target platform. Currently, only OpenHarmony is supported.|
|CMAKE_TOOLCHAIN_FILE|Toolchain file|CMake toolchain file, that is, the aforementioned **ohos.toolchain.cmake** file.|
### Building from Command Line
In the project directory, create the **build** directory to store the intermediate files generated during CMake building.
> **NOTE**
>
> In the following commands, **ohos-sdk** is the root directory of the downloaded SDK. Replace it with the actual directory.
1. Use **OHOS_STL=c++_shared** for dynamic compilation.
```
>mkdir build && cd build
>cmake -DOHOS_STL=c++_shared -DOHOS_ARCH=armeabi-v7a -DOHOS_PLATFORM=OHOS -DCMAKE_TOOLCHAIN_FILE={ohos-sdk}/linux/native/build/cmake/ohos.toolchain.cmake ..
>cmake --build .
```
2. Use **OHOS_STL=c++_static** for static compilation.
```
>mkdir build && cd build
>cmake -DOHOS_STL=c++_static -DOHOS_ARCH=armeabi-v7a -DOHOS_PLATFORM=OHOS -DCMAKE_TOOLCHAIN_FILE={ohos-sdk}/linux/native/build/cmake/ohos.toolchain.cmake ..
>cmake --build .
```
<!--no_check-->
\ No newline at end of file
...@@ -10,6 +10,7 @@ ...@@ -10,6 +10,7 @@
- [Using AudioRenderer for Audio Playback](using-audiorenderer-for-playback.md) - [Using AudioRenderer for Audio Playback](using-audiorenderer-for-playback.md)
- [Using OpenSL ES for Audio Playback](using-opensl-es-for-playback.md) - [Using OpenSL ES for Audio Playback](using-opensl-es-for-playback.md)
- [Using TonePlayer for Audio Playback (for System Applications Only)](using-toneplayer-for-playback.md) - [Using TonePlayer for Audio Playback (for System Applications Only)](using-toneplayer-for-playback.md)
- [Using OHAudio for Audio Playback](using-ohaudio-for-playback.md)
- [Audio Playback Concurrency Policy](audio-playback-concurrency.md) - [Audio Playback Concurrency Policy](audio-playback-concurrency.md)
- [Volume Management](volume-management.md) - [Volume Management](volume-management.md)
- [Audio Effect Management](audio-effect-management.md) - [Audio Effect Management](audio-effect-management.md)
...@@ -21,6 +22,7 @@ ...@@ -21,6 +22,7 @@
- [Using AVRecorder for Audio Recording](using-avrecorder-for-recording.md) - [Using AVRecorder for Audio Recording](using-avrecorder-for-recording.md)
- [Using AudioCapturer for Audio Recording](using-audiocapturer-for-recording.md) - [Using AudioCapturer for Audio Recording](using-audiocapturer-for-recording.md)
- [Using OpenSL ES for Audio Recording](using-opensl-es-for-recording.md) - [Using OpenSL ES for Audio Recording](using-opensl-es-for-recording.md)
- [Using OHAudio for Audio Recording](using-ohaudio-for-recording.md)
- [Microphone Management](mic-management.md) - [Microphone Management](mic-management.md)
- [Audio Recording Stream Management](audio-recording-stream-management.md) - [Audio Recording Stream Management](audio-recording-stream-management.md)
- [Audio Input Device Management](audio-input-device-management.md) - [Audio Input Device Management](audio-input-device-management.md)
...@@ -29,6 +31,14 @@ ...@@ -29,6 +31,14 @@
- [Developing Audio Call](audio-call-development.md) - [Developing Audio Call](audio-call-development.md)
- [Video Playback](video-playback.md) - [Video Playback](video-playback.md)
- [Video Recording](video-recording.md) - [Video Recording](video-recording.md)
- Audio and Video Codecs
- [Obtaining Supported Codecs](obtain-supported-codecs.md)
- [Audio Encoding](audio-encoding.md)
- [Audio Decoding](audio-decoding.md)
- [Video Encoding](video-encoding.md)
- [Video Decoding](video-decoding.md)
- [Audio/Video Encapsulation](audio-video-encapsulation.md)
- [Audio/Video Decapsulation](audio-video-decapsulation.md)
- AVSession - AVSession
- [AVSession Overview](avsession-overview.md) - [AVSession Overview](avsession-overview.md)
- Local AVSession - Local AVSession
......
# Audio Decoding
You can call the native APIs provided by the **AudioDecoder** module to decode audio, that is, to decode media data into PCM streams.
Currently, the following decoding capabilities are supported:
| Container Specification| Audio Decoding Type |
| -------- | :--------------------------- |
| mp4 | AAC, MPEG (MP3), FLAC, Vorbis|
| m4a | AAC |
| flac | FLAC |
| ogg | Vorbis |
| aac | AAC |
| mp3 | MPEG (MP3) |
**Usage Scenario**
- Audio playback
Decode audio and transmit the data to the speaker for playing.
- Audio rendering
Decode audio and transmit the data to the audio processing module for audio rendering.
- Audio editing
Decode audio and transmit the data for audio editing (for example, adjusting the playback speed of a channel). Audio editing is performed based on PCM streams.
## How to Develop
Read [AudioDecoder](../reference/native-apis/_audio_decoder.md) for the API reference.
Refer to the code snippet below to complete the entire audio decoding process, including creating a decoder, setting decoding parameters (such as the sampling rate, bit rate, and number of audio channels), and starting, refreshing, resetting, and destroying the decoder.
During application development, you must call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur.
For details about the complete code, see [Sample](https://gitee.com/openharmony/multimedia_av_codec/blob/master/test/nativedemo/audio_demo/avcodec_audio_decoder_demo.cpp).
The figure below shows the call relationship of audio decoding.
![Call relationship of audio decoding](figures/audio-decode.png)
1. Create a decoder instance.
```cpp
// Create a decoder by name.
OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_MPEG, false);
const char *name = OH_AVCapability_GetName(capability);
OH_AVCodec *audioDec = OH_AudioDecoder_CreateByName(name);
```
```cpp
// Create a decoder by MIME type.
OH_AVCodec *audioDec = OH_AudioDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_MPEG);
```
```cpp
// Initialize the queues.
class ADecSignal {
public:
std::mutex inMutex_;
std::mutex outMutex_;
std::mutex startMutex_;
std::condition_variable inCond_;
std::condition_variable outCond_;
std::condition_variable startCond_;
std::queue<uint32_t> inQueue_;
std::queue<uint32_t> outQueue_;
std::queue<OH_AVMemory *> inBufferQueue_;
std::queue<OH_AVMemory *> outBufferQueue_;
std::queue<OH_AVCodecBufferAttr> attrQueue_;
};
ADecSignal *signal_;
```
2. Call **OH_AudioDecoder_SetCallback()** to set callback functions.
Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers:
- **OnError**, a callback used to report a codec operation error
- **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, audio channel change
- **OnInputBufferAvailable**, a callback used to report input data required, which means that the decoder is ready for receiving data
- **OnOutputBufferAvailable**, a callback used to report output data generated, which means that decoding is complete
You need to process the callback functions to ensure that the decoder runs properly.
```cpp
// Set the OnError callback function.
static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
{
(void)codec;
(void)errorCode;
(void)userData;
}
// Set the OnOutputFormatChanged callback function.
static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void*userData)
{
(void)codec;
(void)format;
(void)userData;
}
// Set the OnInputBufferAvailable callback function, which is used to send the input stream to the InputBuffer queue.
static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, void *userData)
{
(void)codec;
ADecSignal *signal = static_cast<ADecSignal *>(userData);
unique_lock<mutex> lock(signal->inMutex_);
signal->inQueue_.push(index);
signal->inBufferQueue_.push(data);
signal->inCond_.notify_all();
// The input stream is sent to the InputBuffer queue.
}
// Set the OnOutputBufferAvailable callback function, which is used to send the PCM stream obtained after decoding to the OutputBuffer queue.
static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory*data, OH_AVCodecBufferAttr *attr,
void *userData)
{
(void)codec;
ADecSignal *signal = static_cast<ADecSignal *>(userData);
unique_lock<mutex> lock(signal->outMutex_);
signal->outQueue_.push(index);
signal->outBufferQueue_.push(data);
if (attr) {
signal->attrQueue_.push(*attr);
}
signal->outCond_.notify_all();
// The index of the output buffer is sent to OutputQueue_.
// The decoded data is sent to the OutputBuffer queue.
}
signal_ = new ADecSignal();
OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, OnInputBufferAvailable, &OnOutputBufferAvailable};
// Set the asynchronous callbacks.
int32_t ret = OH_AudioDecoder_SetCallback(audioDec, cb, signal_);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
3. Call **OH_AudioDecoder_Configure()** to configure the decoder.
The following options are mandatory: sampling rate, bit rate, and number of audio channels. The maximum input length is optional.
- For AAC decoding, the parameter that specifies whether the data type is Audio Data Transport Stream (ADTS) must be specified. If this parameter is not specified, the data type is considered as Low Overhead Audio Transport Multiplex (LATM).
- For Vorbis decoding, the ID header and setup header must also be specified.
```cpp
enum AudioFormatType : int32_t {
TYPE_AAC = 0,
TYPE_FLAC = 1,
TYPE_MP3 = 2,
TYPE_VORBIS = 3,
};
// Set the decoding resolution.
int32_t ret;
// (Mandatory) Configure the audio sampling rate.
constexpr uint32_t DEFAULT_SMAPLERATE = 44100;
// (Mandatory) Configure the audio bit rate.
constexpr uint32_t DEFAULT_BITRATE = 32000;
// (Mandatory) Configure the number of audio channels.
constexpr uint32_t DEFAULT_CHANNEL_COUNT = 2;
// (Optional) Configure the maximum input length.
constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = 1152;
OH_AVFormat *format = OH_AVFormat_Create();
// Set the format.
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(),DEFAULT_SMAPLERATE);
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_BITRATE.data(),DEFAULT_BITRATE);
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(),DEFAULT_CHANNEL_COUNT);
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_MAX_INPUT_SIZE.data(),DEFAULT_MAX_INPUT_SIZE);
if (audioType == TYPE_AAC) {
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AAC_IS_ADTS.data(), DEFAULT_AAC_TYPE);
}
if (audioType == TYPE_VORBIS) {
OH_AVFormat_SetStringValue(format, MediaDescriptionKey::MD_KEY_IDENTIFICATION_HEADER.data(), DEFAULT_ID_HEADER);
OH_AVFormat_SetStringValue(format, MediaDescriptionKey::MD_KEY_SETUP_HEADER.data(), DEFAULT_SETUP_HEADER);
}
// Configure the decoder.
ret = OH_AudioDecoder_Configure(audioDec, format);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
4. Call **OH_AudioDecoder_Prepare()** to prepare internal resources for the decoder.
```cpp
ret = OH_AudioDecoder_Prepare(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
5. Call **OH_AudioDecoder_Start()** to start the decoder.
```c++
inputFile_ = std::make_unique<std::ifstream>();
// Open the path of the binary file to be decoded.
inputFile_->open(inputFilePath.data(), std::ios::in | std::ios::binary);
// Configure the path of the output file.
outFile_ = std::make_unique<std::ofstream>();
outFile_->open(outputFilePath.data(), std::ios::out | std::ios::binary);
// Start decoding.
ret = OH_AudioDecoder_Start(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
6. Call **OH_AudioDecoder_PushInputData()** to write the data to decode.
To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag.
```c++
// Configure the buffer information.
OH_AVCodecBufferAttr info;
// Set the package size, offset, and timestamp.
info.size = pkt_->size;
info.offset = 0;
info.pts = pkt_->pts;
info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
auto buffer = signal_->inBufferQueue_.front();
if (inputFile_->eof()){
info.size = 0;
info.flags = AVCODEC_BUFFER_FLAGS_EOS;
}else{
inputFile_->read((char *)OH_AVMemory_GetAddr(buffer), INPUT_FRAME_BYTES);
}
uint32_t index = signal_->inQueue_.front();
// Send the data to the input queue for decoding. The index is the subscript of the queue.
int32_t ret = OH_AudioDecoder_PushInputData(audioDec, index, info);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
7. Call **OH_AudioDecoder_FreeOutputData()** to output decoded PCM streams.
```c++
OH_AVCodecBufferAttr attr = signal_->attrQueue_.front();
OH_AVMemory *data = signal_->outBufferQueue_.front();
uint32_t index = signal_->outQueue_.front();
// Write the decoded data (specified by data) to the output file.
outFile_->write(reinterpret_cast<char *>(OH_AVMemory_GetAddr(data)), attr.size);
// Free the buffer that stores the data.
ret = OH_AudioDecoder_FreeOutputData(audioDec, index);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
8. (Optional) Call **OH_AudioDecoder_Flush()** to refresh the decoder.
After **OH_AudioDecoder_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed. To continue decoding, you must call **OH_AudioDecoder_Start()** again.
You need to call **OH_AudioDecoder_Start()** in the following cases:
* The EOS of the file is reached.
* An error with **OH_AudioDecoder_IsValid** set to **true** (indicating that the execution can continue) occurs.
```c++
// Refresh the decoder.
ret = OH_AudioDecoder_Flush(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Start decoding again.
ret = OH_AudioDecoder_Start(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
9. (Optional) Call **OH_AudioDecoder_Reset()** to reset the decoder.
After **OH_AudioDecoder_Reset()** is called, the decoder returns to the initialized state. To continue decoding, you must call **OH_AudioDecoder_Configure()** and then **OH_AudioDecoder_Start()**.
```c++
// Reset the decoder.
ret = OH_AudioDecoder_Reset(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Reconfigure the decoder.
ret = OH_AudioDecoder_Configure(audioDec, format);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
10. Call **OH_AudioDecoder_Stop()** to stop the decoder.
```c++
// Stop the decoder.
ret = OH_AudioDecoder_Stop(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
return ret;
```
11. Call **OH_AudioDecoder_Destroy()** to destroy the decoder instance and release resources.
**NOTE**: You only need to call this API once.
```c++
// Call OH_AudioDecoder_Destroy to destroy the decoder.
ret = OH_AudioDecoder_Destroy(audioDec);
if (ret != AV_ERR_OK) {
// Exception handling.
} else {
audioEnc = NULL; // The decoder cannot be destroyed repeatedly.
}
return ret;
```
\ No newline at end of file
# Audio Encoding
You can call the native APIs provided by the **AudioEncoder** module to encode audio, that is, to compress audio PCM data into a desired format.
PCM data can be from any source. For example, you can use a microphone to record audio data or import edited PCM data. After audio encoding, you can output streams in the desired format and encapsulate the streams into a target file.
Currently, the following encoding capabilities are supported:
| Container Specification| Audio Encoding Type|
| -------- | :----------- |
| mp4 | AAC, FLAC |
| m4a | AAC |
| flac | FLAC |
| aac | AAC |
**Usage Scenario**
- Audio recording
Record and transfer PCM data, and encode the data into streams in the desired format.
- Audio editing
Import edited PCM data, and encode the data into streams in the desired format.
## How to Develop
Read [AudioEncoder](../reference/native-apis/_audio_encoder.md) for the API reference.
Refer to the code snippet below to complete the entire audio encoding process, including creating an encoder, setting encoding parameters (such as the sampling rate, bit rate, and number of audio channels), and starting, refreshing, resetting, and destroying the encoder.
During application development, you must call the APIs in the defined sequence. Otherwise, an exception or undefined behavior may occur.
For details about the complete code, see [Sample](https://gitee.com/openharmony/multimedia_av_codec/blob/master/test/nativedemo/audio_demo/avcodec_audio_aac_encoder_demo.cpp).
The figure below shows the call relationship of audio encoding.
![Call relationship of audio encoding](figures/audio-encode.png)
1. Create an encoder instance.
You can create an encoder by name or MIME type.
```cpp
// Create an encoder by name.
OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_AUDIO_AAC, true);
const char *name = OH_AVCapability_GetName(capability);
OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByName(name);
```
```cpp
// Create an encoder by MIME type.
OH_AVCodec *audioEnc = OH_AudioEncoder_CreateByMime(OH_AVCODEC_MIMETYPE_AUDIO_AAC);
```
```cpp
// Initialize the queues.
class AEncSignal {
public:
std::mutex inMutex_;
std::mutex outMutex_;
std::mutex startMutex_;
std::condition_variable inCond_;
std::condition_variable outCond_;
std::condition_variable startCond_;
std::queue<uint32_t> inQueue_;
std::queue<uint32_t> outQueue_;
std::queue<OH_AVMemory *> inBufferQueue_;
std::queue<OH_AVMemory *> outBufferQueue_;
std::queue<OH_AVCodecBufferAttr> attrQueue_;
};
AEncSignal *signal_ = new AEncSignal();
```
2. Call **OH_AudioEncoder_SetCallback()** to set callback functions.
Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers:
- **OnError**, a callback used to report a codec operation error
- **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, audio channel change
- **OnInputBufferAvailable**, a callback used to report input data required, which means that the encoder is ready for receiving PCM data
- **OnOutputBufferAvailable**, a callback used to report output data generated, which means that encoding is complete
You need to process the callback functions to ensure that the encoder runs properly.
```cpp
// Set the OnError callback function.
static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
{
(void)codec;
(void)errorCode;
(void)userData;
}
// Set the OnOutputFormatChanged callback function.
static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
{
(void)codec;
(void)format;
(void)userData;
}
// Set the OnInputBufferAvailable callback function, which is used to send the input PCM data to the InputBuffer queue.
static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
{
(void)codec;
// The input stream is sent to the InputBuffer queue.
AEncSignal *signal = static_cast<AEncSignal *>(userData);
cout << "OnInputBufferAvailable received, index:" << index << endl;
unique_lock<mutex> lock(signal->inMutex_);
signal->inQueue_.push(index);
signal->inBufferQueue_.push(data);
signal->inCond_.notify_all();
}
// Set the OnOutputBufferAvailable callback function, which is used to send the encoded stream to the OutputBuffer queue.
static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
void *userData)
{
(void)codec;
// The index of the output buffer is sent to the OutputQueue.
// The encoded data is sent to the OutputBuffer queue.
AEncSignal *signal = static_cast<AEncSignal *>(userData);
unique_lock<mutex> lock(signal->outMutex_);
signal->outQueue_.push(index);
signal->outBufferQueue_.push(data);
if (attr) {
signal->attrQueue_.push(*attr);
}
}
OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable};
// Set the asynchronous callbacks.
int32_t ret = OH_AudioEncoder_SetCallback(audioEnc, cb, userData);
```
3. Call **OH_AudioEncoder_Configure** to configure the encoder.
The following options are mandatory: sampling rate, bit rate, number of audio channels, audio channel type, and bit depth. The maximum input length is optional.
For FLAC encoding, the compliance level and sampling precision are also mandatory.
```cpp
enum AudioFormatType : int32_t {
TYPE_AAC = 0,
TYPE_FLAC = 1,
};
int32_t ret;
// (Mandatory) Configure the audio sampling rate.
constexpr uint32_t DEFAULT_SMAPLERATE = 44100;
// (Mandatory) Configure the audio bit rate.
constexpr uint32_t DEFAULT_BITRATE = 32000;
// (Mandatory) Configure the number of audio channels.
constexpr uint32_t DEFAULT_CHANNEL_COUNT = 2;
// (Mandatory) Configure the audio channel type.
constexpr AudioChannelLayout CHANNEL_LAYOUT =AudioChannelLayout::STEREO;
// (Mandatory) Configure the audio bit depth. Only SAMPLE_S16LE and SAMPLE_S32LE are available for FLAC encoding.
constexpr OH_BitsPerSample SAMPLE_FORMAT =OH_BitsPerSample::SAMPLE_S32LE;
// (Mandatory) Configure the audio bit depth. Only SAMPLE_S32P is available for AAC encoding.
constexpr OH_BitsPerSample SAMPLE_AAC_FORMAT =OH_BitsPerSample::SAMPLE_S32P;
// Configure the audio compliance level. The default value is 0, and the value ranges from -2 to 2.
constexpr int32_t COMPLIANCE_LEVEL = 0;
// (Mandatory) Configure the audio sampling precision. SAMPLE_S16LE, SAMPLE_S24LE, and SAMPLE_S32LE are available.
constexpr BITS_PER_CODED_SAMPLE BITS_PER_CODED_SAMPLE =OH_BitsPerSample::SAMPLE_S24LE;
// (Optional) Configure the maximum input length.
constexpr uint32_t DEFAULT_MAX_INPUT_SIZE = 1024*DEFAULT_CHANNEL_COUNT *sizeof(float);//aac
OH_AVFormat *format = OH_AVFormat_Create();
// Set the format.
OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_SAMPLE_RATE.data(),DEFAULT_SMAPLERATE);
OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_BITRATE.data(), DEFAULT_BITRATE);
OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_COUNT.data(),DEFAULT_CHANNEL_COUNT);
OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_MAX_INPUT_SIZE.data(),DEFAULT_MAX_INPUT_SIZE);
OH_AVFormat_SetLongValue(format,MediaDescriptionKey::MD_KEY_CHANNEL_LAYOUT.data(),CHANNEL_LAYOUT);
OH_AVFormat_SetIntValue(format,MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(),SAMPLE_FORMAT);
if(audioType == TYPE_AAC){
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_AUDIO_SAMPLE_FORMAT.data(), SAMPLE_AAC_FORMAT);
}
if (audioType == TYPE_FLAC) {
OH_AVFormat_SetIntValue(format, MediaDescriptionKey::MD_KEY_BITS_PER_CODED_SAMPLE.data(), BITS_PER_CODED_SAMPLE);
OH_AVFormat_SetLongValue(format, MediaDescriptionKey::MD_KEY_COMPLIANCE_LEVEL.data(), COMPLIANCE_LEVEL);
}
// Configure the encoder.
ret = OH_AudioEncoder_Configure(audioEnc, format);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
4. Call **OH_AudioEncoder_Prepare()** to prepare internal resources for the encoder.
```c++
OH_AudioEncoder_Prepare(audioEnc);
```
5. Call **OH_AudioEncoder_Start()** to start the encoder.
```c++
inputFile_ = std::make_unique<std::ifstream>();
// Open the path of the binary file to be encoded.
inputFile_->open(inputFilePath.data(), std::ios::in |std::ios::binary);
// Configure the path of the output file.
outFile_ = std::make_unique<std::ofstream>();
outFile_->open(outputFilePath.data(), std::ios::out |std::ios::binary);
// Start encoding.
ret = OH_AudioEncoder_Start(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
6. Call **OH_AudioEncoder_PushInputData()** to write the data to encode.
To indicate the End of Stream (EOS), pass in the **AVCODEC_BUFFER_FLAGS_EOS** flag.
For AAC encoding, **FRAME_SIZE** (number of sampling points) is fixed at **1024**.
For FLAC encoding, set **FRAME_SIZE** based on the table below.
| Sampling Rate| FRAME_SIZE|
| :----: | :----: |
| 8000 | 576 |
| 16000 | 1152 |
| 22050 | 2304 |
| 24000 | 2304 |
| 32000 | 2304 |
| 44100 | 4608 |
| 48000 | 4608 |
| 88200 | 8192 |
| 96000 | 8192 |
**NOTE**: If **FRAME_SIZE** is not set to **1024** for AAC encoding, an error code is returned. In the case of FLAC encoding, if **FRAME_SIZE** is set to a value greater than the value listed in the table for a given sampling rate, an error code is returned; if **FRAME_SIZE** is set to a value less than the value listed, the encoded file may be damaged.
```c++
constexpr int32_t FRAME_SIZE = 1024; // AAC encoding
constexpr int32_t DEFAULT_CHANNEL_COUNT =2;
constexpr int32_t INPUT_FRAME_BYTES = DEFAULT_CHANNEL_COUNT * FRAME_SIZE * sizeof(float); // AAC encoding
// Configure the buffer information.
OH_AVCodecBufferAttr info;
// Set the package size, offset, and timestamp.
info.size = pkt_->size;
info.offset = 0;
info.pts = pkt_->pts;
info.flags = AVCODEC_BUFFER_FLAGS_CODEC_DATA;
auto buffer = signal_->inBufferQueue_.front();
if (inputFile_->eof()){
info.size = 0;
info.flags = AVCODEC_BUFFER_FLAGS_EOS;
}else{
inputFile_->read((char *)OH_AVMemory_GetAddr(buffer), INPUT_FRAME_BYTES);
}
uint32_t index = signal_->inQueue_.front();
// Send the data to the input queue for encoding. The index is the subscript of the queue.
int32_t ret = OH_AudioEncoder_PushInputData(audioEnc, index,info);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
7. Call **OH_AudioEncoder_FreeOutputData()** to output the encoded stream.
```c++
OH_AVCodecBufferAttr attr = signal_->attrQueue_.front();
OH_AVMemory *data = signal_->outBufferQueue_.front();
uint32_t index = signal_->outQueue_.front();
// Write the encoded data (specified by data) to the output file.
outFile_->write(reinterpret_cast<char *>(OH_AVMemory_GetAdd(data)), attr.size);
// Release the output buffer.
ret = OH_AudioEncoder_FreeOutputData(audioEnc, index);
if (ret != AV_ERR_OK) {
// Exception handling.
}
if (attr.flags == AVCODEC_BUFFER_FLAGS_EOS) {
cout << "decode eos" << endl;
isRunning_.store(false);
break;
}
```
8. (Optional) Call **OH_AudioEncoder_Flush()** to refresh the encoder.
After **OH_AudioEncoder_Flush()** is called, the current encoding queue is cleared.
To continue encoding, you must call **OH_AudioEncoder_Start()** again.
You need to call **OH_AudioEncoder_Flush()** in the following cases:
* The EOS of the file is reached.
* An error with **OH_AudioEncoder_IsValid** set to **true** (indicating that the execution can continue) occurs.
```c++
// Refresh the encoder.
ret = OH_AudioEncoder_Flush(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Start encoding again.
ret = OH_AudioEncoder_Start(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
9. (Optional) Call **OH_AudioEncoder_Reset()** to reset the encoder.
After **OH_AudioEncoder_Reset()** is called, the encoder returns to the initialized state. To continue encoding, you must call **OH_AudioEncoder_Configure()** and then **OH_AudioEncoder_Start()**.
```c++
// Reset the encoder.
ret = OH_AudioEncoder_Reset(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Reconfigure the encoder.
ret = OH_AudioEncoder_Configure(audioEnc, format);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
10. Call **OH_AudioEncoder_Stop()** to stop the encoder.
```c++
// Stop the encoder.
ret = OH_AudioEncoder_Stop(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
}
return ret;
```
11. Call **OH_AudioEncoder_Destroy()** to destroy the encoder instance and release resources.
**NOTE**: You only need to call this API once.
```c++
// Call OH_AudioEncoder_Destroy to destroy the encoder.
ret = OH_AudioEncoder_Destroy(audioEnc);
if (ret != AV_ERR_OK) {
// Exception handling.
} else {
audioEnc = NULL; // The encoder cannot be destroyed repeatedly.
}
return ret;
```
# Audio and Video Decapsulation
You can call the native APIs provided by the **AVDemuxer** module to decapsulate audio and video, that is, to extract audio and video frame data from bit stream data.
Currently, two data input types are supported: remote connection (over HTTP) and File Descriptor (FD).
The following decapsulation formats are supported:
| Media Format | Encapsulation Format |
| -------- | :----------------------------|
| Video | MP4, MPEG TS |
| Audio | M4A, AAC, MP3, OGG, FLAC, WAV|
**Usage Scenario**
- Audio and video playback
Decapsulate audio and video streams, decode the frame data obtained through decapsulation, and play the decoded data.
- Audio and video editing
Decapsulate audio and video streams, and edit the specified frames.
- Media file format conversion
Decapsulate audio and video streams, and encapsulate them into a new file format.
## How to Develop
Read [AVDemuxer](../reference/native-apis/_a_v_demuxer.md) and [AVSource](../reference/native-apis/_a_v_source.md) for the API reference.
> **NOTE**
>
> - To call the decapsulation APIs to parse a network playback path, request the **ohos.permission.INTERNET** permission by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md).
> - To call the decapsulation APIs to parse a local file, request the **ohos.permission.READ_MEDIA** permission by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md).
> - You can also use **ResourceManager.getRawFd** to obtain the FD of a file packed in the HAP file. For details, see [ResourceManager API Reference](../reference/apis/js-apis-resource-manager.md#getrawfd9).
1. Create a demuxer instance.
``` c++
// Create the FD. You must have the read permission on the file handle when opening the file.
std::string fileName = "test.mp4";
int fd = open(fileName.c_str(), O_RDONLY);
struct stat fileStatus {};
size_t fileSize = 0;
if (stat(fileName.c_str(), &fileStatus) == 0) {
fileSize = static_cast<size_t>(fileStatus.st_size);
} else {
printf("get stat failed");
return;
}
// Create a source resource object for the FD resource file. If offset is not the start position of the file or size is not the actual file size, the data obtained may be incomplete. Consequently, the source resource object may fail to create or subsequent decapsulation may fail.
OH_AVSource *source = OH_AVSource_CreateWithFD(fd, 0, fileSize);
if (source == nullptr) {
printf("create source failed");
return;
}
// (Optional) Create a source resource object for the URI resource file.
// OH_AVSource *source = OH_AVSource_CreateWithURI(uri);
```
```c++
// Create a demuxer for the resource object.
OH_AVDemuxer *demuxer = OH_AVDemuxer_CreateWithSource(source);
if (demuxer == nullptr) {
printf("create demuxer failed");
return;
}
```
2. (Optional) Obtain the number of tracks. If you know the track information, skip this step.
``` c++
// Obtain the number of tracks from the file source information.
OH_AVFormat *sourceFormat = OH_AVSource_GetSourceFormat(source);
if (sourceFormat == nullptr) {
printf("get source format failed");
return;
}
int32_t trackCount = 0;
OH_AVFormat_GetIntValue(sourceFormat, OH_MD_KEY_TRACK_COUNT, &trackCount);
OH_AVFormat_Destroy(sourceFormat);
```
3. (Optional) Obtain the track index and format. If you know the track information, skip this step.
``` c++
uint32_t audioTrackIndex = 0;
uint32_t videoTrackIndex = 0;
int32_t w = 0;
int32_t h = 0;
int32_t trackType;
for (uint32_t index = 0; index < (static_cast<uint32_t>(trackCount)); index++) {
// Obtain the track format.
OH_AVFormat *trackFormat = OH_AVSource_GetTrackFormat(source, index);
if (trackFormat == nullptr) {
printf("get track format failed");
return;
}
OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_TRACK_TYPE, &trackType);
static_cast<OH_MediaType>(trackType) == OH_MediaType::MEDIA_TYPE_AUD ? audioTrackIndex = index : videoTrackIndex = index;
// Obtain the width and height of the video track.
if (trackType == OH_MediaType::MEDIA_TYPE_VID) {
OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_WIDTH, &w);
OH_AVFormat_GetIntValue(trackFormat, OH_MD_KEY_HEIGHT, &h);
}
OH_AVFormat_Destroy(trackFormat);
}
```
4. Select a track, from which the demuxer reads data.
``` c++
if(OH_AVDemuxer_SelectTrackByID(demuxer, audioTrackIndex) != AV_ERR_OK){
printf("select audio track failed: %d", audioTrackIndex);
return;
}
if(OH_AVDemuxer_SelectTrackByID(demuxer, videoTrackIndex) != AV_ERR_OK){
printf("select video track failed: %d", videoTrackIndex);
return;
}
// (Optional) Deselect the track.
// OH_AVDemuxer_UnselectTrackByID(demuxer, audioTrackIndex);
```
5. (Optional) Seek to the specified time for the selected track.
``` c++
// Decapsulation is performed from this time.
// Note:
// 1. If OH_AVDemuxer_SeekToTime is called for an MPEG TS file, the target position may be a non-key frame. You can then call OH_AVDemuxer_ReadSample to check whether the current frame is a key frame based on the obtained OH_AVCodecBufferAttr. If it is a non-key frame, which causes display issues on the application side, cyclically read the frames until you reach the first key frame, where you can perform processing such as decoding.
// 2. If OH_AVDemuxer_SeekToTime is called for an OGG file, the file seeks to the start of the time interval (second) where the input parameter millisecond is located, which may cause a certain number of frame errors.
OH_AVDemuxer_SeekToTime(demuxer, 0, OH_AVSeekMode::SEEK_MODE_CLOSEST_SYNC);
```
6. Start decapsulation and cyclically obtain frame data. The code snippet below uses a file that contains audio and video tracks as an example.
``` c++
// Create a buffer to store the data obtained after decapsulation.
OH_AVMemory *buffer = OH_AVMemory_Create(w * h * 3 >> 1);
if (buffer == nullptr) {
printf("build buffer failed");
return;
}
OH_AVCodecBufferAttr info;
bool videoIsEnd = false;
bool audioIsEnd = false;
int32_t ret;
while (!audioIsEnd || !videoIsEnd) {
// Before calling OH_AVDemuxer_ReadSample, call OH_AVDemuxer_SelectTrackByID to select the track from which the demuxer reads data.
// Obtain audio frame data.
if(!audioIsEnd) {
ret = OH_AVDemuxer_ReadSample(demuxer, audioTrackIndex, buffer, &info);
if (ret == AV_ERR_OK) {
// Obtain the process the audio frame data in the buffer.
printf("audio info.size: %d\n", info.size);
if (info.flags == OH_AVCodecBufferFlags::AVCODEC_BUFFER_FLAGS_EOS) {
audioIsEnd = true;
}
}
}
if(!videoIsEnd) {
ret = OH_AVDemuxer_ReadSample(demuxer, videoTrackIndex, buffer, &info);
if (ret == AV_ERR_OK) {
// Obtain the process the video frame data in the buffer.
printf("video info.size: %d\n", info.size);
if (info.flags == OH_AVCodecBufferFlags::AVCODEC_BUFFER_FLAGS_EOS) {
videoIsEnd = true;
}
}
}
}
OH_AVMemory_Destroy(buffer);
```
7. Destroy the demuxer instance.
``` c++
// Manually set the instance to NULL after OH_AVSource_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs.
if (OH_AVSource_Destroy(source) != AV_ERR_OK) {
printf("destroy source pointer error");
}
source = NULL;
// Manually set the instance to NULL after OH_AVDemuxer_Destroy is called. Do not call this API repeatedly for the same instance; otherwise, a program error occurs.
if (OH_AVDemuxer_Destroy(demuxer) != AV_ERR_OK) {
printf("destroy demuxer pointer error");
}
demuxer = NULL;
close(fd);
```
# Audio and Video Encapsulation
You can call the native APIs provided by the **AVMuxer** module to encapsulate audio and video, that is, to store encoded audio and video data to a file in a certain format.
Currently, the following encapsulation capabilities are supported:
| Encapsulation Format| Video Codec Type | Audio Codec Type | Cover Type |
| -------- | --------------------- | ---------------- | -------------- |
| mp4 | MPEG-4, AVC (H.264)| AAC, MPEG (MP3)| jpeg, png, bmp|
| m4a | MPEG-4, AVC (H.264)| AAC | jpeg, png, bmp|
**Usage Scenario**
- Video and audio recording
After you encode audio and video streams, encapsulate them into files.
- Audio and video editing
After you edit audio and video, encapsulate them into files.
- Audio and video transcoding
After transcode audio and video, encapsulate them into files.
## How to Develop
Read [AVMuxer](../reference/native-apis/_a_v_muxer.md) for the API reference.
> **NOTE**
>
> To call the encapsulation APIs to write a local file, request the **ohos.permission.READ_MEDIA** and **ohos.permission.WRITE_MEDIA** permissions by following the instructions provided in [Applying for Permissions](../security/accesstoken-guidelines.md).
The following walks you through how to implement the entire process of audio and video encapsulation. It uses the MP4 format as an example.
1. Call **OH_AVMuxer_Create()** to create an **OH_AVMuxer** instance.
``` c++
// Set the encapsulation format to MP4.
OH_AVOutputFormat format = AV_OUTPUT_FORMAT_MPEG_4;
// Create a File Descriptor (FD) in read/write mode.
int32_t fd = open("test.mp4", O_CREAT | O_RDWR | O_TRUNC, S_IRUSR | S_IWUSR);
OH_AVMuxer *muxer = OH_AVMuxer_Create(fd, format);
```
2. (Optional) Call **OH_AVMuxer_SetRotation()** to set the rotation angle.
``` c++
// Set the rotation angle when a video image needs to be rotated.
OH_AVMuxer_SetRotation(muxer, 0);
```
3. Add an audio track.
**Method 1: Use OH_AVFormat_Create to create the format.**
``` c++
int audioTrackId = -1;
OH_AVFormat *formatAudio = OH_AVFormat_Create();
OH_AVFormat_SetStringValue(formatAudio, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_AUDIO_AAC); // Mandatory.
OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_SAMPLE_RATE, 44100); // Mandatory.
OH_AVFormat_SetIntValue(formatAudio, OH_MD_KEY_AUD_CHANNEL_COUNT, 2); // Mandatory.
int ret = OH_AVMuxer_AddTrack(muxer, &audioTrackId, formatAudio);
if (ret != AV_ERR_OK || audioTrackId < 0) {
// Failure to add the audio track.
}
OH_AVFormat_Destroy (formatAudio); // Destroy the format.
```
**Method 2: Use OH_AVFormat_CreateAudioFormat to create the format.**
``` c++
int audioTrackId = -1;
OH_AVFormat *formatAudio = OH_AVFormat_CreateAudioFormat(OH_AVCODEC_MIMETYPE_AUDIO_AAC, 44100, 2);
int ret = OH_AVMuxer_AddTrack(muxer, &audioTrackId, formatAudio);
if (ret != AV_ERR_OK || audioTrackId < 0) {
// Failure to add the audio track.
}
OH_AVFormat_Destroy (formatAudio); // Destroy the format.
```
4. Add a video track.
**Method 1: Use OH_AVFormat_Create to create the format.**
``` c++
int videoTrackId = -1;
char *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified.
size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements.
OH_AVFormat *formatVideo = OH_AVFormat_Create();
OH_AVFormat_SetStringValue(formatVideo, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_VIDEO_MPEG4); // Mandatory.
OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_WIDTH, 1280); // Mandatory.
OH_AVFormat_SetIntValue(formatVideo, OH_MD_KEY_HEIGHT, 720); // Mandatory.
OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional
int ret = OH_AVMuxer_AddTrack(muxer, &videoTrackId, formatVideo);
if (ret != AV_ERR_OK || videoTrackId < 0) {
// Failure to add the video track.
}
OH_AVFormat_Destroy(formatVideo); // Destroy the format.
```
**Method 2: Use OH_AVFormat_CreateVideoFormat to create the format.**
``` c++
int videoTrackId = -1;
char *buffer = ...; // Encoding configuration data. If there is no configuration data, leave the parameter unspecified.
size_t size =...; // Length of the encoding configuration data. Set this parameter based on project requirements.
OH_AVFormat *formatVideo = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_VIDEO_MPEG4, 1280, 720);
OH_AVFormat_SetBuffer(formatVideo, OH_MD_KEY_CODEC_CONFIG, buffer, size); // Optional
]
if (ret != AV_ERR_OK || videoTrackId < 0) {
// Failure to add the video track.
}
OH_AVFormat_Destroy(formatVideo); // Destroy the format.
```
5. Add a cover track.
**Method 1: Use OH_AVFormat_Create to create the format.**
``` c++
int coverTrackId = -1;
OH_AVFormat *formatCover = OH_AVFormat_Create();
OH_AVFormat_SetStringValue(formatCover, OH_MD_KEY_CODEC_MIME, OH_AVCODEC_MIMETYPE_IMAGE_JPG);
OH_AVFormat_SetIntValue(formatCover, OH_MD_KEY_WIDTH, 1280);
OH_AVFormat_SetIntValue(formatCover, OH_MD_KEY_HEIGHT, 720);
int ret = OH_AVMuxer_AddTrack(muxer, &coverTrackId, formatCover);
if (ret != AV_ERR_OK || coverTrackId < 0) {
// Failure to add the cover track.
}
OH_AVFormat_Destroy(formatCover); // Destroy the format.
```
**Method 2: Use OH_AVFormat_CreateVideoFormat to create the format.**
``` c++
int coverTrackId = -1;
OH_AVFormat *formatCover = OH_AVFormat_CreateVideoFormat(OH_AVCODEC_MIMETYPE_IMAGE_JPG, 1280, 720);
int ret = OH_AVMuxer_AddTrack(muxer, &coverTrackId, formatCover);
if (ret != AV_ERR_OK || coverTrackId < 0) {
// Failure to add the cover track.
}
OH_AVFormat_Destroy(formatCover); // Destroy the format.
```
6. Call **OH_AVMuxer_Start()** to start encapsulation.
``` c++
// Call Start() to write the file header. After this API is called, you cannot set media parameters or add tracks.
if (OH_AVMuxer_Start(muxer) != AV_ERR_OK) {
// Exception handling.
}
```
7. Call **OH_AVMuxer_WriteSample()** to write data, including video, audio, and cover data.
``` c++
// Data can be written only after Start() is called.
int size = ...;
OH_AVMemory *sample = OH_AVMemory_Create (size); // Create an AVMemory instance.
// Write data to the sample buffer. For details, see the usage of OH_AVMemory.
// Encapsulate the cover. One image must be written at a time.
// Set buffer information.
OH_AVCodecBufferAttr info;
info.pts =...; // Playback start time of the current data, in microseconds.
info.size = size; // Length of the current data.
info.offset = 0; // Offset. Generally, the value is 0.
info.flags |= AVCODEC_BUFFER_FLAGS_SYNC_FRAME; // Flag of the current data. For details, see OH_AVCodecBufferFlags.
int trackId = audioTrackId; // Select the track to be written.
int ret = OH_AVMuxer_WriteSample(muxer, trackId, sample, info);
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
8. Call **OH_AVMuxer_Stop()** to stop encapsulation.
``` c++
// Call Stop() to write the file trailer. After this API is called, you cannot write media data.
if (OH_AVMuxer_Stop(muxer) != AV_ERR_OK) {
// Exception handling.
}
```
9. Call **OH_AVMuxer_Destroy()** to release the instance.
``` c++
if (OH_AVMuxer_Destroy(muxer) != AV_ERR_OK) {
// Exception handling.
}
muxer = NULL;
close(fd); // Close the FD.
```
...@@ -77,6 +77,7 @@ The table below lists the supported audio playback formats. ...@@ -77,6 +77,7 @@ The table below lists the supported audio playback formats.
| Video Format| Mandatory or Not| | Video Format| Mandatory or Not|
| -------- | -------- | | -------- | -------- |
| H.265<sup>10+</sup> | Yes|
| H.264 | Yes| | H.264 | Yes|
| MPEG-2 | No| | MPEG-2 | No|
| MPEG-4 | No| | MPEG-4 | No|
...@@ -87,10 +88,10 @@ The table below lists the supported playback formats and mainstream resolutions. ...@@ -87,10 +88,10 @@ The table below lists the supported playback formats and mainstream resolutions.
| Video Container Format| Description| Resolution| | Video Container Format| Description| Resolution|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| MP4| Video formats: H.264, MPEG-2, MPEG-4, and H.263<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| | MP4| Video formats: H.265<sup>10+</sup>, H.264, MPEG2, MPEG4, and H.263<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p|
| MKV| Video formats: H.264, MPEG-2, MPEG-4, and H.263<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| | MKV| Video formats: H.265<sup>10+</sup>, H.264, MPEG2, MPEG4, and H.263<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p|
| TS| Video formats: H.264, MPEG-2, and MPEG-4<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| | TS| Video formats: H.265<sup>10+</sup>, H.264, MPEG2, and MPEG4<br>Audio formats: AAC and MP3| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p|
| WebM| Video format: VP8<br>Audio format: VORBIS| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p| | WebM| Video format: VP8<br>Audio format: VORBIS| Mainstream resolutions, such as 4K, 1080p, 720p, 480p, and 270p|
## AVRecorder ## AVRecorder
......
...@@ -34,7 +34,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. ...@@ -34,7 +34,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
console.log('prepare failed and error is ' + err.message); console.log('prepare failed and error is ' + err.message);
} }
}) })
let videoSurfaceId = null; let videoSurfaceId = null;
AVRecorder.getInputSurface().then((surfaceId) => { AVRecorder.getInputSurface().then((surfaceId) => {
console.info('getInputSurface success'); console.info('getInputSurface success');
...@@ -66,7 +66,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference. ...@@ -66,7 +66,7 @@ Read [Camera](../reference/apis/js-apis-camera.md) for the API reference.
videoFrameRate: 30 // Video frame rate. videoFrameRate: 30 // Video frame rate.
}, },
url: 'fd://35', url: 'fd://35',
rotation: 0 rotation: 90 // 90° is the default vertical display angle. You can use other values based on project requirements.
} }
// Create an AVRecorder instance. // Create an AVRecorder instance.
let avRecorder; let avRecorder;
......
...@@ -13,7 +13,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to ...@@ -13,7 +13,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to
``` ```
2. Obtain an image. 2. Obtain an image.
- Method 1: Obtain the sandbox path. For details about how to obtain the sandbox path, see [Obtaining the Application Development Path](../application-models/application-context-stage.md#obtaining-the-application-development-path). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md). - Method 1: Obtain the sandbox path. For details about how to obtain the sandbox path, see [Obtaining Application File Paths](../application-models/application-context-stage.md#obtaining-application-file-paths). For details about the application sandbox and how to push files to the application sandbox, see [File Management](../file-management/app-sandbox-directory.md).
```ts ```ts
// Code on the stage model // Code on the stage model
...@@ -110,6 +110,11 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to ...@@ -110,6 +110,11 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to
After the decoding is complete and the pixel map is obtained, you can perform subsequent [image processing](image-transformation.md). After the decoding is complete and the pixel map is obtained, you can perform subsequent [image processing](image-transformation.md).
5. Release the **PixelMap** instance.
```ts
pixelMap.release();
```
## Sample Code - Decoding an Image in Resource Files ## Sample Code - Decoding an Image in Resource Files
1. Obtain a resource manager. 1. Obtain a resource manager.
...@@ -140,4 +145,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to ...@@ -140,4 +145,7 @@ Read [Image](../reference/apis/js-apis-image.md#imagesource) for APIs related to
const pixelMap = await imageSource.createPixelMap(); const pixelMap = await imageSource.createPixelMap();
``` ```
<!--no_check--> 5. Release the **PixelMap** instance.
\ No newline at end of file ```ts
pixelMap.release();
```
# Obtaining Supported Codecs
Different devices support different codecs. Before invoking or configuring a codec, you need to query the codec specifications supported.
You can call the native APIs provided by the **AVCapability** module to check whether related capabilities are supported.
## How to Develop
Read [AVCapability](../reference/native-apis/_a_v_capability.md) for the API reference.
1. Obtain a codec capability instance.
```c
// Obtain a codec capability instance based on the MIME type and encoder flag.
OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false);
// Obtain a codec capability instance based on the MIME type, encoder flag, and software/hardware type.
OH_AVCapability *capability = OH_AVCodec_GetCapabilityByCategory(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false, SOFTWARE);
```
2. Query the specifications provided by the codec capability instance.
```c
// Check whether the codec capability instance describes a hardware codec.
bool isHardware = OH_AVCapability_IsHardware(capability);
// Obtain the codec name of the codec capability instance.
const char *codecName = OH_AVCapability_GetName(capability);
// Obtain the maximum number of instances supported by the codec capability instance.
int32_t maxSupportedInstances = OH_AVCapability_GetMaxSupportedInstances(capability);
// Obtain the bit rate range supported by the encoder.
OH_AVRange bitrateRange;
int32_t ret = OH_AVCapability_GetEncoderBitrateRange(capability, &bitrateRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Check whether the codec capability instance supports a specific bit rate mode.
bool isEncoderBitrateModeSupported = OH_AVCapability_IsEncoderBitrateModeSupported(capability, &bitrateMode);
// Obtain the quality range supported by the encoder.
OH_AVRange qualityRange;
int32_t ret = OH_AVCapability_GetEncoderQualityRange(capability, &qualityRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the complexity range supported by the encoder.
OH_AVRange complexityRange;
int32_t ret = OH_AVCapability_GetEncoderComplexityRange(capability, &complexityRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the supported audio sampling rates.
const int32_t *sampleRates;
uint32_t sampleRateNum = 0;
int32_t ret = OH_AVCapability_GetAudioSupportedSampleRates(capability, &sampleRates, &sampleRateNum);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the number of audio channels supported.
OH_AVRange channelCountRange;
int32_t ret = OH_AVCapability_GetAudioChannelCountRange(capability, &channelCountRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the width alignment value supported.
int32_t widthAlignment;
int32_t ret = OH_AVCapability_GetVideoWidthAlignment(capability, &widthAlignment);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the high alignment value supported.
int32_t heightAlignment;
int32_t ret = OH_AVCapability_GetVideoHeightAlignment(capability, &heightAlignment);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the width range when the height is 1080.
OH_AVRange widthRange;
int32_t ret = OH_AVCapability_GetVideoWidthRangeForHeight(capability, 1080, &widthRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the height range when the width is 1920.
OH_AVRange heightRange;
int32_t ret = OH_AVCapability_GetVideoHeightRangeForWidth(capability, 1920, &heightRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the width range supported.
OH_AVRange widthRange;
int32_t ret = OH_AVCapability_GetVideoWidthRange(capability, &widthRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the height range supported.
OH_AVRange heightRange;
int32_t ret = OH_AVCapability_GetVideoWidthRange(capability, &heightRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Check whether the codec capability instance supports the 1080p resolution.
bool isVideoSizeSupported = OH_AVCapability_IsVideoSizeSupported(capability, 1920, 1080);
// Obtain the video frame rate range supported.
OH_AVRange frameRateRange;
int32_t ret = OH_AVCapability_GetVideoFrameRateRange(capability, &frameRateRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the video frame rate range when the resolution is 1920 x 1080.
OH_AVRange frameRateRange;
int32_t ret = OH_AVCapability_GetVideoFrameRateRangeForSize(capability, 1920, 1080, &frameRateRange);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Check whether the codec capability instance supports the scenario where the resolution is 1080p and the frame rate is 30 fps.
bool areVideoSizeAndFrameRateSupported = OH_AVCapability_AreVideoSizeAndFrameRateSupported(capability, 1920, 1080, 30);
// Obtain the supported color formats and the number of supported color formats.
const int32_t *pixFormats;
uint32_t pixFormatNum = 0;
int32_t ret = OH_AVCapability_GetVideoSupportedPixelFormats(capability, &pixFormats, &pixFormatNum);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the profiles supported.
const int32_t *profiles;
uint32_t profileNum = 0;
int32_t ret = OH_AVCapability_GetSupportedProfiles(capability, &profiles, &profileNum);
if (ret != AV_ERR_OK) {
// Exception processing.
}
// Obtain the level range of a specific profile.
const int32_t *levels;
uint32_t levelNum = 0;
int32_t ret = OH_AVCapability_GetSupportedLevelsForProfile(capability, 0, &levels, &levelNum);
// Check whether the codec capability instance supports the scenario where the resolution is 1080p and the frame rate is 30 fps.
bool areVideoSizeAndFrameRateSupported = OH_AVCapability_AreVideoSizeAndFrameRateSupported(capability, 1920, 1080, 30);
```
# Using OHAudio for Audio Playback
**OHAudio** is a set of native APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels.
## Prerequisites
To use the playback or recording capability of **OHAudio**, you must first import the corresponding header files.
Specifically, to use APIs for audio playback, import <[native_audiostreambuilder.h](../reference/native-apis/native__audiostreambuilder_8h.md)> and <[native_audiorenderer.h](../reference/native-apis/native__audiorenderer_8h.md)>.
## Audio Stream Builder
**OHAudio** provides the **OH_AudioStreamBuilder** class, which complies with the builder design pattern and is used to build audio streams. You need to specify [OH_AudioStream_Type](../reference/native-apis/_o_h_audio.md#oh_audiostream_type) based on your service scenarios.
**OH_AudioStream_Type** can be set to either of the following:
- AUDIOSTREAM_TYPE_RENDERER
- AUDIOSTREAM_TYPE_CAPTURER
The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder:
```
OH_AudioStreamBuilder* builder;
OH_AudioStreamBuilder_Create(&builder, streamType);
```
After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder.
```
OH_AudioStreamBuilder_Destroy(builder);
```
## How to Develop
Read [OHAudio](../reference/native-apis/_o_h_audio.md) for the API reference.
The following walks you through how to implement simple playback:
1. Create an audio stream builder.
```c++
OH_AudioStreamBuilder* builder;
OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_RENDERER);
```
2. Set audio stream parameters.
After creating the builder for audio playback, set the parameters required.
```c++
OH_AudioStreamBuilder_SetSamplingRate(builder, rate);
OH_AudioStreamBuilder_SetChannelCount(builder, channelCount);
OH_AudioStreamBuilder_SetSampleFormat(builder, format);
OH_AudioStreamBuilder_SetEncodingType(builder, encodingType);
OH_AudioStreamBuilder_SetRendererInfo(builder, usage);
```
Note that the audio data to play is written through callbacks. You must call **OH_AudioStreamBuilder_SetRendererCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioRenderer_Callbacks](../reference/native-apis/_o_h_audio.md#oh_audiorenderer_callbacks).
3. Set the callback functions.
```c++
OH_AudioStreamBuilder_SetRendererCallback(builder, callbacks, nullptr);
```
4. Create an audio renderer instance.
```c++
OH_AudioRenderer* audioRenderer;
OH_AudioStreamBuilder_GenerateRenderer(builder, &audioRenderer);
```
5. Use the audio renderer.
You can use the APIs listed below to control the audio streams.
| API | Description |
| ------------------------------------------------------------ | ------------ |
| OH_AudioStream_Result OH_AudioRenderer_Start(OH_AudioRenderer* renderer) | Starts the audio renderer. |
| OH_AudioStream_Result OH_AudioRenderer_Pause(OH_AudioRenderer* renderer) | Pauses the audio renderer. |
| OH_AudioStream_Result OH_AudioRenderer_Stop(OH_AudioRenderer* renderer) | Stops the audio renderer. |
| OH_AudioStream_Result OH_AudioRenderer_Flush(OH_AudioRenderer* renderer) | Flushes written audio data.|
| OH_AudioStream_Result OH_AudioRenderer_Release(OH_AudioRenderer* renderer) | Releases the audio renderer instance.|
6. Destroy the audio stream builder.
When the builder is no longer used, release related resources.
```c++
OH_AudioStreamBuilder_Destroy(builder);
```
# Using OHAudio for Audio Recording
**OHAudio** is a set of native APIs introduced in API version 10. These APIs are normalized in design and support both common and low-latency audio channels.
## Prerequisites
To use the playback or recording capability of **OHAudio**, you must first import the corresponding header files.
To use APIs for audio recording, import <[native_audiostreambuilder.h](../reference/native-apis/native__audiostreambuilder_8h.md)> and <[native_audiocapturer.h](../reference/native-apis/native__audiocapturer_8h.md)>.
## Audio Stream Builder
**OHAudio** provides the **OH_AudioStreamBuilder** class, which complies with the builder design pattern and is used to build audio streams. You need to specify [OH_AudioStream_Type](../reference/native-apis/_o_h_audio.md#oh_audiostream_type) based on your service scenarios.
**OH_AudioStream_Type** can be set to either of the following:
- AUDIOSTREAM_TYPE_RENDERER
- AUDIOSTREAM_TYPE_CAPTURER
The following code snippet shows how to use [OH_AudioStreamBuilder_Create](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_create) to create a builder:
```
OH_AudioStreamBuilder* builder;
OH_AudioStreamBuilder_Create(&builder, streamType);
```
After the audio service is complete, call [OH_AudioStreamBuilder_Destroy](../reference/native-apis/_o_h_audio.md#oh_audiostreambuilder_destroy) to destroy the builder.
```
OH_AudioStreamBuilder_Destroy(builder);
```
## How to Develop
Read [OHAudio](../reference/native-apis/_o_h_audio.md) for the API reference.
The following walks you through how to implement simple recording:
1. Create an audio stream builder.
```c++
OH_AudioStreamBuilder* builder;
OH_AudioStreamBuilder_Create(&builder, AUDIOSTREAM_TYPE_CAPTURER);
```
2. Set audio stream parameters.
After creating the builder for audio recording, set the parameters required.
```c++
OH_AudioStreamBuilder_SetSamplingRate(builder, rate);
OH_AudioStreamBuilder_SetChannelCount(builder, channelCount);
OH_AudioStreamBuilder_SetSampleFormat(builder, format);
OH_AudioStreamBuilder_SetEncodingType(builder, encodingType);
OH_AudioStreamBuilder_SetCapturerInfo(builder, sourceType);
```
Note that the audio data to record is written through callbacks. You must call **OH_AudioStreamBuilder_SetCapturerCallback** to implement the callbacks. For details about the declaration of the callback functions, see [OH_AudioCapturer_Callbacks](../reference/native-apis/_o_h_audio.md#oh_audiocapturer_callbacks).
3. Set the callback functions.
```c++
OH_AudioStreamBuilder_SetCapturerCallback(builder, callbacks, nullptr);
```
4. Create an audio capturer instance.
```c++
OH_AudioCapturer* audioCapturer;
OH_AudioStreamBuilder_GenerateCapturer(builder, &audioCapturer);
```
5. Use the audio capturer.
You can use the APIs listed below to control the audio streams.
| API | Description |
| ------------------------------------------------------------ | ------------ |
| OH_AudioStream_Result OH_AudioCapturer_Start(OH_AudioCapturer* capturer) | Starts the audio capturer. |
| OH_AudioStream_Result OH_AudioCapturer_Pause(OH_AudioCapturer* capturer) | Pauses the audio capturer. |
| OH_AudioStream_Result OH_AudioCapturer_Stop(OH_AudioCapturer* capturer) | Stops the audio capturer. |
| OH_AudioStream_Result OH_AudioCapturer_Flush(OH_AudioCapturer* capturer) | Flushes obtained audio data.|
| OH_AudioStream_Result OH_AudioCapturer_Release(OH_AudioCapturer* capturer) | Releases the audio capturer instance.|
6. Destroy the audio stream builder.
When the builder is no longer used, release related resources.
```c++
OH_AudioStreamBuilder_Destroy(builder);
```
# Video Decoding
You can call the native APIs provided by the **VideoDecoder** module to decode video, that is, to decode media data into a YUV file or send it for display.
Currently, the following decoding capabilities are supported:
| Container Specification| Video Hardware Decoding Type | Video Software Decoding Type |
| -------- | --------------------- | ---------------- |
| mp4 | AVC (H.264), HEVC (H.265)|AVC (H.264) |
Video software decoding and hardware decoding are different. When a decoder is created based on the MIME type, only H.264 (video/avc) is supported for software decoding, and H.264 (video/avc) and H.265 (video/hevc) are supported for hardware decoding.
## How to Develop
Read [VideoDecoder](../reference/native-apis/_video_decoder.md) for the API reference.
1. Create a decoder instance.
You can create a decoder by name or MIME type.
``` c++
// Create a decoder by name.
OH_AVCapability *capability = OH_AVCodec_GetCapability(OH_AVCODEC_MIMETYPE_VIDEO_AVC, false);
const char *name = OH_AVCapability_GetName(capability);
OH_AVCodec *videoDec = OH_VideoDecoder_CreateByName(name); // name:"OH.Media.Codec.Decoder.Video.AVC"
```
```c++
// Create a decoder by MIME type.
// Create an H.264 decoder for software/hardware decoding.
OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_AVC);
// Create a decoder by MIME type.
// Create an H.265 decoder for hardware decoding.
OH_AVCodec *videoDec = OH_VideoDecoder_CreateByMime(OH_AVCODEC_MIMETYPE_VIDEO_HEVC);
```
``` c++
// Initialize the queues.
class VDecSignal {
public:
std::mutex inMutex_;
std::mutex outMutex_;
std::condition_variable inCond_;
std::condition_variable outCond_;
std::queue<uint32_t> inQueue_;
std::queue<uint32_t> outQueue_;
std::queue<OH_AVMemory *> inBufferQueue_;
std::queue<OH_AVMemory *> outBufferQueue_;
std::queue<OH_AVCodecBufferAttr> attrQueue_;
};
VDecSignal *signal_;
```
2. Call **OH_VideoDecoder_SetCallback()** to set callback functions.
Register the **OH_AVCodecAsyncCallback** struct that defines the following callback function pointers:
- **OnError**, a callback used to report a codec operation error
- **OnOutputFormatChanged**, a callback used to report a codec stream change, for example, stream width or height change.
- **OnInputBufferAvailable**, a callback used to report input data required, which means that the decoder is ready for receiving data
- **OnOutputBufferAvailable**, a callback used to report output data generated, which means that decoding is complete (Note: The **data** parameter in the callback function is empty in surface output mode.)
You need to process the callback functions to ensure that the decoder runs properly.
``` c++
// Set the OnError callback function.
static void OnError(OH_AVCodec *codec, int32_t errorCode, void *userData)
{
(void)codec;
(void)errorCode;
(void)userData;
}
// Set the OnOutputFormatChanged callback function.
static void OnOutputFormatChanged(OH_AVCodec *codec, OH_AVFormat *format, void *userData)
{
(void)codec;
(void)format;
(void)userData;
}
// Set the OnInputBufferAvailable callback function, which is used to obtain the input frame information.
static void OnInputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, void *userData)
{
(void)codec;
VDecSignal *signal_ = static_cast<VDecSignal *>(userData);
unique_lock<mutex> lock(signal_->inMutex_);
// The ID of the input frame is sent to inQueue_.
signal_->inQueue_.push(index);
// The input frame data is sent to inBufferQueue_.
signal_->inBufferQueue_.push(data);
signal_->inCond_.notify_all();
}
// Set the OnOutputBufferAvailable callback function, which is used to obtain the output frame information.
static void OnOutputBufferAvailable(OH_AVCodec *codec, uint32_t index, OH_AVMemory *data, OH_AVCodecBufferAttr *attr,
void *userData)
{
(void)codec;
VDecSignal *signal_ = static_cast<VDecSignal *>(userData);
unique_lock<mutex> lock(signal_->outMutex_);
// The index of the output buffer is sent to outQueue_.
signal_->outQueue_.push(index);
// The decoded data (specified by data) is sent to outBufferQueue_. (Note: data is empty in surface output mode.)
signal_->outBufferQueue_.push(data);
signal_->attrQueue_.push(*attr);
signal_->outCond_.notify_all();
}
OH_AVCodecAsyncCallback cb = {&OnError, &OnOutputFormatChanged, &OnInputBufferAvailable, &OnOutputBufferAvailable};
// Set the asynchronous callbacks.
int32_t ret = OH_VideoDecoder_SetCallback(videoDec, cb, signal_);
```
3. Call **OH_VideoDecoder_Configure()** to configure the decoder.
The following options are mandatory: video frame width, video frame height, and video color format.
``` c++
// (Mandatory) Configure the video frame width.
constexpr uint32_t DEFAULT_WIDTH = 320;
// (Mandatory) Configure the video frame height.
constexpr uint32_t DEFAULT_HEIGHT = 240;
OH_AVFormat *format = OH_AVFormat_Create();
// Set the format.
OH_AVFormat_SetIntValue(format, OH_MD_KEY_WIDTH, DEFAULT_WIDTH);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_HEIGHT, DEFAULT_HEIGHT);
OH_AVFormat_SetIntValue(format, OH_MD_KEY_PIXEL_FORMAT, AV_PIXEL_FORMAT_NV21);
// Configure the decoder.
int32_t ret = OH_VideoDecoder_Configure(videoDec, format);
OH_AVFormat_Destroy(format);
```
4. (Optional) Set the surface.
This step is required only when the surface is used to send the data for display.
``` c++
// Set the parameters of the display window.
sptr<Rosen::Window> window = nullptr;
sptr<Rosen::WindowOption> option = new Rosen::WindowOption();
option->SetWindowRect({0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT});
option->SetWindowType(Rosen::WindowType::WINDOW_TYPE_APP_LAUNCHING);
option->SetWindowMode(Rosen::WindowMode::WINDOW_MODE_FLOATING);
window = Rosen::Window::Create("video-decoding", option);
window->Show();
sptr<Surface> ps = window->GetSurfaceNode()->GetSurface();
OHNativeWindow *nativeWindow = CreateNativeWindowFromSurface(&ps);
int32_t ret = OH_VideoDecoder_SetSurface(videoDec, window);
bool isSurfaceMode = true;
```
5. (Optional) Configure the surface parameters of the decoder. This step is required only when the surface is used.
``` c++
OH_AVFormat *format = OH_AVFormat_Create();
// Configure the display rotation angle.
OH_AVFormat_SetIntValue(format, OH_MD_KEY_ROTATION, 90);
// Configure the matching mode (scaling or cropping) between the video and the display screen.
OH_AVFormat_SetIntValue(format, OH_MD_KEY_SCALING_MODE, SCALING_MODE_SCALE_CROP);
int32_t ret = OH_VideoDecoder_SetParameter(videoDec, format);
OH_AVFormat_Destroy(format);
```
6. Call **OH_VideoDecoder_Start()** to start the decoder.
``` c++
string_view outputFilePath = "/*yourpath*.yuv";
std::unique_ptr<std::ifstream> inputFile = std::make_unique<std::ifstream>();
// Open the path of the binary file to be decoded.
inputFile->open(inputFilePath.data(), std::ios::in | std::ios::binary);
// Configure the parameter in buffer mode.
if(!isSurfaceMode) {
// Configure the output file path in buffer mode.
std::unique_ptr<std::ofstream> outFile = std::make_unique<std::ofstream>();
outFile->open(outputFilePath.data(), std::ios::out | std::ios::binary);
}
// Start decoding.
int32_t ret = OH_VideoDecoder_Start(videoDec);
```
7. Call **OH_VideoDecoder_PushInputData()** to push the stream to the input queue for decoding.
``` c++
// Configure the buffer information.
OH_AVCodecBufferAttr info;
// Call av_packet_alloc to initialize and return a container packet.
AVPacket pkt = av_packet_alloc();
// Configure the input size, offset, and timestamp of the buffer.
info.size = pkt->size;
info.offset = 0;
info.pts = pkt->pts;
info.flags = AVCODEC_BUFFER_FLAGS_NONE;
// Send the data to the input queue for decoding. The index is the subscript of the queue.
int32_t ret = OH_VideoDecoder_PushInputData(videoDec, index, info);
```
8. Call **OH_VideoDecoder_FreeOutputData()** to output the decoded frames.
``` c++
int32_t ret;
// Write the decoded data (specified by data) to the output file.
outFile->write(reinterpret_cast<char *>(OH_AVMemory_GetAddr(data)), data.size);
// Free the buffer that stores the output data. The index is the subscript of the surface/buffer queue.
if (isSurfaceMode) {
ret = OH_VideoDecoder_RenderOutputData(videoDec, index);
} else {
ret = OH_VideoDecoder_FreeOutputData(videoDec, index);
}
if (ret != AV_ERR_OK) {
// Exception handling.
}
```
9. (Optional) Call **OH_VideoDecoder_Flush()** to refresh the decoder.
After **OH_VideoDecoder_Flush()** is called, the decoder remains in the running state, but the current queue is cleared and the buffer storing the decoded data is freed.
To continue decoding, you must call **OH_VideoDecoder_Start()** again.
``` c++
int32_t ret;
// Refresh the decoder.
ret = OH_VideoDecoder_Flush(videoDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Start decoding again.
ret = OH_VideoDecoder_Start(videoDec);
```
10. (Optional) Call **OH_VideoDecoder_Reset()** to reset the decoder.
After **OH_VideoDecoder_Reset()** is called, the decoder returns to the initialized state. To continue decoding, you must call **OH_VideoDecoder_Configure()** and then **OH_VideoDecoder_Start()**.
``` c++
int32_t ret;
// Reset the decoder.
ret = OH_VideoDecoder_Reset(videoDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
// Reconfigure the decoder.
ret = OH_VideoDecoder_Configure(videoDec, format);
```
11. Call **OH_VideoDecoder_Stop()** to stop the decoder.
``` c++
int32_t ret;
// Stop the decoder.
ret = OH_VideoDecoder_Stop(videoDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
return AV_ERR_OK;
```
12. Call **OH_VideoDecoder_Destroy()** to destroy the decoder instance and release resources.
``` c++
int32_t ret;
// Call OH_VideoDecoder_Destroy to destroy the decoder.
ret = OH_VideoDecoder_Destroy(videoDec);
if (ret != AV_ERR_OK) {
// Exception handling.
}
return AV_ERR_OK;
```
此差异已折叠。
...@@ -85,7 +85,7 @@ The development process consists of the following main steps: ...@@ -85,7 +85,7 @@ The development process consists of the following main steps:
The required model can be downloaded directly or obtained using the model conversion tool. The required model can be downloaded directly or obtained using the model conversion tool.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example. - If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the .ms format. - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/downloads.html#id1) to convert it to the .ms format.
2. Create a context, and set parameters such as the number of runtime threads and device type. 2. Create a context, and set parameters such as the number of runtime threads and device type.
...@@ -280,7 +280,3 @@ The development process consists of the following main steps: ...@@ -280,7 +280,3 @@ The development process consists of the following main steps:
output data is: output data is:
0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023 0.000018 0.000012 0.000026 0.000194 0.000156 0.001501 0.000240 0.000825 0.000016 0.000006 0.000007 0.000004 0.000004 0.000004 0.000015 0.000099 0.000011 0.000013 0.000005 0.000023 0.000004 0.000008 0.000003 0.000003 0.000008 0.000014 0.000012 0.000006 0.000019 0.000006 0.000018 0.000024 0.000010 0.000002 0.000028 0.000372 0.000010 0.000017 0.000008 0.000004 0.000007 0.000010 0.000007 0.000012 0.000005 0.000015 0.000007 0.000040 0.000004 0.000085 0.000023
``` ```
## Samples
The following sample is provided to help you better understand how to use MindSpore Lite:
- [Simple MindSpore Lite Tutorial](https://gitee.com/openharmony/third_party_mindspore/tree/OpenHarmony-3.2-Release/mindspore/lite/examples/quick_start_c)
# app.json5 Configuration File # app.json5 Configuration File
This topic gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains. This document gives an overview of the **app.json5** configuration file. To start with, let's go through an example of what this file contains.
```json ```json
{ {
...@@ -35,7 +35,7 @@ As shown above, the **app.json5** file contains several tags. ...@@ -35,7 +35,7 @@ As shown above, the **app.json5** file contains several tags.
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No|
| bundleType| Bundle type, which is used to distinguish applications and atomic services.<br>- **app**: The bundle is a common application.<br>- **atomicService**: The bundle is an atomic service.<br>- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)| | bundleType| Bundle type, which is used to distinguish applications and atomic services. <br>- **app**: The bundle is a common application.<br>- **atomicService**: The bundle is an atomic service.<br>- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)|
| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| | debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)|
| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No| | icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No|
| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No| | label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No|
...@@ -47,7 +47,7 @@ As shown above, the **app.json5** file contains several tags. ...@@ -47,7 +47,7 @@ As shown above, the **app.json5** file contains several tags.
| minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)| | minAPIVersion | Minimum API version required for running the application.| Number| Yes (initial value: value of **compatibleSdkVersion** in **build-profile.json5**)|
| targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)| | targetAPIVersion | Target API version required for running the application.| Number| Yes (initial value: value of **compileSdkVersion** in **build-profile.json5**)|
| apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)| | apiReleaseType | Type of the target API version required for running the application. The value can be **"CanaryN"**, **"BetaN"**, or **"Release"**, where **N** represents a positive integer.<br>- **Canary**: indicates a restricted release.<br>- **Beta**: indicates a publicly released beta version.<br>- **Release**: indicates a publicly released official version.<br>The value is set by DevEco Studio reading the stage of the SDK in use.| String| Yes (initial value: set by DevEco Studio)|
| multiProjects | Whether the application supports joint development of multiple projects.<br>- **true**: The application supports joint development of multiple projects.<br>- **false**: The application does not support joint development of multiple projects. For details about multi-project development, see [Multi-Project Build](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/ohos-building-overview-0000001263360495-V3#section71471033104216).| Boolean| Yes (initial value: **false**)| | multiProjects | Whether the application supports joint development of multiple projects.<br>- **true**: The application supports joint development of multiple projects.<br>- **false**: The application does not support joint development of multiple projects. | Boolean| Yes (initial value: **false**)|
| asanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.<br>- **true**: ASan is enabled.<br>- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)| | asanEnabled | Whether to enable AddressSanitizer (ASan) to detect memory corruption issues such as buffer overflows.<br>- **true**: ASan is enabled.<br>- **false**: ASan is disabled. Note that ASan is not available in the Release version.| Boolean| Yes (initial value: **false**)|
| tablet | Tablet-specific configuration, which includes the **minAPIVersion** attribute.<br>When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tablet | Tablet-specific configuration, which includes the **minAPIVersion** attribute.<br>When running on tablets, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
| tv | TV-specific configuration, which includes the **minAPIVersion** attribute.<br>When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | tv | TV-specific configuration, which includes the **minAPIVersion** attribute.<br>When running on TVs, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
...@@ -56,4 +56,4 @@ As shown above, the **app.json5** file contains several tags. ...@@ -56,4 +56,4 @@ As shown above, the **app.json5** file contains several tags.
| default | Default device–specific configuration, which includes the **minAPIVersion** attribute.<br>When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)| | default | Default device–specific configuration, which includes the **minAPIVersion** attribute.<br>When running on default devices, the application applies the attribute settings under this tag and ignores the general counterparts.| Object| Yes (initial value: general settings in the **app.json5** file)|
|targetBundleName|Target application name of the bundle. The value rule and range are the same as those of **bundleName**.|String|Yes (if the initial value is used, the target application is not an application with the overlay feature)| |targetBundleName|Target application name of the bundle. The value rule and range are the same as those of **bundleName**.|String|Yes (if the initial value is used, the target application is not an application with the overlay feature)|
|targetPriority|Priority of the application. When **targetBundleName** is set, the application is an application with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)| |targetPriority|Priority of the application. When **targetBundleName** is set, the application is an application with the overlay feature. The value ranges from 1 to 100.|Number|Yes (initial value: **1**)|
|generateBuildHash |Whether the hash values of all HAP and HSP files of the application are generated by the packaging tool. The hash values (if any) are used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.<br>If this tag is set to **true**, the packaging tool generates hash values for all HAP and HSP files of the application.<br>**NOTE**<br>This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| |generateBuildHash |Whether the hash values of all HAP and HSP files of the application are generated by the packaging tool. The hash values (if any) are used to determine whether the application needs to be updated when the system is updated in OTA mode but the **versionCode** value of the application remains unchanged.<br>If this tag is set to **true**, the packaging tool generates hash values for all HAP and HSP files of the application.<br>**NOTE**<br>**This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)|
...@@ -5,6 +5,7 @@ Apart from\@Styles used to extend styles, AkrUI also provides \@Extend, which al ...@@ -5,6 +5,7 @@ Apart from\@Styles used to extend styles, AkrUI also provides \@Extend, which al
> **NOTE** > **NOTE**
>
> Since API version 9, this decorator is supported in ArkTS widgets. > Since API version 9, this decorator is supported in ArkTS widgets.
...@@ -169,7 +170,7 @@ struct FancyUse { ...@@ -169,7 +170,7 @@ struct FancyUse {
Text(`${this.label}`) Text(`${this.label}`)
.fancyText(200, Color.Pink) .fancyText(200, Color.Pink)
Text(`${this.label}`) Text(`${this.label}`)
.fancyText(200, Color.Orange) .fancyText(300, Color.Orange)
}.margin('20%') }.margin('20%')
} }
} }
......
...@@ -9,7 +9,7 @@ This topic describes only the LocalStorage application scenarios and related dec ...@@ -9,7 +9,7 @@ This topic describes only the LocalStorage application scenarios and related dec
> **NOTE** > **NOTE**
> >
> This module is supported since API version 9. > LocalStorage is supported since API version 9.
## Overview ## Overview
......
...@@ -27,7 +27,7 @@ Table 2 describes the internal structure of the **deviceConfig** attributes. ...@@ -27,7 +27,7 @@ Table 2 describes the internal structure of the **deviceConfig** attributes.
| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. The value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)| | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. The value can contain a maximum of 31 characters.| String| Yes (initial value: left empty)|
| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)| | keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application will start during the OS startup and keep alive. If the application process exits, the OS will restart it.| Boolean| Yes (initial value: **false**)|
| supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)| | supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.| Boolean| Yes (initial value: **false**)|
| compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.| Boolean| Yes (initial value: **true**)|
| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)| | network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code.| Object| Yes (initial value: left empty)|
## Internal Structure of the network Attribute ## Internal Structure of the network Attribute
......
...@@ -380,7 +380,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie ...@@ -380,7 +380,7 @@ The **extensionAbilities** tag represents the configuration of extensionAbilitie
| type | Type of the ExtensionAbility component. The options are as follows:<br>- **form**: ExtensionAbility of a widget.<br>- **workScheduler**: ExtensionAbility of a Work Scheduler task.<br>- **inputMethod**: ExtensionAbility of an input method.<br>- **service**: service component running in the background.<br>- **accessibility**: ExtensionAbility of an accessibility feature.<br>- **dataShare**: ExtensionAbility for data sharing.<br>- **fileShare**: ExtensionAbility for file sharing.<br>- **staticSubscriber**: ExtensionAbility for static broadcast.<br>- **wallpaper**: ExtensionAbility of the wallpaper.<br>- **backup**: ExtensionAbility for data backup.<br>- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.<br>- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.<br>- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.<br>- **print**: ExtensionAbility for the print framework.<br>- **push**: ExtensionAbility to be pushed.<br>- **driver**: ExtensionAbility for the driver framework.<br>**NOTE**<br>The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No| | type | Type of the ExtensionAbility component. The options are as follows:<br>- **form**: ExtensionAbility of a widget.<br>- **workScheduler**: ExtensionAbility of a Work Scheduler task.<br>- **inputMethod**: ExtensionAbility of an input method.<br>- **service**: service component running in the background.<br>- **accessibility**: ExtensionAbility of an accessibility feature.<br>- **dataShare**: ExtensionAbility for data sharing.<br>- **fileShare**: ExtensionAbility for file sharing.<br>- **staticSubscriber**: ExtensionAbility for static broadcast.<br>- **wallpaper**: ExtensionAbility of the wallpaper.<br>- **backup**: ExtensionAbility for data backup.<br>- **window**: ExtensionAbility of a window. This type of ExtensionAbility creates a window during startup for which you can develop the GUI. The window is then combined with other application windows through **abilityComponent**.<br>- **thumbnail**: ExtensionAbility for obtaining file thumbnails. You can provide thumbnails for files of customized file types.<br>- **preview**: ExtensionAbility for preview. This type of ExtensionAbility can parse the file and display it in a window. You can combine the window with other application windows.<br>- **print**: ExtensionAbility for the print framework.<br>- **push**: ExtensionAbility to be pushed.<br>- **driver**: ExtensionAbility for the driver framework.<br>**NOTE**<br>The **service** and **dataShare** types apply only to system applications and do not take effect for third-party applications.| String| No|
| permissions | Permissions required for another application to access the ExtensionAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)| | permissions | Permissions required for another application to access the ExtensionAbility component.<br>The value is generally in the reverse domain name notation and contains a maximum of 255 bytes. It is an array of permission names predefined by the system or customized. The name of a customized permission must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty)|
| uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)| | uri | Data URI provided by the ExtensionAbility component. The value is a string with a maximum of 255 bytes, in the reverse domain name notation.<br>**NOTE**<br>This attribute is mandatory when the type of the ExtensionAbility component is set to **dataShare**.| String| Yes (initial value: left empty)|
|skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,<br>but not for an OpenHarmony service.| Array| Yes (initial value: left empty)| |skills | Feature set of [wants](../application-models/want-overview.md) that can be received by the ExtensionAbility component.<br>Configuration rule: In an entry package, you can configure multiple **skills** attributes with the entry capability. (A **skills** attribute with the entry capability is the one that has **ohos.want.action.home** and **entity.system.home** configured.) The **label** and **icon** in the first ExtensionAbility that has **skills** configured are used as the **label** and **icon** of the entire OpenHarmony service/application.<br>**NOTE**<br>The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.| Array| Yes (initial value: left empty)|
| [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)| | [metadata](#metadata)| Metadata of the ExtensionAbility component.| Object| Yes (initial value: left empty)|
| exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | exported | Whether the ExtensionAbility component can be called by other applications. <br>- **true**: The ExtensionAbility component can be called by other applications.<br>- **false**: The ExtensionAbility component cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
......
...@@ -7,24 +7,24 @@ The **module** tag contains the HAP configuration. ...@@ -7,24 +7,24 @@ The **module** tag contains the HAP configuration.
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)| | mainAbility | Ability whose icon is displayed in the Service Center. When the resident process is started, the **mainAbility** is started.| String| Yes (initial value: left empty)|
| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No| | package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. | String| No|
| name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)| | name | Class name of the HAP file. The value is a string with a maximum of 255 bytes, in the reverse domain name notation. The prefix must be the same as the **package** value specified for this module. Alternatively, the value can start with a period (.) followed by the class name.| String| Yes (initial value: left empty)|
| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)| | description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description.| String| Yes (initial value: left empty)|
| supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)| | supportedModes | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty)|
|deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No| |deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No|
|distro | Distribution description of the HAP file.| Object| No| |distro | Distribution description of the HAP file.| Object| No|
|metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)| |metaData | Metadata of the HAP file.| Object| Yes (initial value: left empty)|
| abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)| | abilities | All abilities in the current module. The value is an array of objects, each of which represents an ability.| Object array| Yes (initial value: left empty)|
| js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)| | js | A set of JS modules developed using ArkUI. The value is an array of objects, each of which represents a JS module.| Object array| Yes (initial value: left empty)|
| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)| | shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object.| Object array| Yes (initial value: left empty)|
| reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)| | reqPermissions | Permissions that the application requests from the system when it is running.| Object array| Yes (initial value: left empty)|
| colorMode | Color mode of the application. The options are as follows:<br>- **dark**: Resources applicable for the dark mode are used.<br>- **light**: Resources applicable for the light mode are used.<br>- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)| | colorMode | Color mode of the application. The options are as follows:<br>- **dark**: Resources applicable for the dark mode are used.<br>- **light**: Resources applicable for the light mode are used.<br>- **auto**: Resources are used based on the color mode of the system.| String| Yes (initial value: **auto**)|
| distributionFilter | Distribution rules of the application. This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| | distributionFilter | Rules for distributing HAP files based on different device specifications, so that precise matching can be performed when the application market distributes applications. All sub-attributes under this attribute are optional. This attribute must be configured in the **/resource/profile** directory. During distribution, a unique HAP is determined based on the mapping between **deviceType** and attributes listed in the table below.| Object| Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.|
|commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| Object array| Yes (initial value: left empty)| |commonEvents | Information about the common event static subscriber, which must contain the subscriber name, required permissions, and list of the common events subscribed to. When a subscribed event is sent, the static subscriber is started. Unlike the dynamic subscriber, the static subscriber does not need to proactively call the common event subscription API in the service code, and may not be running when the common event is published.| Object array| Yes (initial value: left empty)|
| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)| | entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String| Yes (initial value: left empty)|
|testRunner | Test runner configuration.| Object| Yes (initial value: left empty)| |testRunner | Test runner configuration.| Object| Yes (initial value: left empty)|
|generateBuildHash | Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the value of [code](#internal-structure-of-the-apiversion-attribute) in **version** of the application remains unchanged.<br>**NOTE**<br>This tag applies only to system applications.|Boolean|Yes (initial value: **false**)| |generateBuildHash |Whether the hash value of the HAP or HSP file is generated by the packaging tool. The hash value (if any) is used to determine whether the application needs to be updated when the system is updated in OTA mode but the value of [code](#internal-structure-of-the-apiversion-attribute) in **version** of the application remains unchanged.<br>**NOTE**<br>**This tag applies only to system applications.**|Boolean|Yes (initial value: **false**)|
Example of the **module** tag structure: Example of the **module** tag structure:
...@@ -96,7 +96,7 @@ Example of the **module** tag structure: ...@@ -96,7 +96,7 @@ Example of the **module** tag structure:
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| moduleName | Name of the HAP file. The maximum length is 31 bytes.| String| No| | moduleName | Name of the HAP file. The maximum length is 31 bytes. During application upgrade, this name can be changed. If it is changed, migration of module-related directories is required for the application. You can use the [file operation API](../reference/apis/js-apis-file-fs.md#fscopydir10) for migration.| String| No|
| moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No| | moduleType | Type of the HAP file, which can **entry**, **feature**, or **har**.| String| No|
| installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No| | installationFree | Whether the HAP file supports the installation-free feature. **true**: The HAP file supports the installation-free feature and meets installation-free constraints. **false**: The HAP file does not support the installation-free feature. If this tag is set to **true** for an entry-type HAP file (**entry.hap**), it must also be set to **true** for feature-type HAP files (**feature.hap**) of the same application. If this tag is set to **false** for an entry-type HAP file, it can be set to **true** or **false** for feature-type modules of the same application based on service requirements.| Boolean| No|
| deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No| | deliveryWithInstall | Whether the HAP file will be installed when the user installs the application. **true**: The HAP file will be installed when the user installs the application. **false**: The HAP file will not be installed when the user installs the application.| Boolean| No|
...@@ -196,10 +196,10 @@ Example of the metadata attribute: ...@@ -196,10 +196,10 @@ Example of the metadata attribute:
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)| | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. The value can contain a maximum of 31 bytes.| String| Yes (initial value: left empty)|
| name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.<br>The ability name must be unique in an application.<br/>**NOTE**<br/>If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes. | String| No| | name | Ability name. The value can be a reverse domain name, in the format of "*bundleName*.*className*", for example, **"com.example.myapplication.EntryAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".EntryAbility"**.<br>The ability name must be unique in an application.<br>**NOTE**<br>If you use DevEco Studio to create the project, an ability named **EntryAbility** will be created by default, and its configuration will be saved to the **config.json** file. If you use other IDEs, the value of this attribute can be customized. The value can contain a maximum of 127 bytes.| String| No|
| description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)| | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.<br>**NOTE**<br>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String| Yes (initial value: left empty)| | icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.<br>**NOTE**<br>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String| Yes (initial value: left empty)|
| label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>**NOTE**<br/>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes. | String| Yes (initial value: left empty)| | label | Ability name displayed to users. The value can be a name string or a resource index to names in multiple languages, for example, **$string:ability_label**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.<br>**NOTE**<br>The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 bytes.| String| Yes (initial value: left empty)|
| uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)| | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 bytes.| String| Yes (No for abilities using the Data template)|
| launchType | Launch type of the ability. The value can be **standard** or **singleton**.<br>**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.<br>**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)| | launchType | Launch type of the ability. The value can be **standard** or **singleton**.<br>**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.<br>**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton launch type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String| Yes (initial value: **"singleton"**)|
| visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by other applications.<br>**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)| | visible | Whether the ability can be called by other applications.<br>**true**: The ability can be called by other applications.<br>**false**: The ability cannot be called by other applications.| Boolean| Yes (initial value: **false**)|
......
...@@ -381,6 +381,7 @@ ...@@ -381,6 +381,7 @@
- Account Management - Account Management
- [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md) - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
- [@ohos.account.appAccount.AuthorizationExtensionAbility (App Account AuthorizationExtensionAbility)](js-apis-appAccount-authorizationExtensionAbility.md)
- [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md)
- [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
......
...@@ -880,10 +880,8 @@ Indicates that the airplane mode of the device has changed. ...@@ -880,10 +880,8 @@ Indicates that the airplane mode of the device has changed.
- Required subscriber permissions: none - Required subscriber permissions: none
## COMMON_EVENT_SPLIT_SCREEN<sup>8+</sup> ## [COMMON_EVENT_SPLIT_SCREEN<sup>8+<sup>](./common_event/commonEvent-window.md)
Indicates that the screen has been split. Indicates that the screen has been split.
- Value: **usual.event.SPLIT_SCREEN**
- Required subscriber permissions: none
## COMMON_EVENT_SLOT_CHANGE<sup>9+</sup> ## COMMON_EVENT_SLOT_CHANGE<sup>9+</sup>
...@@ -907,3 +905,5 @@ Indicates the result of applying a quick fix to the application. ...@@ -907,3 +905,5 @@ Indicates the result of applying a quick fix to the application.
Indicates that the user information has been updated. Indicates that the user information has been updated.
- Value: **usual.event.USER_INFO_UPDATED** - Value: **usual.event.USER_INFO_UPDATED**
- Required subscriber permissions: none - Required subscriber permissions: none
## [COMMON_EVENT_SMS_RECEIVE_COMPLETED](./common_event/commonEvent-mms.md)
Indicates that a new SMS message has been received.
...@@ -476,6 +476,9 @@ Indicates that the system starts charging the battery. ...@@ -476,6 +476,9 @@ Indicates that the system starts charging the battery.
## [COMMON_EVENT_CHARGE_TYPE_CHANGED](./common_event/commonEvent-powermgr.md) ## [COMMON_EVENT_CHARGE_TYPE_CHANGED](./common_event/commonEvent-powermgr.md)
Indicates that the system charging type has changed. This event is available only for system applications. Indicates that the system charging type has changed. This event is available only for system applications.
## [COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED](./common_event/commonEvent-powermgr.md)
Indicates that the device enters the charging idle mode.
## [COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED](./common_event/commonEvent-resourceschedule.md) ## [COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED](./common_event/commonEvent-resourceschedule.md)
Indicates that the system idle mode has changed. Indicates that the system idle mode has changed.
## [COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED<sup>10+<sup>](./common_event/commonEvent-resourceschedule.md) ## [COMMON_EVENT_DEVICE_IDLE_EXEMPTION_LIST_UPDATED<sup>10+<sup>](./common_event/commonEvent-resourceschedule.md)
......
...@@ -65,6 +65,14 @@ Indicates that the system charging type has changed. This event is available onl ...@@ -65,6 +65,14 @@ Indicates that the system charging type has changed. This event is available onl
When the system charging type changes, the event notification service is triggered to publish this event. When the system charging type changes, the event notification service is triggered to publish this event.
## COMMON_EVENT_CHARGE_IDLE_MODE_CHANGED
Indicates that the device enters the charging idle mode.
- Value: usual.event.CHARGE_IDLE_MODE_CHANGED
- Required subscriber permissions: none
When the device starts charging in idle mode, and the temperature rise is acceptable, the event notification service is triggered to publish this event.
## COMMON_EVENT_SHUTDOWN ## COMMON_EVENT_SHUTDOWN
Indicates that the device is being and will be shut down. Indicates that the device is being and will be shut down.
......
...@@ -31,6 +31,8 @@ import config from '@ohos.accessibility.config'; ...@@ -31,6 +31,8 @@ import config from '@ohos.accessibility.config';
| shortkeyTarget | [Config](#config)\<string>| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.| | shortkeyTarget | [Config](#config)\<string>| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.|
| captions | [Config](#config)\<boolean>| Yes| Yes| Whether to enable captions.| | captions | [Config](#config)\<boolean>| Yes| Yes| Whether to enable captions.|
| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| | captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.|
| audioMono| [Config](#config)\<boolean>| Yes| Yes| Whether to enable mono audio. The value **True** means to enable mono audio, and **False** means the opposite.|
| audioBalance| [Config](#config)\<number>| Yes| Yes| Audio balance for the left and right audio channels. The value ranges from -1.0 to 1.0.|
## enableAbility ## enableAbility
......
...@@ -137,11 +137,11 @@ Describes the style of captions. ...@@ -137,11 +137,11 @@ Describes the style of captions.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| --------------- | ---------------------------------------- | ---- | ---- | ----------- | | --------------- | ---------------------------------------- | ---- | ---- | ----------- |
| fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of captions. | | fontFamily | [CaptionsFontFamily](#captionsfontfamily8) | Yes | No | Font family of captions. |
| fontScale | number | Yes | No | Font scale of captions.| | fontScale | number | Yes | No | Font scale factor of captions, in percentage. The value ranges from 1 to 200.|
| fontColor | number \| string | Yes | No | Font color of captions. | | fontColor | number \| string | Yes | No | Font color of captions. For example, red corresponds to #FF0000. |
| fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of captions. | | fontEdgeType | [CaptionsFontEdgeType](#captionsfontedgetype8) | Yes | No | Font edge type of captions. |
| backgroundColor | number \| string | Yes | No | Background color of captions. | | backgroundColor | number \| string | Yes | No | Background color of captions. For example, red corresponds to #FF0000. |
| windowColor | number \| string | Yes | No | Window color of captions. | | windowColor | number \| string | Yes | No | Window color of captions. For example, red corresponds to #FF0000. |
## CaptionsManager<sup>8+</sup> ## CaptionsManager<sup>8+</sup>
...@@ -162,6 +162,8 @@ on(type: 'enableChange', callback: Callback&lt;boolean&gt;): void; ...@@ -162,6 +162,8 @@ on(type: 'enableChange', callback: Callback&lt;boolean&gt;): void;
Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -188,6 +190,8 @@ on(type: 'styleChange', callback: Callback&lt;CaptionsStyle&gt;): void; ...@@ -188,6 +190,8 @@ on(type: 'styleChange', callback: Callback&lt;CaptionsStyle&gt;): void;
Enables listening for captions style changes. This API uses an asynchronous callback to return the result. Enables listening for captions style changes. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -216,6 +220,8 @@ off(type: 'enableChange', callback?: Callback&lt;boolean&gt;): void; ...@@ -216,6 +220,8 @@ off(type: 'enableChange', callback?: Callback&lt;boolean&gt;): void;
Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -242,6 +248,8 @@ off(type: 'styleChange', callback?: Callback&lt;CaptionsStyle&gt;): void; ...@@ -242,6 +248,8 @@ off(type: 'styleChange', callback?: Callback&lt;CaptionsStyle&gt;): void;
Disables listening for captions style changes. This API uses an asynchronous callback to return the result. Disables listening for captions style changes. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Hearing
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -573,7 +581,7 @@ on(type: 'accessibilityStateChange', callback: Callback&lt;boolean&gt;): void ...@@ -573,7 +581,7 @@ on(type: 'accessibilityStateChange', callback: Callback&lt;boolean&gt;): void
Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters** **Parameters**
...@@ -600,7 +608,7 @@ on(type: 'touchGuideStateChange', callback: Callback&lt;boolean&gt;): void ...@@ -600,7 +608,7 @@ on(type: 'touchGuideStateChange', callback: Callback&lt;boolean&gt;): void
Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision
**Parameters** **Parameters**
...@@ -627,13 +635,13 @@ off(type: 'accessibilityStateChange', callback?: Callback&lt;boolean&gt;): void ...@@ -627,13 +635,13 @@ off(type: 'accessibilityStateChange', callback?: Callback&lt;boolean&gt;): void
Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------- | ---- | ---------------------------------------- | | -------- | ----------------------- | ---- | ---------------------------------------- |
| type | string | No | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| | type | string | Yes | Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.|
| callback | Callback&lt;boolean&gt; | No | Callback for the event. | | callback | Callback&lt;boolean&gt; | No | Callback for the event. |
**Example** **Example**
...@@ -654,13 +662,13 @@ off(type: 'touchGuideStateChange', callback?: Callback&lt;boolean&gt;): void ...@@ -654,13 +662,13 @@ off(type: 'touchGuideStateChange', callback?: Callback&lt;boolean&gt;): void
Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------- | ---- | ---------------------------------------- | | -------- | ----------------------- | ---- | ---------------------------------------- |
| type | string | No | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| | type | string | Yes | Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.|
| callback | Callback&lt;boolean&gt; | No | Callback for the event. | | callback | Callback&lt;boolean&gt; | No | Callback for the event. |
**Example** **Example**
......
...@@ -64,8 +64,14 @@ Enumerates the reasons for the last exit. You can use it together with [onCreate ...@@ -64,8 +64,14 @@ Enumerates the reasons for the last exit. You can use it together with [onCreate
| Name | Value | Description | | Name | Value | Description |
| ----------------------------- | ---- | ------------------------------------------------------------ | | ----------------------------- | ---- | ------------------------------------------------------------ |
| UNKNOWN | 0 | Unknown reason.| | UNKNOWN | 0 | Unknown reason.|
| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| | ABILITY_NOT_RESPONDING | 1 | The ability does not respond. This enum is supported since API version 9 and deprecated since API version 10. You are advised to use **APP_FREEZE**.|
| NORMAL | 2 | The ability exits normally.| | NORMAL | 2 | The ability exits normally because the user closes the application.|
| CPP_CRASH<sup>10+</sup> | 3 | The ability exits due to abnormal signals on the local host.|
| JS_ERROR<sup>10+</sup> | 4 | The ability exits due to a JS_ERROR fault triggered when an application has a JS syntax error that is not captured by developers.|
| APP_FREEZE<sup>10+</sup> | 5 | The ability exits because watchdog detects that the application is frozen.|
| PERFORMANCE_CONTROL<sup>10+</sup> | 6 | The ability exits due to system performance problems, for example, insufficient device memory.|
| RESOURCE_CONTROL<sup>10+</sup> | 7 | The ability exits because the system resource usage (CPU, I/O, or memory usage) exceeds the upper limit.|
| UPGRADE<sup>10+</sup> | 8 | The ability exits due to an update.|
**Example** **Example**
...@@ -218,3 +224,24 @@ class MyAbility extends UIAbility { ...@@ -218,3 +224,24 @@ class MyAbility extends UIAbility {
} }
} }
``` ```
## AbilityConstant.ContinueState<sup>10+</sup>
Enumerates the mission continuation states of the application. It is used in the [setMissionContinueState](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10) API of [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md).
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
| Name | Value | Description |
| ------------- | --------- | ------------------------------------------------------------ |
| ACTIVE | 0 | Mission continuation is activated for the current application. |
| INACTIVE | 1 | Mission continuation is not activated for the current application. |
**Example**
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => {
console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
});
```
# @ohos.account.appAccount.AuthorizationExtensionAbility (App AuthorizationExtensionAbility)
The **AuthorizationExtensionAbility** module provides APIs for implementing authorization to app accounts based on the ExtensionAbility framework.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import AuthorizationExtensionAbility, { AuthorizationRequest, AuthorizationCallback } from '@ohos.account.appAccount.AuthorizationExtensionAbility';
```
## AuthorizationRequest
Defines the app account authorization request.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Readable| Writable| Description |
| --------- | ------------------------------- | ---- | ---- | ------------------------------------ |
| callerUid | number | Yes | No | UID of the caller.|
| parameters | [appAccount.AccountCapabilityRequest](js-apis-appAccount.md#accountcapabilityrequest10) | Yes | No | Service parameters.|
## AuthorizationCallback
Provides callbacks to be invoked during the app account authorization.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Readable| Writable| Description |
| --------- | ------------------------------- | ---- | ---- | ------------------------------------ |
| onResult | AsyncCallback<[appAccount.AccountCapabilityResponse](js-apis-appAccount.md#accountcapabilityresponse10), { [key: string]: object }> | Yes | No | Callback invoked to return the authorization result.|
## AuthorizationExtensionAbility.onStartAuthorization
onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback): void
Called when an authorization request is received.
**System API**: This is a system API.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------- |
| request | [AuthorizationRequest](#authorizationrequest) | Yes | Authorization request information.|
| callback | [AuthorizationCallback](#authorizationcallback) | Yes | Authorization callback object.|
**Example**
```ts
class MyAuthorizationExtensionAbility extends AuthorizationExtensionAbility {
onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback) {
console.log('onStartAuthorization, callerUid: ' + request.callerUid + ', parameters: ' + request.parameters);
let response = {
name: 'xxxx',
scopes: ['xxx', 'xxx']
};
callback.onResult(null, response);
}
};
```
...@@ -132,7 +132,7 @@ Creates an app account with custom data. This API uses a promise to return the r ...@@ -132,7 +132,7 @@ Creates an app account with custom data. This API uses a promise to return the r
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the app account to create. | | name | string | Yes | Name of the app account to create. |
| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).<br>By default, no value is passed, which means no additional information needs to be added for the account.| | options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens). <br>By default, no value is passed, which means no additional information needs to be added for the account.|
**Return value** **Return value**
...@@ -730,7 +730,7 @@ Sets a credential for an app account. This API uses an asynchronous callback to ...@@ -730,7 +730,7 @@ Sets a credential for an app account. This API uses an asynchronous callback to
| ID| Error Message| | ID| Error Message|
| ------- | -------| | ------- | -------|
| 12300001 | System service exception. | | 12300001 | System service exception. |
| 12300002 | Invalid name or credentialType or credential. | | 12300002 | Invalid name, credentialType, or credential. |
| 12300003 | Account not found. | | 12300003 | Account not found. |
**Example** **Example**
...@@ -776,7 +776,7 @@ Sets a credential for an app account. This API uses a promise to return the resu ...@@ -776,7 +776,7 @@ Sets a credential for an app account. This API uses a promise to return the resu
| ID| Error Message| | ID| Error Message|
| ------- | -------| | ------- | -------|
| 12300001 | System service exception. | | 12300001 | System service exception. |
| 12300002 | Invalid name or credentialType or credential. | | 12300002 | Invalid name, credentialType, or credential. |
| 12300003 | Account not found. | | 12300003 | Account not found. |
**Example** **Example**
...@@ -2780,7 +2780,7 @@ Adds an app account name and additional information. This API uses an asynchrono ...@@ -2780,7 +2780,7 @@ Adds an app account name and additional information. This API uses an asynchrono
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- | | --------- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| extraInfo | string | No | Additional information (information that can be converted to the string type).<br>The additional information cannot be sensitive information (such as the password and token) of the app account.<br>By default, no value is passed, which means no additional information needs to be added for the account.| | extraInfo | string | No | Additional information (information that can be converted to the string type). <br>The additional information cannot be sensitive information (such as the password and token) of the app account.<br>By default, no value is passed, which means no additional information needs to be added for the account.|
**Return value** **Return value**
...@@ -4982,3 +4982,298 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. ...@@ -4982,3 +4982,298 @@ Obtains the remote object of an authenticator. This API cannot be overloaded.
} }
} }
``` ```
## AccountCapabilityType<sup>10+</sup>
Enumerates the account capability types.
**System capability**: SystemCapability.Account.AppAccount
| Name | Value | Description |
| ---------------- | ----- | ----------------------- |
| AUTHORIZATION | 1 | Authorization capability. |
## AccountCapabilityProvider<sup>10+</sup>
Represents the **AccountCapabilityProvider** class.
### Attributes
**System capability**: SystemCapability.Account.AppAccount
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes| No| Capability type of the account.|
### constructor<sup>10+</sup>
constructor(capabilityType: AccountCapabilityType)
A constructor used to create an **AccountCapabilityProvider** instance.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- |
| capabilityType | [AccountCapabilityType](#accountcapabilitytype10) | Yes | Capability type of the account. |
**Example**
```ts
class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
constructor() {
super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
}
}
try {
let provider = new MyAuthorizationProvider();
if (provider instanceof account_appAccount.AccountCapabilityProvider) {
console.log("the provider is an instance of AccountCapabilityProvider");
}
} catch (err) {
console.error('catch error: ' + JSON.stringify(err));
}
```
## AccountCapabilityRequest<sup>10+</sup>
Represents the **AccountCapabilityRequest** class.
### constructor<sup>10+</sup>
constructor(provider: AccountCapabilityProvider)
A constructor used to create an **AccountCapabilityRequest** instance.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- |
| provider | [AccountCapabilityProvider](#accountcapabilityprovider10) | Yes | Provider of the account capability. |
**Example**
```ts
class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
constructor() {
super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
}
}
class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest {
constructor() {
let provider = new MyAuthorizationProvider();
super(provider);
}
}
try {
let request = new MyAuthorizationRequest();
if (request instanceof account_appAccount.AccountCapabilityRequest) {
console.log("the request is an instance of AccountCapabilityRequest");
}
} catch (err) {
console.error('catch error: ' + JSON.stringify(err));
}
```
## AccountCapabilityResponse<sup>10+</sup>
Represents the **AccountCapabilityResponse** class.
### Attributes
**System capability**: SystemCapability.Account.AppAccount
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes| No| Account capability request corresponding to the response.|
### constructor<sup>10+</sup>
constructor(request: AccountCapabilityRequest)
A constructor used to create an **AccountCapabilityResponse** instance.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- |
| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request corresponding to the response.|
**Example**
```ts
class MyAuthorizationProvider extends account_appAccount.AccountCapabilityProvider {
constructor() {
super(account_appAccount.AccountCapabilityType.AUTHORIZATION);
}
}
class MyAuthorizationRequest extends account_appAccount.AccountCapabilityRequest {
constructor() {
let provider = new MyAuthorizationProvider();
super(provider);
}
}
class MyAuthorizationResponse extends account_appAccount.AccountCapabilityResponse {
constructor(request) {
super(request)
}
}
try {
let request = new MyAuthorizationRequest();
let response = new MyAuthorizationResponse(request);
if (response instanceof account_appAccount.AccountCapabilityResponse) {
console.log("the response is an instance of AccountCapabilityResponse");
}
} catch (err) {
console.error('catch error: ' + JSON.stringify(err));
}
```
## AuthorizationProviderInfo<sup>10+</sup>
Defines information about the authorization provider.
**System capability**: SystemCapability.Account.AppAccount
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | --- | ---------- |
| bundleName | string | Yes| No| Bundle name of the authorization provider.|
| abilityName | string | Yes| No| Ability name of the authorization provider.|
## AuthorizationProvider<sup>10+</sup>
Represents the **AuthorizationProvider** class.
### constructor<sup>10+</sup>
constructor(info: AuthorizationProviderInfo)
A constructor used to create an **AuthorizationProvider** instance.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- |
| info | [AuthorizationProviderInfo](#authorizationproviderinfo10) | Yes | Information about the authorization provider.|
**Example**
```ts
class MyAuthorizationProvider extends account_appAccount.AuthorizationProvider {
constructor() {
super({bundleName: 'xxx', abilityName: 'xxx'});
}
}
try {
let provider = new MyAuthorizationProvider();
if (provider instanceof account_appAccount.AuthorizationProvider) {
console.log("the provider is an instance of AuthorizationProvider");
}
} catch (err) {
console.error("catch error: " + JSON.stringify(err));
}
```
## AccountCapabilityScheduler<sup>10+</sup>
Represents the **AccountCapabilityScheduler** class.
### executeRequest<sup>10+</sup>
executeRequest(request: AccountCapabilityRequest, callback: AsyncCallback&lt;AccountCapabilityResponse, { [key: string]: object }&gt;): void
Executes an account capability request. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------------------------- | ---- | ------------------------- |
| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute. |
| callback | AsyncCallback&lt;[AccountCapabilityResponse](#accountcapabilityresponse10), { [key: string]: object }&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. |
**Error codes**
| ID| Error Message|
| ------- | ------- |
| 12300001 | System service exception. |
| 12300002 | Invalid request. |
**Example**
```ts
let scheduler = new account_appAccount.AccountCapabilityScheduler();
let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' });
let request = new account_appAccount.AccountCapabilityRequest(provider);
try {
scheduler.executeRequest(request, (err, response) => {
if (err != null) {
console.log('executeRequest failed, error: ' + JSON.stringify(err));
} else {
console.log('executeRequest response: ' + JSON.stringify(response));
}
});
} catch (err) {
console.log('executeRequest exception: ' + JSON.stringify(err));
}
```
### executeRequest<sup>10+</sup>
executeRequest(request: AccountCapabilityRequest): Promise&lt;AccountCapabilityResponse&gt;
Executes an account capability request. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------- | ---- | ------------ |
| request | [AccountCapabilityRequest](#accountcapabilityrequest10) | Yes | Account capability request to execute.|
**Return value**
| Type | Description |
| ------------------- | --------------------- |
| Promise&lt;[AccountCapabilityResponse](#accountcapabilityresponse10)&gt; | Promise used to return the result. |
**Error codes**
| ID| Error Message|
| ------- | ------- |
| 12300001 | System service exception. |
| 12300002 | Invalid request. |
**Example**
```ts
let scheduler = new account_appAccount.AccountCapabilityScheduler();
let provider = new account_appAccount.AuthorizationProvider({ bundleName: 'xxx', abilityName: 'xxx' });
let request = new account_appAccount.AccountCapabilityRequest(provider);
try {
scheduler.executeRequest(request).then((response) => {
console.log('executeRequest response: ' + JSON.stringify(response));
}).catch((err) => {
console.log('executeRequest failed, error: ' + JSON.stringify(err));
});
} catch (err) {
console.log('executeRequest exception: ' + JSON.stringify(err));
}
```
# @ohos.application.DataShareExtensionAbility (DataShare Extension Ability) # @ohos.application.DataShareExtensionAbility (DataShare ExtensionAbility)
The **DataShareExtensionAbility** module provides data share services based on the Extension ability. The **DataShareExtensionAbility** module provides data share services based on the ExtensionAbility.
>**NOTE** >**NOTE**
> >
...@@ -23,7 +23,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili ...@@ -23,7 +23,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| | context<sup>10+</sup> | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|DataShareExtensionAbility context, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).|
## onCreate ## onCreate
...@@ -215,7 +215,7 @@ Queries data from the database. This API can be overridden as required. ...@@ -215,7 +215,7 @@ Queries data from the database. This API can be overridden as required.
| uri | string | Yes | URI of the data to query.| | uri | string | Yes | URI of the data to query.|
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.|
| columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is empty, all columns will be queried.| | columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is empty, all columns will be queried.|
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback invoked to return the result set.| | callback | AsyncCallback&lt;Object&gt; | Yes| Callback invoked to return the result set obtained.|
**Example** **Example**
...@@ -275,18 +275,17 @@ let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS ' ...@@ -275,18 +275,17 @@ let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
let rdbStore; let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
batchInsert(uri, valueBuckets, callback) { batchInsert(uri, valueBuckets, callback) {
if (valueBuckets === null || valueBuckets.length === undefined) { if (valueBuckets === null || valueBuckets.length === undefined) {
console.error('invalid valueBuckets'); console.error('invalid valueBuckets');
return; return;
}
rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) {
if (callback !== undefined) {
callback(err, ret);
}
});
});
} }
rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) {
if (callback !== undefined) {
callback(err, ret);
}
});
};
}; };
``` ```
......
...@@ -20,6 +20,7 @@ import bundleManager from '@ohos.bundle.bundleManager'; ...@@ -20,6 +20,7 @@ import bundleManager from '@ohos.bundle.bundleManager';
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.| | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.|
| ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle. | | ohos.permission.REMOVE_CACHE_FILES | system_basic | Permission to clear cache files of a bundle. |
|ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | Permission to enable or disable an application or ability. | |ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | Permission to enable or disable an application or ability. |
| ohos.permission.GET_INSTALLED_BUNDLE_LIST | system_basic | Permission to read installed application list.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
...@@ -115,7 +116,7 @@ Enumerates the types of Extension abilities. ...@@ -115,7 +116,7 @@ Enumerates the types of Extension abilities.
| PRINT<sup>10+</sup> | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.| | PRINT<sup>10+</sup> | 15 | PrintExtensionAbility: provides APIs for printing images. Printing documents is not supported yet.|
| PUSH<sup>10+</sup> | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved.| | PUSH<sup>10+</sup> | 17 | PushExtensionAbility: provides APIs for pushing scenario-specific messages. This ability is reserved.|
| DRIVER<sup>10+</sup> | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.| | DRIVER<sup>10+</sup> | 18 | DriverExtensionAbility: provides APIs for the peripheral driver. This type of ability is not supported yet.|
| APP_ACCOUNT_AUTHORIZATION<sup>10+</sup> | 19 | AuthorizationExtensionAbility: provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.| | APP_ACCOUNT_AUTHORIZATION<sup>10+</sup> | 19 | [AuthorizationExtensionAbility](js-apis-appAccount-authorizationExtensionAbility.md): provides APIs to process authorization requests for application accounts and allow account authorization from a third-party (relative to the operating system vendor) ecosystem platform.|
| UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.| | UNSPECIFIED | 255 | No type is specified. It is used together with **queryExtensionAbilityInfo** to query all types of Extension abilities.|
...@@ -677,7 +678,7 @@ Obtains the information about all bundles based on the given bundle flags and us ...@@ -677,7 +678,7 @@ Obtains the information about all bundles based on the given bundle flags and us
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -726,7 +727,7 @@ Obtains the information about all bundles based on the given bundle flags. This ...@@ -726,7 +727,7 @@ Obtains the information about all bundles based on the given bundle flags. This
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -765,7 +766,7 @@ Obtains the information about all bundles based on the given bundle flags and us ...@@ -765,7 +766,7 @@ Obtains the information about all bundles based on the given bundle flags and us
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -816,7 +817,7 @@ Obtains the information about all applications based on the given application fl ...@@ -816,7 +817,7 @@ Obtains the information about all applications based on the given application fl
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -865,7 +866,7 @@ Obtains the information about all applications based on the given application fl ...@@ -865,7 +866,7 @@ Obtains the information about all applications based on the given application fl
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -904,7 +905,7 @@ Obtains the information about all applications based on the given application fl ...@@ -904,7 +905,7 @@ Obtains the information about all applications based on the given application fl
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Required permissions**: ohos.permission.GET_INSTALLED_BUNDLE_LIST
**System capability**: SystemCapability.BundleManager.BundleFramework.Core **System capability**: SystemCapability.BundleManager.BundleFramework.Core
...@@ -1752,7 +1753,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return ...@@ -1752,7 +1753,7 @@ Enables or disables an ability. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ------------------------------------- | | -------- | ----------- | ---- | ------------------------------------- |
| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. |
| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| | isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -1814,7 +1815,7 @@ Enables or disables an ability. This API uses a promise to return the result. ...@@ -1814,7 +1815,7 @@ Enables or disables an ability. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | ------------------------------------- | | -------- | ----------- | ---- | ------------------------------------- |
| info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. | | info | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes | Information about the target ability. |
| isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the ability.| | isEnabled| boolean | Yes | Whether to enable the ability. The value **true** means to enable the ability, and **false** means to disable the application.|
**Return value** **Return value**
...@@ -3213,3 +3214,129 @@ try { ...@@ -3213,3 +3214,129 @@ try {
hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message); hilog.error(0x0000, 'testTag', 'getAppProvisionInfo failed. Cause: %{public}s', err.message);
} }
``` ```
### bundleManager.getSpecifiedDistributionType<sup>10+</sup>
getSpecifiedDistributionType(bundleName: string): string;
Obtains the distribution type of a bundle in synchronous mode. The return value is the **specifiedDistributionType** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ----------------------------------- | ---- | ---------------------------- |
| bundleName | string | Yes | Bundle name.|
**Return value**
| Type | Description |
| ------------- | -------------------------------------- |
| string | Distribution type of the bundle.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17700001 | The specified bundleName is not found. |
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
let bundleName = "com.example.myapplication";
try {
let type = bundleManager.getSpecifiedDistributionType(bundleName);
console.info('getSpecifiedDistributionType successfully, type:' + type);
} catch (error) {
console.error('getSpecifiedDistributionType failed. Cause: ' + error.message);
}
```
### bundleManager.getAdditionalInfo<sup>10+</sup>
getAdditionalInfo(bundleName: string): string;
Obtains additional information about a bundle in synchronous mode. The return value is the **additionalInfo** field value in [InstallParam](./js-apis-installer.md#installparam) passed when **install** is called.
**System API**: This is a system API.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ----------------------------------- | ---- | ---------------------------- |
| bundleName | string | Yes | Bundle name.|
**Return value**
| Type | Description |
| ------------- | -------------------------------------- |
| string | Additional information about the bundle.|
**Error codes**
For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17700001 | The specified bundleName is not found. |
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
let bundleName = "com.example.myapplication";
try {
let info = bundleManager.getAdditionalInfo(bundleName);
console.info('getAdditionalInfo successfully, additionInfo:' + info);
} catch (error) {
console.error('getAdditionalInfo failed. Cause: ' + error.message);
}
```
### bundleManager.getBundleInfoForSelfSync<sup>10+</sup>
getBundleInfoForSelfSync(bundleFlags: number): BundleInfo;
Obtains the bundle information of this bundle based on the given bundle flags in synchronous mode.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | --------------------- |
| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.|
**Return value**
| Type | Description |
| ------------------------------------------------- | -------------------- |
| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.|
**Example**
```ts
import bundleManager from '@ohos.bundle.bundleManager';
import hilog from '@ohos.hilog';
let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION;
try {
let data = bundleManager.getBundleInfoForSelfSync(bundleFlags);
hilog.info(0x0000, 'testTag', 'getBundleInfoForSelfSync successfully: %{public}s', JSON.stringify(data));
} catch (err) {
hilog.error(0x0000, 'testTag', 'getBundleInfoForSelfSync failed: %{public}s', err.message);
}
```
...@@ -25,9 +25,9 @@ Implements initialization for the interpolation curve, which is used to create a ...@@ -25,9 +25,9 @@ Implements initialization for the interpolation curve, which is used to create a
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----------------------------------------------- | ---- | ----------------------------------- | | ------ | --------------- | ---- | ----------------------------------- |
| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.<br>Default value: **Curve.Linear**| | curve | [Curve](#curve) | No | Curve type.<br>Default value: **Curve.Linear**|
**Return value** **Return value**
...@@ -35,6 +35,28 @@ Implements initialization for the interpolation curve, which is used to create a ...@@ -35,6 +35,28 @@ Implements initialization for the interpolation curve, which is used to create a
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Interpolation curve.| | [ICurve](#icurve) | Interpolation curve.|
## Curve
Since API version 9, this API is supported in ArkTS widgets.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Description: |
| ------------------- | ------------------------------------------------------------ |
| Linear | The animation speed keeps unchanged. |
| Ease | The animation starts slowly, accelerates, and then slows down towards the end. The cubic-bezier curve (0.25, 0.1, 0.25, 1.0) is used.|
| EaseIn | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used. |
| EaseOut | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used. |
| EaseInOut | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.|
| FastOutSlowIn | The animation uses the standard cubic-bezier curve (0.4, 0.0, 0.2, 1.0). |
| LinearOutSlowIn | The animation uses the deceleration cubic-bezier curve (0.0, 0.0, 0.2, 1.0). |
| FastOutLinearIn | The animation uses the acceleration cubic-bezier curve (0.4, 0.0, 1.0, 1.0). |
| ExtremeDeceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0). |
| Sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0). |
| Rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0). |
| Smooth | The animation uses the smooth cubic-bezier curve (0.4, 0.0, 0.4, 1.0). |
| Friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0). |
**Example** **Example**
```ts ```ts
...@@ -153,14 +175,14 @@ Creates a spring animation curve. If multiple spring animations are applied to t ...@@ -153,14 +175,14 @@ Creates a spring animation curve. If multiple spring animations are applied to t
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| response | number | No | Duration of one complete oscillation.<br>Default value: **0.55**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.| | response | number | No | Duration of one complete oscillation.<br>Default value: **0.55**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.|
| dampingFraction | number | No | Damping coefficient.<br>**0**: undamped. In this case, the spring oscillates forever.<br>> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.<br>**1**: critically damped.<br>> 1: overdamped. In this case, the spring approaches equilibrium gradually.<br>Default value: **0.825**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.| | dampingFraction | number | No | Damping coefficient.<br>**0**: undamped. In this case, the spring oscillates forever.<br>> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.<br>**1**: critically damped.<br>> 1: overdamped. In this case, the spring approaches equilibrium gradually.<br>Default value: **0.825**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.|
| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.<br><br>Default value: **0**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0**.<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| | overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, the **response** values of these animations will transit smoothly over this duration if they are different.<br>Default value: **0**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0**.<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the **interpolate** function of the curve.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Curve.<br>**NOTE**<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **interpolate** function of the curve.| | [ICurve](#icurve)| Curve.<br>**NOTE**<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). The time cannot be normalized. Therefore, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.|
**Example** **Example**
...@@ -187,13 +209,13 @@ Creates a responsive spring animation curve. It is a special case of [springMoti ...@@ -187,13 +209,13 @@ Creates a responsive spring animation curve. It is a special case of [springMoti
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| response | number | No | See **response** in **springMotion**.<br>Default value: **0.15**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.15**.| | response | number | No | See **response** in **springMotion**.<br>Default value: **0.15**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.15**.|
| dampingFraction | number | No | See **dampingFraction** in **springMotion**.<br>Default value: **0.86**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.86**.| | dampingFraction | number | No | See **dampingFraction** in **springMotion**.<br>Default value: **0.86**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.86**.|
| overlapDuration | number | No | See **overlapDuration** in **springMotion**.<br>Default value: **0.25**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.25**.<br> To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained by using the **interpolate** function of the curve.| | overlapDuration | number | No | See **overlapDuration** in **springMotion**.<br>Default value: **0.25**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.25**.<br> To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in [animation](../arkui-ts/ts-animatorproperty.md) or [animateTo](../arkui-ts/ts-explicit-animation.md). In addition, the interpolation cannot be obtained using the **interpolate** function of the curve. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Curve.<br>**NOTE**<br>1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate9) function of the curve.| | [ICurve](#icurve)| Curve.<br>**NOTE**<br>1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained using the [interpolate](#interpolate9) function of the curve.|
**Example** **Example**
...@@ -310,9 +332,9 @@ Implements initialization to create a curve. This API is deprecated since API ve ...@@ -310,9 +332,9 @@ Implements initialization to create a curve. This API is deprecated since API ve
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----------------------------------------------- | ---- | ----------------------------------- | | ------ | --------------- | ---- | ----------------------------------- |
| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve type.<br>Default value: **Curve.Linear**| | curve | [Curve](#curve) | No | Curve type.<br>Default value: **Curve.Linear**|
## Curves.steps<sup>(deprecated)</sup> ## Curves.steps<sup>(deprecated)</sup>
......
...@@ -49,10 +49,10 @@ Describes a rectangle on the display. ...@@ -49,10 +49,10 @@ Describes a rectangle on the display.
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| ------ | -------- | ---- | ---- | ------------------ | | ------ | -------- | ---- | ---- | ------------------ |
| left | number | Yes | Yes | Left boundary of the rectangle, in pixels.| | left | number | Yes | Yes | Left boundary of the rectangle, in pixels. The value must be an integer.|
| top | number | Yes | Yes | Top boundary of the rectangle, in pixels.| | top | number | Yes | Yes | Top boundary of the rectangle, in pixels. The value must be an integer.|
| width | number | Yes | Yes | Width of the rectangle, in pixels. | | width | number | Yes | Yes | Width of the rectangle, in pixels. The value must be an integer. |
| height | number | Yes | Yes | Height of the rectangle, in pixels. | | height | number | Yes | Yes | Height of the rectangle, in pixels. The value must be an integer. |
## WaterfallDisplayAreaRects<sup>9+</sup> ## WaterfallDisplayAreaRects<sup>9+</sup>
...@@ -196,7 +196,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo ...@@ -196,7 +196,7 @@ Checks whether there is a visible privacy window on a display. The privacy windo
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------------------------- | ---- |----------| | ------ | ------------------------- | ---- |----------|
| id | number | Yes | ID of the display.| | id | number | Yes | ID of the display. The value must be an integer.|
**Return value** **Return value**
...@@ -248,10 +248,10 @@ Subscribes to display changes. ...@@ -248,10 +248,10 @@ Subscribes to display changes.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |---------------------------------------------------------------------------------------------------------------------------------|
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event. Example: event that a display is connected.<br>- **remove**, indicating the display removal event. Example: event that a display is disconnected.<br>- **change**, indicating the display change event. Example: event that the display orientation is changed.| | type | string | Yes| Event type.<br>- **add**, indicating the display addition event. Example: event that a display is connected.<br>- **remove**, indicating the display removal event. Example: event that a display is disconnected.<br>- **change**, indicating the display change event. Example: event that the display orientation is changed.|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.| | callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display, which is an integer. |
**Example** **Example**
...@@ -279,7 +279,7 @@ Unsubscribes from display changes. ...@@ -279,7 +279,7 @@ Unsubscribes from display changes.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type.<br>- **add**, indicating the display addition event. Example: event that a display is connected.<br>- **remove**, indicating the display removal event. Example: event that a display is disconnected.<br>- **change**, indicating the display change event. Example: event that the display orientation is changed.| | type | string | Yes| Event type.<br>- **add**, indicating the display addition event. Example: event that a display is connected.<br>- **remove**, indicating the display removal event. Example: event that a display is disconnected.<br>- **change**, indicating the display change event. Example: event that the display orientation is changed.|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.| | callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display, which is an integer.|
**Example** **Example**
...@@ -335,7 +335,7 @@ Unsubscribes from privacy mode changes of this display. When there is a privacy ...@@ -335,7 +335,7 @@ Unsubscribes from privacy mode changes of this display. When there is a privacy
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- |------------------------------------------| ---- | ------------------------------------------------------- | | -------- |------------------------------------------| ---- | ------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'privateModeChange'**, indicating the event of display private mode changes.| | type | string | Yes | Event type. The value is fixed at **'privateModeChange'**, indicating the event of display privacy mode changes.|
| callback | Callback&lt;boolean&gt; | No | Callback used to return whether the privacy mode of the display is changed. The value **true** means that the display changes to the privacy mode, and **false** means the opposite.| | callback | Callback&lt;boolean&gt; | No | Callback used to return whether the privacy mode of the display is changed. The value **true** means that the display changes to the privacy mode, and **false** means the opposite.|
**Example** **Example**
...@@ -479,22 +479,22 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg ...@@ -479,22 +479,22 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |---------------------------------------------------------------------------------------------------------------|
| id | number | Yes| No| ID of the display.| | id | number | Yes| No| ID of the display. The value must be an integer. |
| name | string | Yes| No| Name of the display.| | name | string | Yes| No| Name of the display. |
| alive | boolean | Yes| No| Whether the display is alive.| | alive | boolean | Yes| No| Whether the display is alive. |
| state | [DisplayState](#displaystate) | Yes| No| State of the display.| | state | [DisplayState](#displaystate) | Yes| No| State of the display. |
| refreshRate | number | Yes| No| Refresh rate of the display.| | refreshRate | number | Yes| No| Refresh rate of the display. The value must be an integer. |
| rotation | number | Yes| No| Screen rotation angle of the display.<br>The value **0** indicates that the screen of the display rotates by 0°.<br>The value **1** indicates that the screen of the display rotates by 90°.<br>The value **2** indicates that the screen of the display rotates by 180°.<br>The value **3** indicates that the screen of the display rotates by 270°.| | rotation | number | Yes| No| Screen rotation angle of the display.<br>The value **0** indicates that the screen of the display rotates by 0°.<br>The value **1** indicates that the screen of the display rotates by 90°.<br>The value **2** indicates that the screen of the display rotates by 180°.<br>The value **3** indicates that the screen of the display rotates by 270°.|
| width | number | Yes| No| Width of the display, in pixels.| | width | number | Yes| No| Width of the display, in pixels. The value must be an integer. |
| height | number | Yes| No| Height of the display, in pixels.| | height | number | Yes| No| Height of the display, in pixels. The value must be an integer. |
| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| | densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. The value must be a floating point number. Generally, the value is **160.0** or **480.0**. |
| orientation<sup>10+</sup> | [Orientation](#orientation10) | Yes| No| Orientation of the display.| | orientation<sup>10+</sup> | [Orientation](#orientation10) | Yes| No| Orientation of the display. |
| densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. Generally, the value is **1** or **3**.| | densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. The value must be a floating point number. Generally, the value is **1.0** or **3.0**. |
| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. Generally, the value is the same as that of **densityPixels**.| | scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. The value must be a floating point number. Generally, the value is the same as that of **densityPixels**. |
| xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| | xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction. The value must be a floating point number. |
| yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| | yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction. The value must be a floating point number. |
### getCutoutInfo<sup>9+</sup> ### getCutoutInfo<sup>9+</sup>
getCutoutInfo(callback: AsyncCallback&lt;CutoutInfo&gt;): void getCutoutInfo(callback: AsyncCallback&lt;CutoutInfo&gt;): void
......
...@@ -241,6 +241,14 @@ Obtains the focus element. This API uses an asynchronous callback to return the ...@@ -241,6 +241,14 @@ Obtains the focus element. This API uses an asynchronous callback to return the
| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus. | | isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus. |
| callback | AsyncCallback&lt;AccessibilityElement&gt; | Yes | Callback used to return the current focus element.| | callback | AsyncCallback&lt;AccessibilityElement&gt; | Yes | Callback used to return the current focus element.|
**Error codes**
For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md).
| ID | Error Message |
| ------- | ---------------------------------------- |
| 9300003 | Do not have accessibility right for this operation. |
**Example** **Example**
```ts ```ts
......
...@@ -10,7 +10,7 @@ Provides the bundle information of an application. ...@@ -10,7 +10,7 @@ Provides the bundle information of an application.
**System capability**: SystemCapability.Notification.Notification **System capability**: SystemCapability.Notification.Notification
| Name | Type | Read-only| Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ---- | ------ | | ------ | ------ | ------ | ------ |
| bundle | string | No | Yes| Bundle information of the application.| | bundle | string | Yes| Bundle information of the application.|
| uid | number | No | No| User ID.| | uid | number | No| User ID.|
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册