提交 b738fad7 编写于 作者: J jiaoyanlin3

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

# AI # AI
- [Using MindSpore Lite for Model Inference (JS)](mindspore-lite-js-guidelines.md) - [AI Development](ai-overview.md)
- [Using MindSpore Lite JavaScript APIs to Develop AI Applications](mindspore-guidelines-based-js.md)
- [Using MindSpore Lite Native APIs to Develop AI Applications](mindspore-guidelines-based-native.md)
# AI Development
## Overview
OpenHarmony provides native distributed AI capabilities. The AI subsystem consists of the following components:
- MindSpore Lite: an AI inference framework that provides unified APIs for AI inference.
- Neural Network Runtime (NNRt): an intermediate bridge that connects the inference framework and AI hardware.
## MindSpore Lite
MindSpore Lite is a built-in AI inference framework of OpenHarmony. It provides AI model inference capabilities for different hardware devices and end-to-end AI model inference solutions for developers to empower intelligent applications in all scenarios. Currently, MindSpore Lite has been widely used in applications such as image classification, target recognition, facial recognition, and character recognition.
**Figure 1** Development process for MindSpore Lite model inference
![MindSpore workflow](figures/mindspore_workflow.png)
The MindSpore Lite development process consists of two phases:
- Model conversion
MindSpore Lite uses models in `.ms` format for inference. You can use the model conversion tool provided by MindSpore Lite to convert third-party framework models, such as TensorFlow, TensorFlow Lite, Caffe, and ONNX, into `.ms` models. For details, see [Converting Models for Inference](https://www.mindspore.cn/lite/docs/en/r1.8/use/converter_tool.html).
- Model inference
You can call the MindSpore Lite runtime APIs to implement model inference. The procedure is as follows:
1. Create an inference context by setting the inference hardware and number of threads.
2. Load the **.ms** model file.
3. Set the model input data.
4. Perform model inference, and read the output.
MindSpore Lite is built in the OpenHarmony standard system as a system component. You can develop AI applications based on MindSpore Lite in the following ways:
- Method 1: [Using MindSpore Lite JavaScript APIs to develop AI applications](./mindspore-guidelines-based-js.md). You directly call MindSpore Lite JavaScript APIs in the UI code to load the AI model and perform model inference. An advantage of this method is the quick verification of the inference effect.
- Method 2: [Using MindSpore Lite native APIs to develop AI applications](./mindspore-guidelines-based-native.md). You encapsulate the algorithm models and the code for calling MindSpore Lite native APIs into a dynamic library, and then use N-API to encapsulate the dynamic library into JavaScript APIs for the UI to call.
## Neural Network Runtime
Neural Network Runtime (NNRt) functions as a bridge to connect the upper-layer AI inference framework and bottom-layer acceleration chip, implementing cross-chip inference computing of AI models.
MindSpore Lite supports configuration of the NNRt backend, and therefore you can directly configure MindSpore Lite to use the NNRt hardware. The focus of this topic is about how to develop AI applications using MindSpore Lite. For details about how to use NNRt, see [Connecting the Neural Network Runtime to an AI Inference Framework](../napi/neural-network-runtime-guidelines.md).
# Using MindSpore Lite for Model Inference (JS) # Using MindSpore Lite JavaScript APIs to Develop AI Applications
## Scenarios ## 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. You can use the JavaScript APIs provided by MindSpore Lite to directly integrate MindSpore Lite capabilities into the UI code. This way, you can quickly deploy AI algorithms for AI model inference.
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 ## Basic Concepts
...@@ -27,16 +25,14 @@ APIs involved in MindSpore Lite model inference are categorized into context API ...@@ -27,16 +25,14 @@ APIs involved in MindSpore Lite model inference are categorized into context API
## How to Develop ## How to Develop
The development process consists of the following main steps: Assume that you have prepared a model in the **.ms** format. The key steps in model inference are model reading, model building, model inference, and memory release. The development procedure is described as follows:
1. Create a context, and set parameters such as the number of runtime threads and device type.
2. Load the model. In this example, the model is read from the file.
3. Load data. Before executing a model, you need to obtain the model input and then fill data in the input tensor.
4. Perform model inference by calling **predict**, and read the output.
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 ```js
@State inputName: string = 'mnet_caffemodel_nhwc.bin'; @State inputName: string = 'mnet_caffemodel_nhwc.bin';
@State T_model_predict: string = 'Test_MSLiteModel_predict' @State T_model_predict: string = 'Test_MSLiteModel_predict'
...@@ -49,7 +45,6 @@ build() { ...@@ -49,7 +45,6 @@ build() {
.fontSize(30) .fontSize(30)
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
.onClick(async () => { .onClick(async () => {
// 1. Prepare for a model.
let syscontext = globalThis.context; let syscontext = globalThis.context;
syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => { syscontext.resourceManager.getRawFileContent(this.inputName).then((buffer) => {
this.inputBuffer = buffer; this.inputBuffer = buffer;
...@@ -57,20 +52,24 @@ build() { ...@@ -57,20 +52,24 @@ build() {
}).catch(error => { }).catch(error => {
console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.'); console.error('Failed to get buffer, error code: ${error.code},message:${error.message}.');
}) })
// 2. Create a context.
// 1. Create a context.
let context: mindSporeLite.Context = {}; let context: mindSporeLite.Context = {};
context.target = ['cpu']; context.target = ['cpu'];
context.cpu = {} context.cpu = {}
context.cpu.threadNum = 1; context.cpu.threadNum = 1;
context.cpu.threadAffinityMode = 0; context.cpu.threadAffinityMode = 0;
context.cpu.precisionMode = 'enforce_fp32'; context.cpu.precisionMode = 'enforce_fp32';
// 3. Load the model.
// 2. Load the model.
let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms'; let modelFile = '/data/storage/el2/base/haps/entry/files/mnet.caffemodel.ms';
let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context); let msLiteModel = await mindSporeLite.loadModelFromFile(modelFile, context);
// 4. Load data.
// 3. Set the input data.
const modelInputs = msLiteModel.getInputs(); const modelInputs = msLiteModel.getInputs();
modelInputs[0].setData(this.inputBuffer.buffer); modelInputs[0].setData(this.inputBuffer.buffer);
// 5. Perform inference and print the output.
// 4. Perform inference and print the output.
console.log('=========MSLITE predict start=====') console.log('=========MSLITE predict start=====')
msLiteModel.predict(modelInputs).then((modelOutputs) => { msLiteModel.predict(modelInputs).then((modelOutputs) => {
let output0 = new Float32Array(modelOutputs[0].getData()); let output0 = new Float32Array(modelOutputs[0].getData());
...@@ -89,21 +88,21 @@ build() { ...@@ -89,21 +88,21 @@ build() {
## Debugging and Verification ## 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: 1. On DevEco Studio, connect to the device, click **Run entry**, and compile your own HAP. The following information is displayed:
```shell ```shell
Launching com.example.myapptfjs Launching com.example.myapptfjs
$ hdc uninstall 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 install -r "path/to/xxx.hap"
$ hdc shell aa start -a EntryAbility -b com.example.myapptfjs $ 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. 2. Use hdc to connect to the device, 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 ```shell
hdc -t 7001005458323933328a00bcdf423800 file send .\mnet.caffemodel.ms /data/app/el2/100/base/com.example.myapptfjs/haps/entry/files/ hdc -t your_device_id 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: 3. Click **Test\_MSLiteModel\_predict** on the device screen to run the test case. The following information is displayed in the HiLog printing result:
```shell ```shell
08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start===== 08-27 23:25:50.278 31782-31782/? I C03d00/JSAPP: =========MSLITE predict start=====
......
# Using MindSpore Lite Native APIs to Develop AI Applications
## Scenarios
You can use the native APIs provided by MindSpore Lite to deploy AI algorithms and provides APIs for the UI layer to invoke the algorithms for model inference. A typical scenario is the AI SDK development.
## Basic concepts
- [N-API](../reference/native-lib/third_party_napi/napi.md): a set of native APIs used to build JavaScript components. N-APIs can be used to encapsulate libraries developed using C/C++ into JavaScript modules.
## Preparing the Environment
- Install DevEco Studio 3.1.0.500 or later, and update the SDK to API version 10 or later.
## How to Develop
1. Create a native C++ project.
Open DevEco Studio, choose **File** > **New** > **Create Project** to create a native C++ template project. By default, the **entry/src/main/** directory of the created project contains the **cpp/** directory. You can store C/C++ code in this directory and provide JavaScript APIs for the UI layer to call the code.
2. Compile the C++ inference code.
Assume that you have prepared a model in the **.ms** format.
Before using the Native APIs provided by MindSpore Lite for development, you need to reference the corresponding header files.
```c
#include <mindspore/model.h>
#include <mindspore/context.h>
#include <mindspore/status.h>
#include <mindspore/tensor.h>
```
(1). Read model files.
```C++
void *ReadModelFile(NativeResourceManager *nativeResourceManager, const std::string &modelName, size_t *modelSize) {
auto rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, modelName.c_str());
if (rawFile == nullptr) {
LOGE("Open model file failed");
return nullptr;
}
long fileSize = OH_ResourceManager_GetRawFileSize(rawFile);
void *modelBuffer = malloc(fileSize);
if (modelBuffer == nullptr) {
LOGE("Get model file size failed");
}
int ret = OH_ResourceManager_ReadRawFile(rawFile, modelBuffer, fileSize);
if (ret == 0) {
LOGI("Read model file failed");
OH_ResourceManager_CloseRawFile(rawFile);
return nullptr;
}
OH_ResourceManager_CloseRawFile(rawFile);
*modelSize = fileSize;
return modelBuffer;
}
```
(2). Create a context, set parameters such as the number of threads and device type, and load the model.
```c++
OH_AI_ModelHandle CreateMSLiteModel(void *modelBuffer, size_t modelSize) {
// Create a context.
auto context = OH_AI_ContextCreate();
if (context == nullptr) {
DestroyModelBuffer(&modelBuffer);
LOGE("Create MSLite context failed.\n");
return nullptr;
}
auto cpu_device_info = OH_AI_DeviceInfoCreate(OH_AI_DEVICETYPE_CPU);
OH_AI_ContextAddDeviceInfo(context, cpu_device_info);
// Load the .ms model file.
auto model = OH_AI_ModelCreate();
if (model == nullptr) {
DestroyModelBuffer(&modelBuffer);
LOGE("Allocate MSLite Model failed.\n");
return nullptr;
}
auto build_ret = OH_AI_ModelBuild(model, modelBuffer, modelSize, OH_AI_MODELTYPE_MINDIR, context);
DestroyModelBuffer(&modelBuffer);
if (build_ret != OH_AI_STATUS_SUCCESS) {
OH_AI_ModelDestroy(&model);
LOGE("Build MSLite model failed.\n");
return nullptr;
}
LOGI("Build MSLite model success.\n");
return model;
}
```
(3). Set the model input data, perform model inference, and obtain the output data.
```js
void RunMSLiteModel(OH_AI_ModelHandle model) {
// Set the model input data.
auto inputs = OH_AI_ModelGetInputs(model);
FillInputTensors(inputs);
auto outputs = OH_AI_ModelGetOutputs(model);
// Perform inference and print the output.
auto predict_ret = OH_AI_ModelPredict(model, inputs, &outputs, nullptr, nullptr);
if (predict_ret != OH_AI_STATUS_SUCCESS) {
OH_AI_ModelDestroy(&model);
LOGE("Predict MSLite model error.\n");
return;
}
LOGI("Run MSLite model success.\n");
LOGI("Get model outputs:\n");
for (size_t i = 0; i < outputs.handle_num; i++) {
auto tensor = outputs.handle_list[i];
LOGI("- Tensor %{public}d name is: %{public}s.\n", static_cast<int>(i), OH_AI_TensorGetName(tensor));
LOGI("- Tensor %{public}d size is: %{public}d.\n", static_cast<int>(i), (int)OH_AI_TensorGetDataSize(tensor));
auto out_data = reinterpret_cast<const float *>(OH_AI_TensorGetData(tensor));
std::cout << "Output data is:";
for (int i = 0; (i < OH_AI_TensorGetElementNum(tensor)) && (i <= kNumPrintOfOutData); i++) {
std::cout << out_data[i] << " ";
}
std::cout << std::endl;
}
OH_AI_ModelDestroy(&model);
}
```
(4). Implement a complete model inference process.
```C++
static napi_value RunDemo(napi_env env, napi_callback_info info)
{
LOGI("Enter runDemo()");
GET_PARAMS(env, info, 2);
napi_value error_ret;
napi_create_int32(env, -1, &error_ret);
const std::string modelName = "ml_headpose.ms";
size_t modelSize;
auto resourcesManager = OH_ResourceManager_InitNativeResourceManager(env, argv[1]);
auto modelBuffer = ReadModelFile(resourcesManager, modelName, &modelSize);
if (modelBuffer == nullptr) {
LOGE("Read model failed");
return error_ret;
}
LOGI("Read model file success");
auto model = CreateMSLiteModel(modelBuffer, modelSize);
if (model == nullptr) {
OH_AI_ModelDestroy(&model);
LOGE("MSLiteFwk Build model failed.\n");
return error_ret;
}
RunMSLiteModel(model);
napi_value success_ret;
napi_create_int32(env, 0, &success_ret);
LOGI("Exit runDemo()");
return success_ret;
}
```
(5). Write the **CMake** script to link the MindSpore Lite dynamic library `libmindspore_lite_ndk.so`.
```cmake
cmake_minimum_required(VERSION 3.4.1)
project(OHOSMSLiteNapi)
set(NATIVERENDER_ROOT_PATH ${CMAKE_CURRENT_SOURCE_DIR})
include_directories(${NATIVERENDER_ROOT_PATH}
${NATIVERENDER_ROOT_PATH}/include)
add_library(mslite_napi SHARED mslite_napi.cpp)
target_link_libraries(mslite_napi PUBLIC mindspore_lite_ndk) # MindSpore Lite dynamic library to link
target_link_libraries(mslite_napi PUBLIC hilog_ndk.z)
target_link_libraries(mslite_napi PUBLIC rawfile.z)
target_link_libraries(mslite_napi PUBLIC ace_napi.z)
```
3. Use N-APIs to encapsulate C++ dynamic libraries into JavaScript modules.
Create the **libmslite_api/** subdirectory in **entry/src/main/cpp/types/**, and create the **index.d.ts** file in the subdirectory. The file content is as follows:
```js
export const runDemo: (a:String, b:Object) => number;
```
Use the preceding code to define the JavaScript API `runDemo()`.
In addition, add the **oh-package.json5** file to associate the API with the **.so** file to form a complete JavaScript module.
```json
{
"name": "libmslite_napi.so",
"types": "./index.d.ts"
}
```
4. Invoke the encapsulated MindSpore module in the UI code.
In **entry/src/ets/MainAbility/pages/index.ets**, define the **onClick()** event and call the encapsulated **runDemo()** API in the event callback.
```js
import msliteNapi from'libmslite_napi.so' // Import the msliteNapi module.
// Certain code omitted
// Trigger the event when the text on the UI is tapped.
.onClick(() => {
resManager.getResourceManager().then(mgr => {
hilog.info(0x0000, TAG, '*** Start MSLite Demo ***');
let ret = 0;
ret = msliteNapi.runDemo("", mgr); // Call runDemo() to perform AI model inference.
if (ret == -1) {
hilog.info(0x0000, TAG, 'Error when running MSLite Demo!');
}
hilog.info(0x0000, TAG, '*** Finished MSLite Demo ***');
})
})
```
## Debugging and Verification
On DevEco Studio, connect to the device and click **Run entry**. The following log is generated for the application process:
```text
08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Start MSLite Demo ***
08-08 16:55:33.766 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Enter runDemo()
08-08 16:55:33.772 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Read model file success
08-08 16:55:33.799 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Build MSLite model success.
08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Run MSLite model success.
08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Get model outputs:
08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 name is: output_node_0.
08-08 16:55:33.818 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: - Tensor 0 size is: 12.
08-08 16:55:33.826 1513-1529/com.mslite.native_demo I A00000/[MSLiteNapi]: Exit runDemo()
08-08 16:55:33.827 1513-1529/com.mslite.native_demo I A00000/MSLiteNativeDemo: *** Finished MSLite Demo ***
```
# Traffic Management
## Introduction
The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID).
Its functions include:
- Obtaining real-time traffic data by NIC or UID
- Obtaining historical traffic data by NIC or UID
- Subscribing to traffic change events by NIC or UID
> **NOTE**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md).
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Traffic Management](../reference/apis/js-apis-net-statistics.md).
| Type| API| Description|
| ---- | ---- | ---- |
| ohos.net.statistics | getIfaceRxBytes(nic: string, callback: AsyncCallback\<number>): void; |Obtains the real-time downlink data traffic of the specified NIC. |
| ohos.net.statistics | getIfaceTxBytes(nic: string, callback: AsyncCallback\<number>): void; |Obtains the real-time uplink data traffic of the specified NIC. |
| ohos.net.statistics | getCellularRxBytes(callback: AsyncCallback\<number>): void; |Obtains the real-time downlink data traffic of the cellular network.|
| ohos.net.statistics | getCellularTxBytes(callback: AsyncCallback\<number>): void; |Obtains the real-time uplink data traffic of the cellular network.|
| ohos.net.statistics | getAllRxBytes(callback: AsyncCallback\<number>): void; |Obtains the real-time downlink data traffic of the all NICs. |
| ohos.net.statistics | getAllTxBytes(callback: AsyncCallback\<number>): void; |Obtains the real-time uplink data traffic of the all NICs. |
| ohos.net.statistics | getUidRxBytes(uid: number, callback: AsyncCallback\<number>): void; |Obtains the real-time downlink data traffic of the specified application. |
| ohos.net.statistics | getUidTxBytes(uid: number, callback: AsyncCallback\<number>): void; |Obtains the real-time uplink data traffic of the specified application. |
| ohos.net.statistics | getTrafficStatsByIface(ifaceInfo: IfaceInfo, callback: AsyncCallback\<NetStatsInfo>): void; |Obtains the historical data traffic of the specified NIC. |
| ohos.net.statistics | getTrafficStatsByUid(uidInfo: UidInfo, callback: AsyncCallback\<NetStatsInfo>): void; |Obtains the historical data traffic of the specified application. |
| ohos.net.statistics | on(type: 'netStatsChange', callback: Callback\<{ iface: string, uid?: number }>): void |Subscribes to traffic change events.|
| ohos.net.statistics | off(type: 'netStatsChange', callback?: Callback\<{ iface: string, uid?: number }>): void; |Unsubscribes from traffic change events.|
## Obtaining Real-Time Traffic Data by NIC or UID
1. Obtain the real-time data traffic of the specified NIC.
2. Obtain the real-time data traffic of the cellular network.
3. Obtain the real-time data traffic of all NICs.
4. Obtain the real-time data traffic of the specified application.
```js
// Import the statistics namespace from @ohos.net.statistics.
import statistics from '@ohos.net.statistics'
// Obtain the real-time downlink data traffic of the specified NIC.
statistics.getIfaceRxBytes("wlan0", (error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time uplink data traffic of the specified NIC.
statistics.getIfaceTxBytes("wlan0", (error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time downlink data traffic of the cellular network.
statistics.getCellularRxBytes((error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time uplink data traffic of the cellular network.
statistics.getCellularTxBytes((error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time downlink data traffic of the all NICs.
statistics.getAllRxBytes((error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time uplink data traffic of the all NICs.
statistics.getAllTxBytes((error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time downlink data traffic of the specified application.
let uid = 20010038;
statistics.getUidRxBytes(uid, (error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
// Obtain the real-time uplink data traffic of the specified application.
let uid = 20010038;
statistics.getUidTxBytes(uid, (error, stats) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(stats))
})
```
## Obtaining Historical Traffic Data by NIC or UID
1. Obtain the historical data traffic of the specified NIC.
2. Obtain the historical data traffic of the specified application.
```js
let ifaceInfo = {
iface: "wlan0",
startTime: 1685948465,
endTime: 16859485670
}
// Obtain the historical data traffic of the specified NIC.
statistics.getTrafficStatsByIface(ifaceInfo), (error, statsInfo) => {
console.log(JSON.stringify(error))
console.log("getTrafficStatsByIface bytes of received = " + JSON.stringify(statsInfo.rxBytes));
console.log("getTrafficStatsByIface bytes of sent = " + JSON.stringify(statsInfo.txBytes));
console.log("getTrafficStatsByIface packets of received = " + JSON.stringify(statsInfo.rxPackets));
console.log("getTrafficStatsByIface packets of sent = " + JSON.stringify(statsInfo.txPackets));
});
let uidInfo = {
ifaceInfo: {
iface: "wlan0",
startTime: 1685948465,
endTime: 16859485670
},
uid: 20010037
}
// Obtain the historical data traffic of the specified application.
statistics.getTrafficStatsByUid(uidInfo), (error, statsInfo) => {
console.log(JSON.stringify(error))
console.log("getTrafficStatsByUid bytes of received = " + JSON.stringify(statsInfo.rxBytes));
console.log("getTrafficStatsByUid bytes of sent = " + JSON.stringify(statsInfo.txBytes));
console.log("getTrafficStatsByUid packets of received = " + JSON.stringify(statsInfo.rxPackets));
console.log("getTrafficStatsByUid packets of sent = " + JSON.stringify(statsInfo.txPackets));
});
```
## Subscribing to Traffic Change Events
1. Subscribe to traffic change events.
2. Unsubscribe from traffic change events.
```js
let callback = data => {
console.log("on netStatsChange, data:" + JSON.stringify(data));
}
// Subscribe to traffic change events.
statistics.on('netStatsChange', callback);
// Unsubscribe from traffic change events. You can pass the callback of the **on** function if you want to unsubscribe from a certain type of event. If you do not pass the callback, you will unsubscribe from all events.
statistics.off('netStatsChange', callback);
statistics.off('netStatsChange');
```
...@@ -40,7 +40,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -40,7 +40,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance. | | name | string | Yes | Name of the **Preferences** instance. |
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -159,15 +159,166 @@ class EntryAbility extends UIAbility { ...@@ -159,15 +159,166 @@ class EntryAbility extends UIAbility {
} }
``` ```
## data_preferences.getPreferences<sup>10+</sup>
getPreferences(context: Context, options: Options, callback: AsyncCallback&lt;Preferences&gt;): void
Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ------------------------------ |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
let preferences = null;
try {
data_preferences.getPreferences(context, {name: 'mystore'}, function (err, val) {
if (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
console.info("Obtained the preferences successfully.");
})
} catch (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
let preferences = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, val) {
if (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
console.info("Obtained the preferences successfully.");
})
} catch (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## data_preferences.getPreferences<sup>10+</sup>
getPreferences(context: Context, options: Options): Promise&lt;Preferences&gt;
Obtains a **Preferences** instance. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
**Return value**
| Type | Description |
| --------------------------------------- | ---------------------------------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the **Preferences** instance obtained.|
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ------------------------------ |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
let preferences = null;
try {
let promise = data_preferences.getPreferences(context, {name: 'mystore'});
promise.then((object) => {
preferences = object;
console.info("Obtained the preferences successfully.");
}).catch((err) => {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
let preferences = null;
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
let promise = data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'});
promise.then((object) => {
preferences = object;
console.info("Obtained the preferences successfully.");
}).catch((err) => {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## data_preferences.deletePreferences ## data_preferences.deletePreferences
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Deletes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result. Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.
If the **Preferences** instance has a persistent file, this API also deletes the persistent file. After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner.
The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -176,8 +327,8 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -176,8 +327,8 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -235,11 +386,9 @@ class EntryAbility extends UIAbility { ...@@ -235,11 +386,9 @@ class EntryAbility extends UIAbility {
deletePreferences(context: Context, name: string): Promise&lt;void&gt; deletePreferences(context: Context, name: string): Promise&lt;void&gt;
Deletes a **Preferences** instance from the memory. This API uses a promise to return the result. Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.
If the **Preferences** instance has a persistent file, this API also deletes the persistent file.
The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -248,7 +397,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -248,7 +397,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -306,13 +455,164 @@ class EntryAbility extends UIAbility { ...@@ -306,13 +455,164 @@ class EntryAbility extends UIAbility {
} }
``` ```
## data_preferences.deletePreferences<sup>10+</sup>
deletePreferences(context: Context, options: Options, callback: AsyncCallback&lt;void&gt;): void
Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result.
After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ---------------------------------- |
| 15500010 | Failed to delete preferences file. |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
data_preferences.deletePreferences(context, {name: 'mystore'}, function (err) {
if (err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Deleted the preferences successfully." );
})
} catch (err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
data_preferences.deletePreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err) {
if (err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Deleted the preferences successfully." );
})
} catch (err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## data_preferences.deletePreferences<sup>10+</sup>
deletePreferences(context: Context, options: Options): Promise&lt;void&gt;
Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result.
After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ---------------------------------- |
| 15500010 | Failed to delete preferences file. |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
let promise = data_preferences.deletePreferences(context, {name: 'mystore'});
promise.then(() => {
console.info("Deleted the preferences successfully.");
}).catch((err) => {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try{
let promise = data_preferences.deletePreferences(this.context, {name: 'mystore', dataGroupId:'myId'});
promise.then(() => {
console.info("Deleted the preferences successfully.");
}).catch((err) => {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to delete the preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## data_preferences.removePreferencesFromCache ## data_preferences.removePreferencesFromCache
removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result. Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result.
The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -321,8 +621,8 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -321,8 +621,8 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -332,17 +632,16 @@ FA model: ...@@ -332,17 +632,16 @@ FA model:
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { data_preferences.removePreferencesFromCache(context, 'mystore', function (err) {
if (err) { if (err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Removed the preferences successfully."); console.info("Removed the preferences successfully.");
}) })
} catch (err) { } catch (err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -356,17 +655,16 @@ class EntryAbility extends UIAbility { ...@@ -356,17 +655,16 @@ class EntryAbility extends UIAbility {
try { try {
data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
if (err) { if (err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Removed the preferences successfully."); console.info("Removed the preferences successfully.");
}) })
} catch (err) { } catch (err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
} }
} }
``` ```
## data_preferences.removePreferencesFromCache ## data_preferences.removePreferencesFromCache
...@@ -375,7 +673,9 @@ removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt; ...@@ -375,7 +673,9 @@ removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
Removes a **Preferences** instance from the cache. This API uses a promise to return the result. Removes a **Preferences** instance from the cache. This API uses a promise to return the result.
The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -384,7 +684,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -384,7 +684,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -400,16 +700,15 @@ FA model: ...@@ -400,16 +700,15 @@ FA model:
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); let promise = data_preferences.removePreferencesFromCache(context, 'mystore');
promise.then(() => { promise.then(() => {
console.info("Removed the preferences successfully."); console.info("Removed the preferences successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -425,10 +724,10 @@ class EntryAbility extends UIAbility { ...@@ -425,10 +724,10 @@ class EntryAbility extends UIAbility {
promise.then(() => { promise.then(() => {
console.info("Removed the preferences successfully."); console.info("Removed the preferences successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
console.info("Failed to remove the preferences. code =" + err.code + ", message =" + err.message); console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
} }
} }
} }
...@@ -440,7 +739,9 @@ removePreferencesFromCacheSync(context: Context, name: string): void ...@@ -440,7 +739,9 @@ removePreferencesFromCacheSync(context: Context, name: string): void
Synchronously removes a **Preferences** instance from the cache. Synchronously removes a **Preferences** instance from the cache.
The deleted **Preferences** instance cannot be used to perform data operations. Otherwise, data inconsistency will be caused. After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -459,7 +760,6 @@ FA model: ...@@ -459,7 +760,6 @@ FA model:
// Obtain the context. // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext(); let context = featureAbility.getContext();
try { try {
data_preferences.removePreferencesFromCacheSync(context, 'mystore'); data_preferences.removePreferencesFromCacheSync(context, 'mystore');
} catch(err) { } catch(err) {
...@@ -483,6 +783,164 @@ class EntryAbility extends UIAbility { ...@@ -483,6 +783,164 @@ class EntryAbility extends UIAbility {
} }
``` ```
## data_preferences.removePreferencesFromCache<sup>10+</sup>
removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback&lt;void&gt;): void
Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result.
After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ------------------------------ |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
data_preferences.removePreferencesFromCache(context, {name: 'mystore'}, function (err) {
if (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Removed the preferences successfully.");
})
} catch (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
data_preferences.removePreferencesFromCache(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err) {
if (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
console.info("Removed the preferences successfully.");
})
} catch (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## data_preferences.removePreferencesFromCache<sup>10+</sup>
removePreferencesFromCache(context: Context, options: Options): Promise&lt;void&gt;
Removes a **Preferences** instance from the cache. This API uses a promise to return the result.
After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance.
After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | ------------------------------ |
| 15501001 | Only supported in stage mode. |
| 15501002 | The data group id is not valid. |
**Example**
FA model:
```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
try {
let promise = data_preferences.removePreferencesFromCache(context, {name: 'mystore'});
promise.then(() => {
console.info("Removed the preferences successfully.");
}).catch((err) => {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
try {
let promise = data_preferences.removePreferencesFromCache(this.context, {name: 'mystore', dataGroupId:'myId'});
promise.then(() => {
console.info("Removed the preferences successfully.");
}).catch((err) => {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
})
} catch(err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
}
}
```
## Options<sup>10+</sup>
Represents the configuration options of a **Preferences** instance.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name | Type | Mandatory| Description |
| ----------- | ------ | ---- | ------------------------------------------------------------ |
| name | string | Yes | Name of the **Preferences** instance. |
| dataGroupId | string | No | Application group ID, which needs to be obtained from the AppGallery.<br>**Model restriction**: This attribute can be used only in the stage model.<br>This parameter is supported since API version 10. It specifies the **Preferences** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **Preferences** instance is created in the sandbox directory of the application.|
## Preferences ## Preferences
Provides APIs for obtaining and modifying the stored data. Provides APIs for obtaining and modifying the stored data.
...@@ -504,7 +962,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ...@@ -504,7 +962,7 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to obtain. It cannot be empty. | | key | string | Yes | Key of the data to obtain. It cannot be empty. |
| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| | defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| callback | AsyncCallback&lt;[ValueType](#valuetype)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is** undefined** and **data** is the value obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[ValueType](#valuetype)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the value obtained. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -512,13 +970,13 @@ Obtains the value corresponding to the specified key from the cached **Preferenc ...@@ -512,13 +970,13 @@ Obtains the value corresponding to the specified key from the cached **Preferenc
try { try {
preferences.get('startup', 'default', function (err, val) { preferences.get('startup', 'default', function (err, val) {
if (err) { if (err) {
console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Obtained the value of 'startup' successfully. val: " + val); console.info("Obtained the value of 'startup' successfully. val: " + val);
}) })
} catch (err) { } catch (err) {
console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -552,10 +1010,10 @@ try { ...@@ -552,10 +1010,10 @@ try {
promise.then((data) => { promise.then((data) => {
console.info("Got the value of 'startup'. Data: " + data); console.info("Got the value of 'startup'. Data: " + data);
}).catch((err) => { }).catch((err) => {
console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
}) })
} catch(err) { } catch(err) {
console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -587,7 +1045,7 @@ try { ...@@ -587,7 +1045,7 @@ try {
let value = preferences.getSync('startup', 'default'); let value = preferences.getSync('startup', 'default');
console.info("Obtained the value of 'startup'. Data: " + value); console.info("Obtained the value of 'startup'. Data: " + value);
} catch(err) { } catch(err) {
console.info("Failed to obtain the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain value of 'startup'. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -603,7 +1061,7 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an ...@@ -603,7 +1061,7 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;Object&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** provides all KV pairs obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;Object&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** provides all KV pairs obtained. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -611,7 +1069,7 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an ...@@ -611,7 +1069,7 @@ Obtains all KV pairs from the cached **Preferences** instance. This API uses an
try { try {
preferences.getAll(function (err, value) { preferences.getAll(function (err, value) {
if (err) { if (err) {
console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
return; return;
} }
let allKeys = Object.keys(value); let allKeys = Object.keys(value);
...@@ -619,7 +1077,7 @@ try { ...@@ -619,7 +1077,7 @@ try {
console.info("getAll object = " + JSON.stringify(value)); console.info("getAll object = " + JSON.stringify(value));
}) })
} catch (err) { } catch (err) {
console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -648,10 +1106,10 @@ try { ...@@ -648,10 +1106,10 @@ try {
console.info('getAll keys = ' + allKeys); console.info('getAll keys = ' + allKeys);
console.info("getAll object = " + JSON.stringify(value)); console.info("getAll object = " + JSON.stringify(value));
}).catch((err) => { }).catch((err) => {
console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
}) })
} catch (err) { } catch (err) {
console.info("Failed to get all KV pairs. code =" + err.code + ", message =" + err.message); console.info("Failed to obtain all KV pairs. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -659,7 +1117,7 @@ try { ...@@ -659,7 +1117,7 @@ try {
getAllSync(): Object getAllSync(): Object
Synchronously obtains all KV pairs from the cached **Preferences** instance. Obtains all KV pairs from the cached **Preferences** instance synchronously.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core **System capability**: SystemCapability.DistributedDataManager.Preferences.Core
...@@ -696,7 +1154,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou ...@@ -696,7 +1154,7 @@ Writes data to the cached **Preferences** instance. This API uses an asynchronou
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data. It cannot be empty. | | key | string | Yes | Key of the data. It cannot be empty. |
| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| | value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If data is written successfully, **err** is **undefined**. Otherwise, **err** is an error object. |
**Example** **Example**
...@@ -707,7 +1165,7 @@ try { ...@@ -707,7 +1165,7 @@ try {
console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Put the value of 'startup' successfully."); console.info("Successfully put the value of 'startup'.");
}) })
} catch (err) { } catch (err) {
console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message); console.info("Failed to put the value of 'startup'. code =" + err.code + ", message =" + err.message);
...@@ -742,7 +1200,7 @@ Writes data to the cached **Preferences** instance. This API uses a promise to r ...@@ -742,7 +1200,7 @@ Writes data to the cached **Preferences** instance. This API uses a promise to r
try { try {
let promise = preferences.put('startup', 'auto'); let promise = preferences.put('startup', 'auto');
promise.then(() => { promise.then(() => {
console.info("Put the value of 'startup' successfully."); console.info("Successfully put the value of 'startup'.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message); console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
}) })
...@@ -773,7 +1231,7 @@ Synchronously writes data to the cached **Preferences** instance. You can use [f ...@@ -773,7 +1231,7 @@ Synchronously writes data to the cached **Preferences** instance. You can use [f
try { try {
preferences.putSync('startup', 'auto'); preferences.putSync('startup', 'auto');
} catch(err) { } catch(err) {
console.info("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); console.info("Failed to put the value of 'startup'. code =" + err.code +", message =" + err.message);
} }
``` ```
...@@ -903,7 +1361,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie ...@@ -903,7 +1361,7 @@ Deletes a KV pair from the cached **Preferences** instance based on the specifie
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------------- |
| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | | key | string | Yes | Key of the KV pair to delete. It cannot be empty. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -995,7 +1453,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file. ...@@ -995,7 +1453,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -1006,7 +1464,7 @@ try { ...@@ -1006,7 +1464,7 @@ try {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message); console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Flushed data successfully."); console.info("Successfully flushed data.");
}) })
} catch (err) { } catch (err) {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message); console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
...@@ -1034,7 +1492,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file. ...@@ -1034,7 +1492,7 @@ Flushes the data in the cached **Preferences** instance to the persistent file.
try { try {
let promise = preferences.flush(); let promise = preferences.flush();
promise.then(() => { promise.then(() => {
console.info("Flushed data successfully."); console.info("Successfully flushed data.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message); console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
}) })
...@@ -1056,7 +1514,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr ...@@ -1056,7 +1514,7 @@ Clears all data in the cached **Preferences** instance. This API uses an asynchr
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -1067,7 +1525,7 @@ try { ...@@ -1067,7 +1525,7 @@ try {
console.info("Failed to clear data. code =" + err.code + ", message =" + err.message); console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
return; return;
} }
console.info("Cleared data successfully."); console.info("Successfully cleared data.");
}) })
} catch (err) { } catch (err) {
console.info("Failed to clear data. code =" + err.code + ", message =" + err.message); console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
...@@ -1095,7 +1553,7 @@ Clears all data in the cached **Preferences** instance. This API uses a promise ...@@ -1095,7 +1553,7 @@ Clears all data in the cached **Preferences** instance. This API uses a promise
try { try {
let promise = preferences.clear(); let promise = preferences.clear();
promise.then(() => { promise.then(() => {
console.info("Cleared data successfully."); console.info("Successfully cleared data.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to clear data. code =" + err.code + ", message =" + err.message); console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
}) })
...@@ -1119,7 +1577,7 @@ Synchronously clears all data in the cached **Preferences** instance. You can us ...@@ -1119,7 +1577,7 @@ Synchronously clears all data in the cached **Preferences** instance. You can us
try { try {
preferences.clearSync(); preferences.clearSync();
} catch(err) { } catch(err) {
console.info("Failed to clear. code =" + err.code + ", message =" + err.message); console.info("Failed to clear data. code =" + err.code + ", message =" + err.message);
} }
``` ```
...@@ -1157,14 +1615,14 @@ try { ...@@ -1157,14 +1615,14 @@ try {
console.info("Failed to put the value of 'startup'. Cause: " + err); console.info("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Put the value of 'startup' successfully."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush(function (err) {
if (err) { if (err) {
console.info("Failed to flush data. Cause: " + err); console.info("Failed to flush data. Cause: " + err);
return; return;
} }
console.info("Flushed data successfully."); console.info("Successfully flushed data.");
}) })
}) })
}) })
...@@ -1173,6 +1631,125 @@ try { ...@@ -1173,6 +1631,125 @@ try {
} }
``` ```
### on('multiProcessChange')<sup>10+</sup>
on(type: 'multiProcessChange', callback: Callback&lt;{ key : string }&gt;): void
Subscribes to inter-process data changes. For the multiple processes holding the same preference file, if the value of the subscribed key changes in any process, the callback in this API will be invoked after [flush()](#flush) is executed.
This API can be used with [removePreferencesFromCache](#data_preferencesremovepreferencesfromcache) to update the **Preferences** instance in the callback when detecting that a process updates a file. For details, see example 2.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | -------------------------------------------------------------- |
| type | string | Yes | Event type. The value is **multiProcessChange**, which indicates data changes between multiple processes.|
| callback | Callback&lt;{ key : string }&gt; | Yes | Callback invoked to return data changes. |
**Error codes**
For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md).
| ID| Error Message |
| -------- | -------------------------------------- |
| 15500019 | Failed to obtain subscription service. |
**Example 1**
```js
try {
data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, preferences) {
if (err) {
console.info("Failed to obtain the preferences.");
return;
}
let observer = function (key) {
console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.put('startup', 'manual', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
})
})
})
} catch (err) {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
}
```
**Example 2**
```js
let preferences = null;
try {
data_preferences.getPreferences(this.context, { name: 'mystore' }, function (err, val) {
if (err) {
console.info("Failed to obtain the preferences.");
return;
}
preferences = val;
let observer = function (key) {
console.info("The key " + key + " changed.");
try {
data_preferences.removePreferencesFromCache(context, { name: 'mystore' }, function (err) {
if (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = null;
console.info("Removed the preferences successfully.");
})
} catch (err) {
console.info("Failed to remove preferences. code =" + err.code + ", message =" + err.message);
}
try {
data_preferences.getPreferences(context, { name: 'mystore' }, function (err, val) {
if (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
return;
}
preferences = val;
console.info("Obtained the preferences successfully.");
})
} catch (err) {
console.info("Failed to obtain the preferences. code =" + err.code + ", message =" + err.message);
}
}
preferences.on('multiProcessChange', observer);
preferences.put('startup', 'manual', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
})
})
})
} catch (err) {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
}
```
### off('change') ### off('change')
...@@ -1186,7 +1763,7 @@ Unsubscribes from data changes. ...@@ -1186,7 +1763,7 @@ Unsubscribes from data changes.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ------------------------------------------ | | -------- | -------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | | type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. |
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks for all data changes will be unregistered.| | callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, the callbacks for all data changes will be unregistered.|
**Example** **Example**
...@@ -1207,14 +1784,14 @@ try { ...@@ -1207,14 +1784,14 @@ try {
console.info("Failed to put the value of 'startup'. Cause: " + err); console.info("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Put the value of 'startup' successfully."); console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) { preferences.flush(function (err) {
if (err) { if (err) {
console.info("Failed to flush data. Cause: " + err); console.info("Failed to flush data. Cause: " + err);
return; return;
} }
console.info("Flushed data successfully."); console.info("Successfully flushed data.");
}) })
preferences.off('change', observer); preferences.off('change', observer);
}) })
...@@ -1224,6 +1801,55 @@ try { ...@@ -1224,6 +1801,55 @@ try {
} }
``` ```
### off('multiProcessChange')<sup>10+</sup>
off(type: 'multiProcessChange', callback?: Callback&lt;{ key : string }&gt;): void
Unsubscribes from inter-process data changes.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | -------------------------------------------------------------- |
| type | string | Yes | Event type. The value is **multiProcessChange**, which indicates data changes between multiple processes.|
| callback | Callback&lt;{ key : string }&gt; | No | Callback to unregister. If this parameter is left blank, all callbacks for **multiProcessChange** will be unregistered. |
**Example**
```js
try {
data_preferences.getPreferences(this.context, {name: 'mystore', dataGroupId:'myId'}, function (err, preferences) {
if (err) {
console.info("Failed to obtain the preferences.");
return;
}
let observer = function (key) {
console.info("The key " + key + " changed.");
}
preferences.on('multiProcessChange', observer);
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err);
return;
}
console.info("Successfully put the value of 'startup'.");
preferences.flush(function (err) {
if (err) {
console.info("Failed to flush data. Cause: " + err);
return;
}
console.info("Successfully flushed data.");
})
preferences.off('multiProcessChange', observer);
})
})
} catch (err) {
console.info("Failed to flush data. code =" + err.code + ", message =" + err.message);
}
```
## ValueType ## ValueType
Enumerates the value types. Enumerates the value types.
...@@ -1237,4 +1863,4 @@ Enumerates the value types. ...@@ -1237,4 +1863,4 @@ Enumerates the value types.
| boolean | The value is of Boolean type. | | boolean | The value is of Boolean type. |
| Array\<number> | The value is an array of numbers. | | Array\<number> | The value is an array of numbers. |
| Array\<boolean> | The value is a Boolean array. | | Array\<boolean> | The value is a Boolean array. |
| Array\<string> | The value is an array of the strings.| | Array\<string> | The value is an array of strings.|
# @ohos.data.relationalStore (RDB Store) # @ohos.data.relationalStore (RDB Store)
The relational database (RDB) store manages data based on relational models. The RDB store provides a complete mechanism for managing local databases based on the underlying SQLite. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The worker threads are not supported. The relational database (RDB) store manages data based on relational models. It provides a complete mechanism for managing local databases based on the underlying SQLite. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The worker threads are not supported.
The **relationalStore** module provides the following functions: The **relationalStore** module provides the following functions:
...@@ -43,6 +43,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -43,6 +43,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| 14800010 | Failed to open or delete database by invalid database path. | | 14800010 | Failed to open or delete database by invalid database path. |
| 14800011 | Failed to open database by database corrupted. | | 14800011 | Failed to open database by database corrupted. |
| 14800000 | Inner error. | | 14800000 | Inner error. |
| 14801001 | Only supported in stage mode. |
| 14801002 | The data group id is not valid. |
**Example** **Example**
...@@ -127,6 +129,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -127,6 +129,8 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
| 14800010 | Failed to open or delete database by invalid database path. | | 14800010 | Failed to open or delete database by invalid database path. |
| 14800011 | Failed to open database by database corrupted. | | 14800011 | Failed to open database by database corrupted. |
| 14800000 | Inner error. | | 14800000 | Inner error. |
| 14801001 | Only supported in stage mode. |
| 14801002 | The data group id is not valid. |
**Example** **Example**
...@@ -184,6 +188,8 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&g ...@@ -184,6 +188,8 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&g
Deletes an RDB store. This API uses an asynchronous callback to return the result. Deletes an RDB store. This API uses an asynchronous callback to return the result.
After the deletion, you are advised to set the database object to null.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
...@@ -218,6 +224,7 @@ relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) { ...@@ -218,6 +224,7 @@ relationalStore.deleteRdbStore(context, "RdbTest.db", function (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return; return;
} }
store = null;
console.info(`Delete RdbStore successfully.`); console.info(`Delete RdbStore successfully.`);
}) })
``` ```
...@@ -234,6 +241,7 @@ class EntryAbility extends UIAbility { ...@@ -234,6 +241,7 @@ class EntryAbility extends UIAbility {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return; return;
} }
store = null;
console.info(`Delete RdbStore successfully.`); console.info(`Delete RdbStore successfully.`);
}) })
} }
...@@ -246,6 +254,8 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt; ...@@ -246,6 +254,8 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
Deletes an RDB store. This API uses a promise to return the result. Deletes an RDB store. This API uses a promise to return the result.
After the deletion, you are advised to set the database object to null.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
...@@ -282,6 +292,7 @@ let context = featureAbility.getContext(); ...@@ -282,6 +292,7 @@ let context = featureAbility.getContext();
let promise = relationalStore.deleteRdbStore(context, "RdbTest.db"); let promise = relationalStore.deleteRdbStore(context, "RdbTest.db");
promise.then(()=>{ promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`); console.info(`Delete RdbStore successfully.`);
}).catch((err) => { }).catch((err) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
...@@ -297,6 +308,162 @@ class EntryAbility extends UIAbility { ...@@ -297,6 +308,162 @@ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db");
promise.then(()=>{ promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
}).catch((err) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
}
}
```
## relationalStore.deleteRdbStore<sup>10+</sup>
deleteRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback\<void>): void
Deletes an RDB store. This API uses an asynchronous callback to return the result.
After the deletion, you are advised to set the database object to null. If the database file is in the public sandbox directory, you must use this API to delete the database. If the database is accessed by multiple processes at the same time, you are advised to send a database deletion notification to other processes.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800000 | Inner error. |
| 14801001 | Only supported in stage mode. |
| 14801002 | The data group id is not valid. |
**Example**
FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext()
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.deleteRdbStore(context, STORE_CONFIG, function (err) {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
store = null;
console.info(`Delete RdbStore successfully.`);
})
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.deleteRdbStore(this.context, STORE_CONFIG, function (err) {
if (err) {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
return;
}
store = null;
console.info(`Delete RdbStore successfully.`);
})
}
}
```
## relationalStore.deleteRdbStore<sup>10+</sup>
deleteRdbStore(context: Context, config: StoreConfig): Promise\<void>
Deletes an RDB store. This API uses a promise to return the result.
After the deletion, you are advised to set the database object to null. If the database file is in the public sandbox directory, you must use this API to delete the database. If the database is accessed by multiple processes at the same time, you are advised to send a database deletion notification to other processes.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | --------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).|
| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. |
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ----------------------------------------------------------- |
| 14800010 | Failed to open or delete database by invalid database path. |
| 14800000 | Inner error. |
| 14801001 | Only supported in stage mode. |
| 14801002 | The data group id is not valid. |
**Example**
FA model:
```js
import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext();
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
let promise = relationalStore.deleteRdbStore(context, STORE_CONFIG);
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`);
}).catch((err) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
})
```
Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility'
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: relationalStore.SecurityLevel.S1
};
let promise = relationalStore.deleteRdbStore(this.context, STORE_CONFIG);
promise.then(()=>{
store = null;
console.info(`Delete RdbStore successfully.`); console.info(`Delete RdbStore successfully.`);
}).catch((err) => { }).catch((err) => {
console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`); console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
...@@ -315,7 +482,8 @@ Defines the RDB store configuration. ...@@ -315,7 +482,8 @@ Defines the RDB store configuration.
| ------------- | ------------- | ---- | --------------------------------------------------------- | | ------------- | ------------- | ---- | --------------------------------------------------------- |
| name | string | Yes | Database file name. | | name | string | Yes | Database file name. |
| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | | securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. |
| encrypt | boolean | No | Whether to encrypt the RDB store.<br> The value **true** means to encrypt the RDB store;<br> the value **false** (default) means the opposite.| | encrypt | boolean | No | Whether to encrypt the RDB store.<br>The value **true** means to encrypt the RDB store;<br>the value **false** (default) means the opposite.|
| dataGroupId<sup>10+</sup> | string | No| Application group ID, which needs to be obtained from the AppGallery.<br>**Model restriction**: This attribute can be used only in the stage model.<br>This parameter is supported since API version 10. It specifies the **relationalStore** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **relationalStore** instance is created in the sandbox directory of the application.|
## SecurityLevel ## SecurityLevel
...@@ -323,7 +491,7 @@ Enumerates the RDB store security levels. ...@@ -323,7 +491,7 @@ Enumerates the RDB store security levels.
> **NOTE** > **NOTE**
> >
> To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Access Control Mechanism in Cross-Device Synchronization]( ../../database/access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-synchronization). > To perform data synchronization operations, the RDB store security level must be lower than or equal to that of the peer device. For details, see the [Access Control Mechanism in Cross-Device Synchronization](../../database/access-control-by-device-and-data-level.md#access-control-mechanism-in-cross-device-synchronization).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -369,6 +537,8 @@ Defines information about an asset (such as a document, image, and video). The a ...@@ -369,6 +537,8 @@ Defines information about an asset (such as a document, image, and video). The a
Defines an array of the [Asset](#asset10) type. Defines an array of the [Asset](#asset10) type.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Type | Description | | Type | Description |
| ------- | -------------------- | | ------- | -------------------- |
| [Asset](#asset10)[] | Array of assets. | | [Asset](#asset10)[] | Array of assets. |
...@@ -399,6 +569,36 @@ Defines the types of the key and value in a KV pair. This type is not multi-thre ...@@ -399,6 +569,36 @@ Defines the types of the key and value in a KV pair. This type is not multi-thre
| ------ | ----------------------- | | ------ | ----------------------- |
| string | [ValueType](#valuetype) | | string | [ValueType](#valuetype) |
## PRIKeyType<sup>10+</sup>
Represents the type of the primary key in a row of a database table.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Type | Description |
| ---------------- | ---------------------------------- |
| number \| string | The type of the primary key can be number or string.|
## UTCTime<sup>10+</sup>
Represents the data type of the UTC time.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Type| Description |
| ---- | --------------- |
| Date | UTC time.|
## ModifyTime<sup>10+</sup>
Represents the data type of the primary key and modification time of a database table.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Type | Description |
| ------------------------------------------------------- | ------------------------------------------------------------ |
| Map<[PRIKeyType](#prikeytype10), [UTCTime](#utctime10)> | The key is the primary key of a row in the database table, and the value is the last modification time of the row in UTC format.|
## SyncMode ## SyncMode
Enumerates the database synchronization modes. Enumerates the database synchronization modes.
...@@ -407,9 +607,9 @@ Enumerates the database synchronization modes. ...@@ -407,9 +607,9 @@ Enumerates the database synchronization modes.
| -------------- | ---- | ---------------------------------- | | -------------- | ---- | ---------------------------------- |
| SYNC_MODE_PUSH | 0 | Push data from a local device to a remote device.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | SYNC_MODE_PUSH | 0 | Push data from a local device to a remote device.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core |
| SYNC_MODE_PULL | 1 | Pull data from a remote device to a local device.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | SYNC_MODE_PULL | 1 | Pull data from a remote device to a local device.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core |
| SYNC_MODE_TIME_FIRST<sup>10+</sup> | - | Synchronize with the data with the latest modification time. Use the enum names instead of the enum values. Currently, manual synchronization between the device and cloud is not supported.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client| | SYNC_MODE_TIME_FIRST<sup>10+</sup> | - | Synchronize with the data with the latest modification time. Use the enum names instead of the enum values.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client|
| SYNC_MODE_NATIVE_FIRST<sup>10+</sup> | - | Synchronize data from a local device to the cloud. Use the enum names instead of the enum values. Currently, manual synchronization between the device and cloud is not supported.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client | | SYNC_MODE_NATIVE_FIRST<sup>10+</sup> | - | Synchronize data from a local device to the cloud. Use the enum names instead of the enum values.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client |
| SYNC_MODE_CLOUD_FIRST<sup>10+</sup> | - | Synchronize data from the cloud to a local device. Use the enum names instead of the enum values. Currently, manual synchronization between the device and cloud is not supported.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client | | SYNC_MODE_CLOUD_FIRST<sup>10+</sup> | - | Synchronize data from the cloud to a local device. Use the enum names instead of the enum values.<br>**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client |
## SubscribeType ## SubscribeType
...@@ -440,15 +640,15 @@ Enumerates data change types. Use the enum names instead of the enum values. ...@@ -440,15 +640,15 @@ Enumerates data change types. Use the enum names instead of the enum values.
Defines the details about the device-cloud synchronization process. Defines the details about the device-cloud synchronization process.
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | --- | -------------------------------------------------------------------------------------------------------------------- | | -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| table | string | Yes | Name of the table with data changes.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | table | string | Yes | Name of the table with data changes. |
| type | [ChangeType](#changetype10) | Yes | Type of the data changed, which can be data or asset.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | type | [ChangeType](#changetype10) | Yes | Type of the data changed, which can be data or asset. |
| inserted | Array\<string\> \| Array\<number\> | Yes | Location where data is inserted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the inserted data.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | inserted | Array\<string\> \| Array\<number\> | Yes | Location where data is inserted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the inserted data.|
| updated | Array\<string\> \| Array\<number\> | Yes | Location where data is updated. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the updated data.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | updated | Array\<string\> \| Array\<number\> | Yes | Location where data is updated. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the updated data.|
| deleted | Array\<string\> \| Array\<number\> | Yes | Location where data is deleted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the deleted data.<br>**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | | deleted | Array\<string\> \| Array\<number\> | Yes | Location where data is deleted. If the primary key of the table is of the string type, the value is the value of the primary key. Otherwise, the value is the row number of the deleted data.|
## DistributedType<sup>10+</sup> ## DistributedType<sup>10+</sup>
...@@ -486,6 +686,70 @@ Defines the resolution to use when **insert()** and **update()** conflict. ...@@ -486,6 +686,70 @@ Defines the resolution to use when **insert()** and **update()** conflict.
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| | ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| | ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## Progress<sup>10+</sup>
Enumerates the device-cloud synchronization processes. Use the enum names instead of the enum values.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| ---------------- | ---- | ------------------------ |
| SYNC_BEGIN | - | The device-cloud synchronization starts. |
| SYNC_IN_PROGRESS | - | The device-cloud synchronization is in progress.|
| SYNC_FINISH | - | The device-cloud synchronization is complete.|
## Statistic<sup>10+</sup>
Represents the device-cloud synchronization statistics information.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------------------------------------- |
| total | number | Yes | Total number of rows to be synchronized between the device and cloud in the database table. |
| success | number | Yes | Number of rows that are successfully synchronized between the device and cloud in the database table. |
| failed | number | Yes | Number of rows that failed to be synchronized between the device and cloud in the database table. |
| remained | number | Yes | Number of rows that are not executed for device-cloud synchronization in the database table.|
## TableDetails<sup>10+</sup>
Represents the upload and download statistics of device-cloud synchronization tasks.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
| upload | [Statistic](#statistic10) | Yes | Statistics of the device-cloud upload tasks.|
| download | [Statistic](#statistic10) | Yes | Statistics of the device-cloud download tasks.|
## ProgressCode<sup>10+</sup>
Enumerates the device-cloud synchronization states. Use the enum names instead of the enum values.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| --------------------- | ---- | ------------------------------------------------------------ |
| SUCCESS | - | The device-cloud synchronization is successful. |
| UNKNOWN_ERROR | - | An unknown error occurs during device-cloud synchronization. |
| NETWORK_ERROR | - | A network error occurs during device-cloud synchronization. |
| CLOUD_DISABLED | - | The cloud is unavailable. |
| LOCKED_BY_OTHERS | - | The device-cloud synchronization of another device is being performed.<br>Start device-cloud synchronization after checking that cloud resources are not occupied by other devices.|
| RECORD_LIMIT_EXCEEDED | - | The number of records or size of the data to be synchronized exceeds the maximum. The maximum value is configured on the cloud.|
| NO_SPACE_FOR_ASSET | - | The remaining cloud space is less than the size of the data to be synchronized. |
## ProgressDetails<sup>10+</sup>
Represents the statistics of the overall device-cloud synchronization (upload and download) tasks.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| schedule | [Progress](#progress10) | Yes | Device-cloud synchronization process. |
| code | [ProgressCode](#progresscode10) | Yes | Device-cloud synchronization state. |
| details | [table: string] : [TableDetails](#tabledetails10) | Yes | Statistics of each table.<br>The key indicates the table name, and the value indicates the device-cloud synchronization statistics of the table.|
## RdbPredicates ## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If an **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance. Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If an **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance.
...@@ -2133,6 +2397,53 @@ promise.then((rows) => { ...@@ -2133,6 +2397,53 @@ promise.then((rows) => {
}) })
``` ```
### query<sup>10+</sup>
query(predicates: RdbPredicates, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
```js
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
store.query(predicates, function (err, resultSet) {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
### query ### query
query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
...@@ -2233,9 +2544,9 @@ promise.then((resultSet) => { ...@@ -2233,9 +2544,9 @@ promise.then((resultSet) => {
}) })
``` ```
### query ### query<sup>10+</sup>
query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
...@@ -2251,7 +2562,6 @@ Queries data from the RDB store based on specified conditions. This API uses an ...@@ -2251,7 +2562,6 @@ Queries data from the RDB store based on specified conditions. This API uses an
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| table | string | Yes | Name of the target table. | | table | string | Yes | Name of the target table. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. |
| columns | Array&lt;string&gt; | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Error codes** **Error codes**
...@@ -2268,7 +2578,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -2268,7 +2578,7 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose"); predicates.equalTo("NAME", "Rose");
store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { store.query("EMPLOYEE", predicates, function (err, resultSet) {
if (err) { if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`); console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return; return;
...@@ -2289,9 +2599,9 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu ...@@ -2289,9 +2599,9 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu
### query ### query
query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -2301,17 +2611,12 @@ Queries data from the RDB store based on specified conditions. This API uses a p ...@@ -2301,17 +2611,12 @@ Queries data from the RDB store based on specified conditions. This API uses a p
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| table | string | Yes | Name of the target table. | | table | string | Yes | Name of the target table. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | | predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. |
| columns | Array&lt;string&gt; | No | Columns to query. If this parameter is not specified, the query applies to all columns.| | columns | Array&lt;string&gt; | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Return value**
| Type | Description |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Error codes** **Error codes**
...@@ -2327,8 +2632,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -2327,8 +2632,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose"); predicates.equalTo("NAME", "Rose");
let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) {
promise.then((resultSet) => { if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0. // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) { while(resultSet.goToNextRow()) {
...@@ -2340,12 +2648,68 @@ promise.then((resultSet) => { ...@@ -2340,12 +2648,68 @@ promise.then((resultSet) => {
} }
// Release the dataset memory. // Release the dataset memory.
resultSet.close(); resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
}) })
``` ```
### remoteQuery ### query
query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ |
| table | string | Yes | Name of the target table. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. |
| columns | Array&lt;string&gt; | No | Columns to query. If this parameter is not specified, the query applies to all columns.|
**Return value**
| Type | Description |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
```js
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo("NAME", "Rose");
let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
}).catch((err) => {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
})
```
### remoteQuery
remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt; , callback: AsyncCallback&lt;ResultSet&gt;): void remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt; , callback: AsyncCallback&lt;ResultSet&gt;): void
...@@ -2487,6 +2851,51 @@ promise.then((resultSet) => { ...@@ -2487,6 +2851,51 @@ promise.then((resultSet) => {
}) })
``` ```
### querySql<sup>10+</sup>
querySql(sql: string, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| sql | string | Yes | SQL statement to run. |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | ---------------------------- |
| 14800000 | Inner error. |
**Example**
```js
store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", function (err, resultSet) {
if (err) {
console.error(`Query failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 0.
while(resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
}
// Release the dataset memory.
resultSet.close();
})
```
### querySql ### querySql
querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
...@@ -2583,6 +2992,43 @@ promise.then((resultSet) => { ...@@ -2583,6 +2992,43 @@ promise.then((resultSet) => {
}) })
``` ```
### executeSql<sup>10+</sup>
executeSql(sql: string, callback: AsyncCallback&lt;void&gt;):void
Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| sql | string | Yes | SQL statement to run. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------------- |
| 14800047 | The WAL file size exceeds the default limit. |
| 14800000 | Inner error. |
**Example**
```js
const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
store.executeSql(SQL_DELETE_TABLE, function(err) {
if (err) {
console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`Delete table done.`);
})
```
### executeSql ### executeSql
executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void
...@@ -2663,6 +3109,85 @@ promise.then(() => { ...@@ -2663,6 +3109,85 @@ promise.then(() => {
}) })
``` ```
### getModifyTime<sup>10+</sup>
getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[], callback: AsyncCallback&lt;ModifyTime&gt;): void
Obtains the last modification time of the data in a table. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| table | string | Yes | Name of the database table to query. |
| columnName | string | Yes | Column name of the database table to query. |
| primaryKeys | [PRIKeyType](#prikeytype10)[] | Yes | Primary keys of the rows to query.<br>If the database table has no primary key, **rowid** must be passed in through **columnName**. In this case, **primaryKeys** specifies the row numbers of the database table to query.<br>If the database table has no primary key and no **rowid** is passed in through **columnName**, an error code will be returned.|
| callback | AsyncCallback&lt;[ModifyTime](#modifytime10)&gt; | Yes | Callback invoked to return the result. If the operation is successful, the **ModifyTime** object is returned.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message**|
| ------------ | ------------ |
| 14800000 | Inner error. |
**Example**
```js
let PRIKey = [1, 4, 2, 3];
store.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) {
if (err) {
console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
return;
}
let size = modifyTime.size();
});
```
### getModifyTime<sup>10+</sup>
getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[]): Promise&lt;ModifyTime&gt;
Obtains the last modification time of the data in a table. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ----------------------------- | ---- | ------------------------------------------------------------ |
| table | string | Yes | Name of the database table to query. |
| columnName | string | Yes | Column name of the database table to query. |
| primaryKeys | [PRIKeyType](#prikeytype10)[] | Yes | Primary keys of the rows to query.<br>If the database table has no primary key, **rowid** must be passed in through **columnName**. In this case, **primaryKeys** specifies the row numbers of the database table to query.<br>If the database table has no primary key and no **rowid** is passed in through **columnName**, an error code will be returned.|
**Return value**
| Type | Description |
| ------------------------------------------ | --------------------------------------------------------- |
| Promise&lt;[ModifyTime](#modifytime10)&gt; | Promise used to return the **ModifyTime** object.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message**|
| ------------ | ------------ |
| 14800000 | Inner error. |
**Example**
```js
let PRIKey = [1, 2, 3];
store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => {
let size = modifyTime.size();
}).catch((err) => {
console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
});
```
### beginTransaction ### beginTransaction
beginTransaction():void beginTransaction():void
...@@ -3021,14 +3546,14 @@ Sets distributed tables. This API uses an asynchronous callback to return the re ...@@ -3021,14 +3546,14 @@ Sets distributed tables. This API uses an asynchronous callback to return the re
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ----------------------------------- | --- | --------------- | | -------- | ----------------------------------- | --- | --------------- |
| tables | Array&lt;string&gt; | Yes | Names of the distributed tables to set. | | tables | Array&lt;string&gt; | Yes | Names of the distributed tables to set. |
| type | number | Yes | Distributed type of the tables. Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported.<br> The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices.<br> The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.| | type | number | Yes | Distributed type of the tables. Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported.<br>The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices.<br>The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.|
| config | [DistributedConfig](#distributedconfig10) | Yes| Configuration of the distributed mode.| | config | [DistributedConfig](#distributedconfig10) | Yes| Configuration of the distributed mode.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result.|
**Example** **Example**
```js ```js
let config = new DistributedConfig(); let config = new relationalStore.DistributedConfig();
config.autoSync = true; config.autoSync = true;
store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) { store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) {
if (err) { if (err) {
...@@ -3054,7 +3579,7 @@ Sets distributed tables. This API uses a promise to return the result. ...@@ -3054,7 +3579,7 @@ Sets distributed tables. This API uses a promise to return the result.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ | | ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| tables | Array&lt;string&gt; | Yes | Names of the distributed tables to set. | | tables | Array&lt;string&gt; | Yes | Names of the distributed tables to set. |
| type | number | No | Distributed type of the tables. The default value is **relationalStore.DistributedType.DISTRIBUTED_DEVICE**.<br> Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported.<br> The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices.<br> The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.| | type | number | No | Distributed type of the tables. The default value is **relationalStore.DistributedType.DISTRIBUTED_DEVICE**.<br>Currently, only **relationalStore.DistributedType.DISTRIBUTED_DEVICE** and **relationalStore.DistributedType.DISTRIBUTED_CLOUD** are supported.<br>The value **relationalStore.DistributedType.DISTRIBUTED_DEVICE** indicates distributed tables across different devices.<br>The value **relationalStore.DistributedType.DISTRIBUTED_CLOUD** indicates distributed tables between the device and cloud.|
| config | [DistributedConfig](#distributedconfig10) | No | Configuration of the distributed mode. If this parameter is not specified, the value of **autoSync** is **false** by default, which means only manual synchronization is supported.| | config | [DistributedConfig](#distributedconfig10) | No | Configuration of the distributed mode. If this parameter is not specified, the value of **autoSync** is **false** by default, which means only manual synchronization is supported.|
**Return value** **Return value**
...@@ -3066,7 +3591,7 @@ Sets distributed tables. This API uses a promise to return the result. ...@@ -3066,7 +3591,7 @@ Sets distributed tables. This API uses a promise to return the result.
**Example** **Example**
```js ```js
let config = new DistributedConfig(); let config = new relationalStore.DistributedConfig();
config.autoSync = true; config.autoSync = true;
let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config); let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config);
promise.then(() => { promise.then(() => {
...@@ -3314,11 +3839,153 @@ promise.then((result) =>{ ...@@ -3314,11 +3839,153 @@ promise.then((result) =>{
}) })
``` ```
### cloudSync<sup>10+</sup>
cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;, callback: AsyncCallback&lt;void&gt;): void
Manually starts device-cloud synchronization for all distributed tables. This API uses an asynchronous callback to return the result. Before using this API, ensure that the cloud service must be available.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------- |
| mode | [SyncMode](#syncmode) | Yes | Synchronization mode of the database. |
| progress | Callback&lt;[ProgressDetails](#progressdetails10)&gt; | Yes | Callback used to process database synchronization details. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to send the synchronization result to the caller.|
**Example**
```js
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
console.info(`Progess: ${progressDetails}`);
}, function (err) {
if (err) {
console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info('Cloud sync succeeded');
});
```
### cloudSync<sup>10+</sup>
cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;): Promise&lt;void&gt;
Manually starts device-cloud synchronization for all distributed tables. This API uses a promise to return the result. Before using this API, ensure that the cloud service must be available.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------- |
| mode | [SyncMode](#syncmode) | Yes | Synchronization mode of the database. |
| progress | Callback&lt;[ProgressDetails](#progressdetails10)&gt; | Yes | Callback used to process database synchronization details.|
**Return value**
| Type | Description |
| ------------------- | --------------------------------------- |
| Promise&lt;void&gt; | Promise used to send the synchronization result.|
**Example**
```js
function progress(progressDetail) {
console.info(`progress: ${progressDetail}`);
}
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
console.info('Cloud sync succeeded');
}).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
});
```
### cloudSync<sup>10+</sup>
cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetails&gt;, callback: AsyncCallback&lt;void&gt;): void
Manually starts device-cloud synchronization of the specified table. This API uses an asynchronous callback to return the result. Before using this API, ensure that the cloud service must be available.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------------------- |
| mode | [SyncMode](#syncmode) | Yes | Synchronization mode of the database. |
| tables | string[] | Yes | Name of the table to synchronize. |
| progress | Callback&lt;[ProgressDetails](#progressdetails10)&gt; | Yes | Callback used to process database synchronization details. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to send the synchronization result to the caller.|
**Example**
```js
const tables = ["table1", "table2"];
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
console.info(`Progess: ${progressDetails}`);
}, function (err) {
if (err) {
console.error(`Cloud sync failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info('Cloud sync succeeded');
});
```
### cloudSync<sup>10+</sup>
cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetails&gt;): Promise&lt;void&gt;
Manually starts device-cloud synchronization of the specified table. This API uses a promise to return the result. Before using this API, ensure that the cloud service must be available.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | -------------------------------------- |
| mode | [SyncMode](#syncmode) | Yes | Synchronization mode of the database. |
| tables | string[] | Yes | Name of the table to synchronize. |
| progress | Callback&lt;[ProgressDetails](#progressdetails10)&gt; | Yes | Callback used to process database synchronization details.|
**Return value**
| Type | Description |
| ------------------- | --------------------------------------- |
| Promise&lt;void&gt; | Promise used to send the synchronization result.|
**Example**
```js
const tables = ["table1", "table2"];
function progress(progressDetail) {
console.info(`progress: ${progressDetail}`);
}
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
console.info('Cloud sync succeeded');
}).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
});
```
### on('dataChange') ### on('dataChange')
on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void
Registers the data change event listener for the RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. Registers a data change event listener for the RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -3327,12 +3994,12 @@ Registers the data change event listener for the RDB store. When the data in the ...@@ -3327,12 +3994,12 @@ Registers the data change event listener for the RDB store. When the data in the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md#subscribetype) | Yes | Subscription type to register. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to register. |
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the data change. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.| | observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the data change. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
**Example** **Example**
``` ```js
function storeObserver(devices) { function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
console.info(`device= ${devices[i]} data changed`); console.info(`device= ${devices[i]} data changed`);
...@@ -3349,7 +4016,7 @@ try { ...@@ -3349,7 +4016,7 @@ try {
on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;\| Callback&lt;Array&lt;ChangeInfo&gt;&gt;): void on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;\| Callback&lt;Array&lt;ChangeInfo&gt;&gt;): void
Registers the data change event listener for the RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. Registers a data change event listener for the RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -3359,7 +4026,7 @@ Registers the data change event listener for the RDB store. When the data in the ...@@ -3359,7 +4026,7 @@ Registers the data change event listener for the RDB store. When the data in the
| -------- | ----------------------------------- | ---- | ------------------------------------------- | | -------- | ----------------------------------- | ---- | ------------------------------------------- |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.| | type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.|
| observer | Callback&lt;Array&lt;string&gt;&gt; \| Callback&lt;Array&lt;[ChangeInfo](#changeinfo10)&gt;&gt; | Yes | Callback invoked to return the data change event.<br>If **type** is **SUBSCRIBE_TYPE_REMOTE**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the IDs of the peer devices with data changes.<br> If **type** is **SUBSCRIBE_TYPE_CLOUD**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the cloud accounts with data changes.<br> If **type** is **SUBSCRIBE_TYPE_CLOUD_DETAILS**, **observer** must be **Callback&lt;Array&lt;ChangeInfo&gt;&gt;**, where **Array&lt;ChangeInfo&gt;** specifies the details about the device-cloud synchronization.| | observer | Callback&lt;Array&lt;string&gt;&gt; \| Callback&lt;Array&lt;[ChangeInfo](#changeinfo10)&gt;&gt; | Yes | Callback invoked to return the data change.<br>If **type** is **SUBSCRIBE_TYPE_REMOTE**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the IDs of the peer devices with data changes.<br>If **type** is **SUBSCRIBE_TYPE_CLOUD**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the cloud accounts with data changes.<br>If **type** is **SUBSCRIBE_TYPE_CLOUD_DETAILS**, **observer** must be **Callback&lt;Array&lt;ChangeInfo&gt;&gt;**, where **Array&lt;ChangeInfo&gt;** specifies the details about the device-cloud synchronization.|
**Example** **Example**
...@@ -3376,6 +4043,44 @@ try { ...@@ -3376,6 +4043,44 @@ try {
} }
``` ```
### on<sup>10+</sup>
on(event: string, interProcess: boolean, observer: Callback\<void>): void
Registers an intra-process or inter-process event listener for the RDB store. This callback is invoked by [emit](#emit10).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | --------------- | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event name to observe. |
| interProcess | boolean | Yes | Type of the event to observe.<br>The value **true** means the inter-process event.<br>The value **false** means the intra-process event. |
| observer | Callback\<void> | Yes | Callback invoked to return the result. |
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------- |
| 14800000 | Inner error. |
| 14800050 | Failed to obtain subscription service. |
**Example**
```js
function storeObserver() {
console.info(`storeObserver`);
}
try {
store.on('storeObserver', false, storeObserver);
} catch (err) {
console.error(`Register observer failed, code is ${err.code},message is ${err.message}`);
}
```
### off('dataChange') ### off('dataChange')
off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void
...@@ -3388,8 +4093,8 @@ Unregisters the data change event listener. ...@@ -3388,8 +4093,8 @@ Unregisters the data change event listener.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype)| Yes | Subscription type to unregister. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. |
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback for the data change event. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.| | observer | Callback&lt;Array&lt;string&gt;&gt; | Yes | Callback for the data change event. **Array<string>** indicates the IDs of the peer devices whose data in the database is changed.|
**Example** **Example**
...@@ -3419,9 +4124,9 @@ Unregisters the data change event listener. ...@@ -3419,9 +4124,9 @@ Unregisters the data change event listener.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------ | | -------- | ---------------------------------- | ---- | ------------------------------------------ |
| event | string | Yes | Event to observe. The value is **dataChange**, which indicates a data change event. | | event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event. |
| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register. | | type | [SubscribeType](#subscribetype) | Yes | Subscription type to unregister. |
| observer | Callback&lt;Array&lt;string&gt;&gt;\| Callback&lt;Array&lt;[ChangeInfo](#changeinfo10)&gt;&gt; | No| Callback invoked to return the result.<br>If **type** is **SUBSCRIBE_TYPE_REMOTE**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the IDs of the peer devices with data changes.<br> If **type** is **SUBSCRIBE_TYPE_CLOUD**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the cloud accounts with data changes.<br> If **type** is **SUBSCRIBE_TYPE_CLOUD_DETAILS**, **observer** must be **Callback&lt;Array&lt;ChangeInfo&gt;&gt;**, where **Array&lt;ChangeInfo&gt;** specifies the details about the device-cloud synchronization.<br> If **observer** is not specified, listening for all data change events of the specified **type** will be canceled.| | observer | Callback&lt;Array&lt;string&gt;&gt;\| Callback&lt;Array&lt;[ChangeInfo](#changeinfo10)&gt;&gt; | No| Callback invoked to return the result.<br>If **type** is **SUBSCRIBE_TYPE_REMOTE**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the IDs of the peer devices with data changes.<br>If **type** is **SUBSCRIBE_TYPE_CLOUD**, **observer** must be **Callback&lt;Array&lt;string&gt;&gt;**, where **Array&lt;string&gt;** specifies the cloud accounts with data changes.<br>If **type** is **SUBSCRIBE_TYPE_CLOUD_DETAILS**, **observer** must be **Callback&lt;Array&lt;ChangeInfo&gt;&gt;**, where **Array&lt;ChangeInfo&gt;** specifies the details about the device-cloud synchronization.<br>If **observer** is not specified, listening for all data change events of the specified **type** will be canceled.|
**Example** **Example**
...@@ -3438,6 +4143,73 @@ try { ...@@ -3438,6 +4143,73 @@ try {
} }
``` ```
### off<sup>10+</sup>
off(event: string, interProcess: boolean, observer?: Callback\<void>): void
Unregisters the data change event listener.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | --------------- | ---- | ------------------------------------------------------------ |
| event | string | Yes | Name of the event to unsubscribe from. |
| interProcess | boolean | Yes | Type of the event.<br>The value **true** means the inter-process event.<br>The value **false** means the intra-process event.|
| observer | Callback\<void> | No | Callback for the event to unregister. If this parameter is specified, the specified callback will be unregistered. If this parameter is not specified, all callbacks of the specified event will be unregistered.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------- |
| 14800000 | Inner error. |
| 14800050 | Failed to obtain subscription service. |
**Example**
```js
function storeObserver() {
console.info(`storeObserver`);
}
try {
store.off('storeObserver', false, storeObserver);
} catch (err) {
console.error(`Register observer failed, code is ${err.code},message is ${err.message}`);
}
```
### emit<sup>10+</sup>
emit(event: string): void
Triggers the inter-process or intra-process event listener registered through [on](#on10).
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| event | string | Yes | Name of the event.|
**Error codes**
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
| **ID**| **Error Message** |
| ------------ | -------------------------------------- |
| 14800000 | Inner error. |
| 14800050 | Failed to obtain subscription service. |
**Example**
```js
store.emit('storeObserver');
```
## ResultSet ## ResultSet
Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called. Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called.
...@@ -3857,7 +4629,7 @@ Obtains the value of the Long type based on the specified column and the current ...@@ -3857,7 +4629,7 @@ Obtains the value of the Long type based on the specified column and the current
| Type | Description | | Type | Description |
| ------ | ------------------------------------------------------------ | | ------ | ------------------------------------------------------------ |
| number | Value obtained.<br>The value range supported by API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| | number | Value obtained.<br>The value range supported by this API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).|
**Error codes** **Error codes**
......
# @ohos.net.policy (Network Policy Management)
The **policy** module provides APIs for managing network policies, through which you can control and manage the data volume used.
> **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
```js
import policy from '@ohos.net.policy'
```
## policy.setBackgroundAllowed<sup>10+</sup>
setBackgroundAllowed(isAllowed: boolean, callback: AsyncCallback\<void>): void
Specifies whether background applications are allowed to access the network. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | Yes | Whether background applications are allowed to use mobile data.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setBackgroundAllowed(true, (error) => {
console.log(JSON.stringify(error))
})
;
```
## policy.setBackgroundAllowed<sup>10+</sup>
setBackgroundAllowed(isAllowed: boolean): Promise\<void>
Specifies whether background applications are allowed to access the network. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| isAllowed | boolean | Yes | Whether background applications are allowed to use mobile data.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Example**
```js
policy.setBackgroundAllowed(true).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.isBackgroundAllowed<sup>10+</sup>
isBackgroundAllowed(callback: AsyncCallback\<boolean>): void
Checks whether the current application is allowed to access the network when running at the background. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the operation is successful, the value **true** is returned, which means that background applications are allowed to use mobile data. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isBackgroundAllowed((error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.isBackgroundAllowed<sup>10+</sup>
isBackgroundAllowed(): Promise\<boolean>;
Checks whether the current application is allowed to access the network when running at the background. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. If the operation is successful, the value **true** is returned, which means that background applications are allowed to use mobile data. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setPolicyByUid<sup>10+</sup>
setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\<void>): void
Sets the metered network access policy for the application specified by a given UID. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes | Unique ID of the application.|
| policy | [NetUidPolicy](#netuidpolicy10) | Yes| Network access policy for the application.|netuidpolicy
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE, (error) => {
console.log(JSON.stringify(error))
});
```
## policy.setPolicyByUid<sup>10+</sup>
setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\<void>;
Sets the metered network access policy for the application specified by a given UID. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes | Unique ID of the application.|
| policy | [NetUidPolicy](#netuidpolicy10) | Yes| Network access policy for the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setPolicyByUid(11111, policy.NetUidPolicy.NET_POLICY_NONE).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.getPolicyByUid<sup>10+</sup>
getPolicyByUid(uid: number, callback: AsyncCallback\<NetUidPolicy>): void
Obtains the network access policy for the application specified by a given UID. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy10)> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPolicyByUid(11111, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getPolicyByUid<sup>10+</sup>
getPolicyByUid(uid: number): Promise\<NetUidPolicy>;
Obtains the network access policy for the application specified by a given UID. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetUidPolicy](#netuidpolicy10)> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. | |
**Example**
```js
policy.getPolicyByUid(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getUidsByPolicy<sup>10+</sup>
getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\<Array\<number>>): void
Obtains all UIDs that match the specified network policy. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy10) | Yes| Network policy for the application.|
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getUidsByPolicy(11111, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getUidsByPolicy<sup>10+</sup>
getUidsByPolicy(policy: NetUidPolicy): Promise\<Array\<number>>;
Obtains all UIDs that match the specified network policy. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| policy | [NetUidPolicy](#netuidpolicy10) | Yes| Network policy for the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result. If the operation is successful, the operation result is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getUidsByPolicy(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getNetQuotaPolicies<sup>10+</sup>
getNetQuotaPolicies(callback: AsyncCallback\<Array\<NetQuotaPolicy>>): void
Obtains the network quota policies. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<[NetQuotaPolicy](#netquotapolicy10)>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getNetQuotaPolicies((error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getNetQuotaPolicies<sup>10+</sup>
getNetQuotaPolicies(): Promise\<Array\<NetQuotaPolicy>>;
Obtains the network quota policies. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<[NetQuotaPolicy](#netquotapolicy10)>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setNetQuotaPolicies<sup>10+</sup>
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>, callback: AsyncCallback\<void>): void
Sets network quota policies. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy10)> | Yes| Network quota policies.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
import connection from '@ohos.net.connection';
let netQuotaPolicyList = []
let netquotapolicy = {
networkMatchRule: {
netType: connection.NetBearType.BEARER_CELLULAR,
identity:"",
simId:"1"
},
quotaPolicy: {
periodDuration: "M1",
warningBytes: 40000,
limitBytes: 50000,
metered: true,
limitAction: policy.LimitAction.LIMIT_ACTION_NONE
},
}
netQuotaPolicyList.push(netquotapolicy);
policy.setNetQuotaPolicies(netQuotaPolicyList, (error) => {
console.log(JSON.stringify(error))
});
```
## policy.setNetQuotaPolicies<sup>10+</sup>
setNetQuotaPolicies(quotaPolicies: Array\<NetQuotaPolicy>): Promise\<void>;
Sets network quota policies. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy10)> | Yes| Network quota policies.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Example**
```js
import connection from '@ohos.net.connection';
let netQuotaPolicyList = []
let netquotapolicy = {
networkMatchRule: {
netType: connection.NetBearType.BEARER_CELLULAR,
identity:"",
simId:"1"
},
quotaPolicy: {
periodDuration: "M1",
warningBytes: 40000,
limitBytes: 50000,
metered: true,
limitAction: policy.LimitAction.LIMIT_ACTION_NONE
},
}
netQuotaPolicyList.push(netquotapolicy);
policy.setNetQuotaPolicies(netQuotaPolicyList).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.isUidNetAllowed<sup>10+</sup>
isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\<boolean>): void
Checks whether the application specified by a given UID is allowed to access a metered network. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isUidNetAllowed(11111, true, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.isUidNetAllowed<sup>10+</sup>
isUidNetAllowed(uid: number, isMetered: boolean): Promise\<boolean>;
Checks whether the application specified by a given UID is allowed to access a metered network. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| isMetered | boolean | Yes| Whether the network is a metered network.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isUidNetAllowed(11111, true).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.isUidNetAllowed<sup>10+</sup>
isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\<boolean>): void
Checks whether the application specified by a given UID is allowed to access the network specified by a given **iface**. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the specified network, and **false** means the opposite.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isUidNetAllowed(11111, 'wlan0', (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.isUidNetAllowed<sup>10+</sup>
isUidNetAllowed(uid: number, iface: string): Promise\<boolean>;
Checks whether the application specified by a given UID is allowed to access the network specified by a given **iface**. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| iface | string | Yes| Name of the target network.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<boolean> | Promise used to return the result. |
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.isUidNetAllowed(11111, 'wlan0').then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.setDeviceIdleTrustlist<sup>10+</sup>
setDeviceIdleTrustlist(uids: Array\<number>, isAllowed: boolean, callback: AsyncCallback\<void>): void
Adds applications specified by given UIDs to the device idle allowlist. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uids | Array\<number> | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
| callback | callback: AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setDeviceIdleTrustlist([11111,22222], true, (error) => {
console.log(JSON.stringify(error))
});
```
## policy.setDeviceIdleTrustlist<sup>10+</sup>
setDeviceIdleTrustlist(uids: Array\<number>, isAllowed: boolean): Promise\<void>;
Adds applications specified by given UIDs to the device idle allowlist. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uids | Array\<number> | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setDeviceIdleTrustlist([11111,22222], true).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.getDeviceIdleTrustlist<sup>10+</sup>
getDeviceIdleTrustlist(callback: AsyncCallback\<Array\<number>>): void
Obtains the UIDs of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getDeviceIdleTrustlist((error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getDeviceIdleTrustlist<sup>10+</sup>
getDeviceIdleTrustlist(): Promise\<Array\<number>>;
Obtains the UIDs of applications that are on the device idle allowlist. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getDeviceIdleTrustlist().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.getBackgroundPolicyByUid<sup>10+</sup>
getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\<NetBackgroundPolicy>): void
Obtains the background network policy for the application specified by a given UID. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy10)> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getBackgroundPolicyByUid(11111, (error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getBackgroundPolicyByUid<sup>10+</sup>
getBackgroundPolicyByUid(uid: number): Promise\<NetBackgroundPolicy>;
Obtains the background network policy for the application specified by a given UID. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uid | number | Yes| Unique ID of the application.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy10)> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getBackgroundPolicyByUid(11111).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.resetPolicies<sup>10+</sup>
resetPolicies(simId: string, callback: AsyncCallback\<void>): void
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the specified SIM card. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| simId | string | Yes| SIM card ID.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.resetPolicies('1', (error) => {
console.log(JSON.stringify(error))
});
```
## policy.resetPolicies<sup>10+</sup>
resetPolicies(simId: string): Promise\<void>;
Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the specified SIM card. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| simId | string | Yes| SIM card ID.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.resetPolicies('1').then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.updateRemindPolicy<sup>10+</sup>
updateRemindPolicy(netType: NetBearType, simId: string, remindType: RemindType, callback: AsyncCallback\<void>): void
Updates a reminder policy. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.|
| simId | string | Yes| SIM card ID.|
| remindType | [RemindType](#remindtype10) | Yes| Reminder type.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
import connection from '@ohos.net.connection';
policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING, (error) => {
console.log(JSON.stringify(error))
});
```
## policy.updateRemindPolicy<sup>10+</sup>
updateRemindPolicy(netType: NetBearType, simId: string, remindType: RemindType): Promise\<void>;
Updates a reminder policy. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.|
| simId | string | Yes| SIM card ID.|
| remindType | [RemindType](#remindtype10) | Yes| Reminder type.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
import connection from '@ohos.net.connection';
policy.updateRemindPolicy(connection.NetBearType.BEARER_CELLULAR, '1', policy.RemindType.REMIND_TYPE_WARNING).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.setPowerSaveTrustlist<sup>10+</sup>
setPowerSaveTrustlist(uids: Array\<number>, isAllowed: boolean, callback: AsyncCallback\<void>): void
Sets whether to add the application specified by a given UID to the power-saving allowlist. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uids | Array\<number> | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
| callback | callback: AsyncCallback\<void> | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setPowerSaveTrustlist([11111,22222], true, (error) => {
console.log(JSON.stringify(error))
});
```
## policy.setPowerSaveTrustlist<sup>10+</sup>
setPowerSaveTrustlist(uids: Array\<number>, isAllowed: boolean): Promise\<void>;
Sets whether to add the application specified by a given UID to the power-saving allowlist. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| uids | Array\<number> | Yes| Unique ID of the application.|
| isAllowed | boolean | Yes| Whether to add the application to the allowlist.|
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void> | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.setPowerSaveTrustlist([11111,22222], true).then(function (error) {
console.log(JSON.stringify(error))
})
```
## policy.getPowerSaveTrustlist<sup>10+</sup>
getPowerSaveTrustlist(callback: AsyncCallback\<Array\<number>>): void
Obtains the UID array of applications that are on the power-saving allowlist. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| callback | AsyncCallback\<Array\<number>> | Yes | Callback used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPowerSaveTrustlist((error, data) => {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
```
## policy.getPowerSaveTrustlist<sup>10+</sup>
getPowerSaveTrustlist(): Promise\<Array\<number>>;
Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<Array\<number>> | Promise used to return the result.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error. |
**Example**
```js
policy.getPowerSaveTrustlist().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
```
## policy.on
Represents the handle to a network policy.
### on('netUidPolicyChange')<sup>10+</sup>
on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void
Subscribes to policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.|
| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy10) }> | Yes | Callback used to return the result. It is called when the registered network policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
policy.on('netUidPolicyChange', (data) => {
console.log('on netUidPolicyChange: ' + JSON.stringify(data));
})
```
### off('netUidPolicyChange')<sup>10+</sup>
off(type: "netUidPolicyChange", callback?: Callback<{ uid: number, policy: NetUidPolicy }>): void
Unsubscribes from policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.|
| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy10) }> | No | Callback used to return the result. It is called when the registered network policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
let callback = data => {
console.log("on netUidPolicyChange, data:" + JSON.stringify(data));
}
policy.on('netUidPolicyChange', callback);
policy.off('netUidPolicyChange', callback);
```
### on('netUidRuleChange')<sup>10+</sup>
on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void
Subscribes to rule changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.|
| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule10) }> | Yes | Callback used to return the result. It is called when the registered rule changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
policy.on('netUidRuleChange', (data) => {
console.log('on netUidRuleChange: ' + JSON.stringify(data));
})
```
### off('netUidRuleChange')<sup>10+</sup>
off(type: "netUidRuleChange", callback?: Callback<{ uid: number, rule: NetUidRule }>): void
Unsubscribes from rule changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.|
| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule10) }> | No | Callback used to return the result. It is called when the registered rule changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
let callback = data => {
console.log("on netUidRuleChange, data:" + JSON.stringify(data));
}
policy.on('netUidRuleChange', callback);
policy.off('netUidRuleChange', callback);
```
### on('netMeteredIfacesChange')<sup>10+</sup>
on(type: "netMeteredIfacesChange", callback: Callback\<Array\<string>>): void
Subscribes to metered **iface** changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered **iface** change event.|
| callback | Callback\<Array\<string>> | Yes | Callback used to return the result. It is called when the registered metered **iface** changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
policy.on('netMeteredIfacesChange', (data) => {
console.log('on netMeteredIfacesChange: ' + JSON.stringify(data));
})
```
### off('netMeteredIfacesChange')<sup>10+</sup>
off(type: "netMeteredIfacesChange", callback?: Callback\<Array\<string>>): void
Unsubscribes from metered **iface** changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered **iface** change event.|
| callback | Callback\<Array\<string>> | No | Callback used to return the result. It is called when the registered metered **iface** changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
let callback = data => {
console.log("on netMeteredIfacesChange, data:" + JSON.stringify(data));
}
policy.on('netMeteredIfacesChange', callback);
policy.off('netMeteredIfacesChange', callback);
```
### on('netQuotaPolicyChange')<sup>10+</sup>
on(type: "netQuotaPolicyChange", callback: Callback\<Array\<NetQuotaPolicy>>): void
Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.|
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy10)>> | Yes | Callback used to return the result. It is called when the registered network quota policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
policy.on('netQuotaPolicyChange', (data) => {
console.log('on netQuotaPolicyChange: ' + JSON.stringify(data));
})
```
### off('netQuotaPolicyChange')<sup>10+</sup>
off(type: "netQuotaPolicyChange", callback?: Callback\<Array\<NetQuotaPolicy>>): void
Unsubscribes from network quota policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.|
| callback | Callback\<Array\<[NetQuotaPolicy](#netquotapolicy10)>> | No | Callback used to return the result. It is called when the registered network quota policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
let callback = data => {
console.log("on netQuotaPolicyChange, data:" + JSON.stringify(data));
}
policy.on('netQuotaPolicyChange', callback);
policy.off('netQuotaPolicyChange', callback);
```
### on('netBackgroundPolicyChange')<sup>10+</sup>
on(type: "netBackgroundPolicyChange", callback: Callback\<boolean>): void
Subscribes to background network policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.|
| callback | Callback\<boolean> | Yes | Callback used to return the result. It is called when the registered background network policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
policy.on('netBackgroundPolicyChange', (data) => {
console.log('on netBackgroundPolicyChange: ' + JSON.stringify(data));
})
```
### off('netBackgroundPolicyChange')<sup>10+</sup>
off(type: "netBackgroundPolicyChange", callback?: Callback\<boolean>): void
Unsubscribes from background network policy changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.MANAGE_NET_STRATEGY
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.|
| callback | Callback\<boolean> | No | Callback used to return the result. It is called when the registered background network policy changes.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Non-system applications use system APIs. |
| 401 | Parameter error. |
| 2100001 | Invalid parameter value. |
| 2100002 | Operation failed. Cannot connect to service.|
| 2100003 | System internal error.
**Example**
```js
let callback = data => {
console.log("on netBackgroundPolicyChange, data:" + JSON.stringify(data));
}
policy.on('netBackgroundPolicyChange', callback);
policy.off('netBackgroundPolicyChange', callback);
```
## NetBackgroundPolicy<sup>10+</sup>
Enumerates the background network policies.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.|
| NET_BACKGROUND_POLICY_ENABLE | 1 | Background applications are allowed to access a metered network.|
| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access a metered network.|
| NET_BACKGROUND_POLICY_TRUSTLIST | 3 | Only applications on the allowlist are allowed to access metered networks when they are running in the background.|
## NetQuotaPolicy<sup>10+</sup>
Defines the quota policy for the specified network.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type |Mandatory| Description |
| ----------------------- | ----------------------------------- |------| ------------------------------------------------------- |
| networkMatchRule | [NetworkMatchRule](#networkmatchrule10) |Yes| Network for which the quota policy is set.
| quotaPolicy | [QuotaPolicy](#quotapolicy10) |Yes| Network quota policy.
## NetworkMatchRule<sup>10+</sup>
Defines the network for which the quota policy is set.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type |Mandatory| Description |
| ----------------------- | ----------------------------------- |-----| ------------------------------------------------------------ |
| netType | [NetBearType](js-apis-net-connection.md#netbeartype) |Yes| Network type.|
| simId | string |Yes| Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.|
| identity | string |Yes| ID of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.|
## QuotaPolicy<sup>10+</sup>
Defines the network quota policy.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type |Mandatory| Description |
| ----------------------- | ----------------------------------- |----| ------------------------------------------------------------ |
| periodDuration | string |Yes| Metering period for the quota limit. **D1**, **M1**, and **Y1** indicate one day, one month, and one year, respectively. If the specified metering period is exceeded, the quota is not limited.|
| warningBytes | number |Yes| Data volume threshold for generating an alarm.|
| limitBytes | number |Yes| Data volume quota.|
| metered | string |Yes| Whether the network is a metered network.|
| limitAction | [LimitAction](#limitaction10) |Yes| Action to take when the data volume quota is reached.|
| lastWarningRemind | string |No| Last time when an alarm was generated.|
| lastLimitRemind | string |No| Last time when the quota was exhausted.|
## LimitAction<sup>10+</sup>
Enumerates the actions that can be taken when the data volume quota is reached.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| LIMIT_ACTION_NONE | -1 | No action is taken. This is the default value.|
| LIMIT_ACTION_ACCESS_DISABLED | 0 | Internet access is disabled.|
| LIMIT_ACTION_ALERT_ONLY| 1 | An alarm is generated when the quota limit is reached.|
## NetUidRule<sup>10+</sup>
Enumerates the metered network rules.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| NET_RULE_NONE | 0 | Default rule.|
| NET_RULE_ALLOW_METERED_FOREGROUND | 1 << 0 | Applications running in the foreground are allowed to access a metered network.|
| NET_RULE_ALLOW_METERED | 1 << 1 | Applications are allowed to access a metered network.|
| NET_RULE_REJECT_METERED | 1 << 2 | Applications are not allowed to access a metered network.|
| NET_RULE_ALLOW_ALL | 1 << 5 | Applications are allowed to access all networks (metered or non-metered).|
| NET_RULE_REJECT_ALL | 1 << 6 | Applications are not allowed to access any networks (metered or non-metered).|
## RemindType<sup>10+</sup>
Enumerates the reminder types.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name| Value| Description|
| ---------------------- | - | ------- |
| REMIND_TYPE_WARNING | 1 | Warning.|
| REMIND_TYPE_LIMIT | 2 | Limit.|
## NetUidPolicy<sup>10+</sup>
Enumerates network access policies for the application.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value| Description |
| ---------------------- | ----- | ------------ |
| NET_POLICY_NONE | 0 | Default network policy.|
| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 << 0 | Background applications are allowed to access a metered network.|
| NET_POLICY_REJECT_METERED_BACKGROUND | 1 << 1 | Applications running in the background are not allowed to access a metered network.|
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
The **statistics** module provides APIs to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID). The **statistics** module provides APIs to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID).
> **NOTE** > **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. > 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 ## Modules to Import
...@@ -589,7 +588,7 @@ For details about the error codes, see [Traffic Management Error Codes](../error ...@@ -589,7 +588,7 @@ For details about the error codes, see [Traffic Management Error Codes](../error
on(type: 'netStatsChange', callback: Callback\<{ iface: string, uid?: number }>): void on(type: 'netStatsChange', callback: Callback\<{ iface: string, uid?: number }>): void
Subscribes to data traffic change events. Subscribes to traffic change events.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -602,7 +601,7 @@ Subscribes to data traffic change events. ...@@ -602,7 +601,7 @@ Subscribes to data traffic change events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. This field has a fixed value of **netStatsChange**.| | type | string | Yes | Event type. This field has a fixed value of **netStatsChange**.|
| callback | Callback\<{ iface: string, uid?: number }\> | Yes | Callback invoked when the data traffic changes.<br>**iface**: NIC name.<br>**uid**: application UID.| | callback | Callback\<{ iface: string, uid?: number }\> | Yes | Callback invoked when the traffic changes.<br>**iface**: NIC name.<br>**uid**: application UID.|
**Error codes** **Error codes**
...@@ -628,7 +627,7 @@ For details about the error codes, see [Traffic Management Error Codes](../error ...@@ -628,7 +627,7 @@ For details about the error codes, see [Traffic Management Error Codes](../error
off(type: 'netStatsChange', callback?: Callback\<{ iface: string, uid?: number }>): void; off(type: 'netStatsChange', callback?: Callback\<{ iface: string, uid?: number }>): void;
Unsubscribes from data traffic change events. Unsubscribes from traffic change events.
**System API**: This is a system API. **System API**: This is a system API.
...@@ -641,7 +640,7 @@ Unsubscribes from data traffic change events. ...@@ -641,7 +640,7 @@ Unsubscribes from data traffic change events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- | | -------- | --------------------------------------- | ---- | ---------- |
| type | string | Yes | Event type. This field has a fixed value of **netStatsChange**.| | type | string | Yes | Event type. This field has a fixed value of **netStatsChange**.|
| callback | Callback\<{ iface: string, uid?: number }\> | No | Callback invoked when the data traffic changes.<br>**iface**: NIC name.<br>uid: application UID.| | callback | Callback\<{ iface: string, uid?: number }\> | No | Callback invoked when the traffic changes.<br>**iface**: NIC name.<br>uid: application UID.|
**Error codes** **Error codes**
......
...@@ -117,4 +117,59 @@ Data is added, deleted, and modified continuously without closing the read trans ...@@ -117,4 +117,59 @@ Data is added, deleted, and modified continuously without closing the read trans
**Solution** **Solution**
1. Check for unclosed result sets or transactions. 1. Check for unclosed result sets or transactions.
2. Closes all result sets or transactions. 2. Closes all result sets or transactions.
## 14800050 Failed to Obtain the Subscription Service
**Error Message**
Failed to obtain subscription service.
**Description**
The error code is returned when the subscription service failed to be obtained.
**Possible Causes**
The platform does not support service subscription.
**Solution**
Deploy the subscription service on the platform.
## 14801001 Stage Model Required
**Error Message**
Only supported in stage mode.
**Description**
This operation can be performed only on the stage model.
**Possible Causes**
The context is not a stage model.
**Solution**
Perform the operation on the stage model.
## 14801002 Invalid dataGroupId in storeConfig
**Error Message**
The data group id is not valid.
**Description**
The **dataGroupId** parameter is invalid.
**Possible Causes**
The **dataGroupId** is not obtained from the AppGallery.
**Solution**
Obtain **dataGroupId** from the AppGallery and pass it to **storeConfig** correctly.
# Policy Management Error Codes
> **NOTE**
>
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 2100001 Invalid Parameters
**Error Information**
Invalid parameter value.
**Description**
This error code is reported if any input parameter value is incorrect.
**Possible Causes**
The end time is earlier than the start time.
**Solution**
Check whether the start time and end time are properly set.
## 2100002 Service Connection Failure
**Error Information**
Operation failed. Cannot connect to service.
**Description**
This error code is reported if a service connection failure occurs.
**Possible Causes**
The service is abnormal.
**Solution**
Check whether system services are running properly.
## 2100003 System Internal Error
**Error Information**
System internal error.
**Description**
This error code is reported if an internal system error occurs.
**Possible Causes**
1. The memory is abnormal.
2. A null pointer is present.
**Solution**
1. Check whether the memory space is sufficient. If not, clear the memory and try again.
2. Check whether the system is normal. If not, try again later or restart the device.
...@@ -23,3 +23,57 @@ The possible causes are as follows: ...@@ -23,3 +23,57 @@ The possible causes are as follows:
1. Check that the file name is correct. 1. Check that the file name is correct.
2. Check that the file path is correct. 2. Check that the file path is correct.
## 15500019 Failed to Obtain the Subscription Service
**Error Message**
Failed to obtain subscription service.
**Description**
Failed to obtain the subscription service in inter-process event subscription.
**Possible Causes**
The platform does not support service subscription.
**Solution**
Deploy the subscription service on the platform.
## 14801001 Stage Model Required
**Error Message**
Only supported in stage mode.
**Description**
This operation can be performed only on the stage model.
**Possible Causes**
The context is not a stage model.
**Solution**
Perform the operation on the stage model.
## 15501002 The dataGroupId parameter in Options is invalid.
**Error Message**
The data group id is not valid.
**Description**
The **dataGroupId** parameter is invalid.
**Possible Causes**
The **dataGroupId** is not obtained from the AppGallery.
**Solution**
Obtain **dataGroupId** from the AppGallery and pass it correctly.
...@@ -1662,7 +1662,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api ...@@ -1662,7 +1662,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api
| HUKS_USER_AUTH_TYPE_FINGERPRINT | 0x0001 | Fingerprint authentication, which can be enabled with facial authentication and PIN authentication at the same time. | | HUKS_USER_AUTH_TYPE_FINGERPRINT | 0x0001 | Fingerprint authentication, which can be enabled with facial authentication and PIN authentication at the same time. |
| HUKS_USER_AUTH_TYPE_FACE | 0x0002 | Facial authentication, whch can be enabled with fingerprint authentication and PIN authentication at the same time. | | HUKS_USER_AUTH_TYPE_FACE | 0x0002 | Facial authentication, whch can be enabled with fingerprint authentication and PIN authentication at the same time. |
| HUKS_USER_AUTH_TYPE_PIN | 0x0004 | PIN authentication, which can be enabled with fingerprint authentication and facial authenticationat the same time. | | HUKS_USER_AUTH_TYPE_PIN | 0x0004 | PIN authentication, which can be enabled with fingerprint authentication and facial authenticationat the same time. |
| | | |
**Table 4** Secure access types **Table 4** Secure access types
...@@ -1670,7 +1670,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api ...@@ -1670,7 +1670,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api
| --------------------------------------- | ----- | ------------------------------------------------------------ | | --------------------------------------- | ----- | ------------------------------------------------------------ |
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. | | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication. | | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication. |
| | | |
**Table 5** Challenge types **Table 5** Challenge types
...@@ -1679,7 +1679,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api ...@@ -1679,7 +1679,7 @@ When a key is generated or imported, [HuksUserAuthType](../reference/apis/js-api
| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key. | | HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key. |
| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys. | | HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys. |
| HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication. | | HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication. |
| | | |
> **NOTICE** > **NOTICE**
> >
......
# Obtaining Source Code<a name="EN-US_TOPIC_0000001150448437"></a> # Obtaining Source Code
## About OpenHarmony<a name="section6370143622110"></a>
OpenHarmony is an open-source project launched by the OpenAtom Foundation. The purpose of this project is to build an open, distributed operating system \(OS\) framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era. ## About OpenHarmony
The open-source code repositories are available at [https://openharmony.gitee.com](https://openharmony.gitee.com). OpenHarmony is an open source project launched by the OpenAtom Foundation. The purpose of this project is to build an open, distributed operating system (OS) framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era.
## Overview of Source Code Acquisition<a name="section12763342204"></a>
The OpenHarmony source code is open to you as [HPM parts](../hpm-part/hpm-part-about.md), which can be obtained in any of the following ways:
- **Method 1**: Acquire the source code from the Gitee code repository. You can use the **repo** or **git** tool to download the latest code from the code repository. The open source code repositories are available at [https://openharmony.gitee.com](https://openharmony.gitee.com).
- **Method 2**: Acquire the source code from [DevEco Marketplace](https://repo.harmonyos.com/#/en/home). Visit [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), search for your desired open-source distribution, and download the bundle list \(or customize bundles and download the bundle list\). Then use the **hpm-cli** tool to download and install the bundles and compilation toolchain on your local PC.
- **Method 3**: Download the compressed file of a distribution from a mirror site. This method provides a fast download speed, so you can also use this method for obtaining the source code of an earlier version.
- **Method 4**: Acquire the source code from the GitHub image repository. You can use the **repo** or **git** tool to download the latest code from the code repository.
## Method 1: Acquiring Source Code from the Gitee Code Repository<a name="section537312010229"></a>
### When to Use<a name="section10881513459"></a> ## Overview of Source Code Acquisition
- You want to establish a baseline based on stable OpenHarmony releases and distribute the baseline to your customers. This document describes how to acquire OpenHarmony source code and provides its directory structure. The OpenHarmony source code is open to you as [HPM parts](../hpm-part/hpm-part-about.md), which can be obtained in any of the following ways:
- You have interconnected your software with OpenHarmony and need official certification from OpenHarmony. - **Method 1**: Acquire the source code from the Gitee code repository. You can use the **repo** or **git** tool to download the latest code from the code repository.
- You want to contribute code to the OpenHarmony community after obtaining official OpenHarmony certification for chips, modules, and applications. - **Method 2**: Acquire the source code from [DevEco Marketplace](https://repo.harmonyos.com/#/en/home). Visit [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), search for your desired open source distribution, and download the component list (or customize components and download the component list). Then use the **hpm-cli** tool to download and install the components and compilation toolchain on your local PC.
- You need to rectify OpenHarmony issues. - **Method 3**: Download the compressed file of a distribution from a mirror site. This method provides a fast download speed, so you can also use this method for obtaining the source code of an earlier version.
- You want to learn OpenHarmony source code. - **Method 4**: Acquire the source code from the GitHub image repository. You can use the **repo** or **git** tool to download the latest code from the code repository.
### Prerequisites<a name="section102871547153314"></a> ## Method 1: Acquiring Source Code from the Gitee Code Repository
1. Register your account with Gitee.
2. Register an SSH public key for access to Gitee.
3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure basic user information.
```shell ### When to Use
git config --global user.name "yourname"
git config --global user.email "your-email-address"
git config --global credential.helper store
```
4. Run the following commands to install the **repo** tool: - You want to establish a baseline based on stable OpenHarmony releases and distribute the baseline to your customers.
- You have interconnected your software with OpenHarmony and need official certification from OpenHarmony.
- You want to contribute code to the OpenHarmony community after obtaining official OpenHarmony certification for chips, modules, and applications.
- You need to rectify OpenHarmony issues.
- You want to learn OpenHarmony source code.
### Prerequisites
1. Register your account with Gitee.
2. Register an SSH public key for access to Gitee.
3. Install the [Git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure basic user information.
```shell
git config --global user.name "yourname"
git config --global user.email "your-email-address"
git config --global credential.helper store
```
4. Install the **repo** tool:
In this example, **~/bin** is used as an example installation directory. You can change the directory as needed. In this example, **~/bin** is used as an example installation directory. You can change the directory as needed.
...@@ -62,115 +73,122 @@ The OpenHarmony source code is open to you as [HPM parts](../hpm-part/hpm-part-a ...@@ -62,115 +73,122 @@ The OpenHarmony source code is open to you as [HPM parts](../hpm-part/hpm-part-a
``` ```
### How to Use<a name="section429012478331"></a> ### Procedure
>![](../public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> >
>Download the release code, which is more stable, if you want to develop commercial functionalities. Download the master code if you want to get quick access to the latest features for your development. > Download the release code, which is more stable, if you want to develop commercial functionalities. Download the master code if you want to get quick access to the latest features for your development.
- **Obtaining OpenHarmony release code** - **Obtaining OpenHarmony release code**
For details about how to obtain the source code of an OpenHarmony release, see the [Release Notes](../../release-notes/Readme.md). For details about how to obtain the source code of an OpenHarmony release, see the [Release Notes](../../release-notes/Readme.md).
- **Obtaining OpenHarmony master code** - **Obtaining OpenHarmony master code**
Method 1 (recommended): Use the **repo** tool to download the source code over SSH. (You must have registered an SSH public key for access to Gitee.)
```shell
repo init -u git@gitee.com:openharmony/manifest.git -b master --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
Method 1 \(recommended\): Use the **repo** tool to download the source code over SSH. \(You must have registered an SSH public key for access to Gitee.\) Method 2: Use the **repo** tool to download the source code over HTTPS.
```shell
repo init -u git@gitee.com:openharmony/manifest.git -b master --no-repo-verify ```shell
repo sync -c repo init -u https://gitee.com/openharmony/manifest.git -b master --no-repo-verify
repo forall -c 'git lfs pull' repo sync -c
``` repo forall -c 'git lfs pull'
```
Method 2: Use the **repo** tool to download the source code over HTTPS.
```shell ## Method 2: Acquiring Source Code from DevEco Marketplace
repo init -u https://gitee.com/openharmony/manifest.git -b master --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
## Method 2: Acquiring Source Code from DevEco Marketplace<a name="section463013147412"></a> ### When to Use
### When to Use<a name="section26661067443"></a> If OpenHarmony is new to you, sample solutions are helpful to your development. You can obtain an open source distribution from [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), or customize a distribution by adding or deleting components of an open source distribution. Then use the **hpm-cli** tool to download and install the components and compilation toolchain on your local PC.
If OpenHarmony is new to you, sample solutions are helpful to your development. You can obtain an open-source distribution from [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), or customize a distribution by adding or deleting bundles of an open-source distribution. Then use the **hpm-cli** tool to download and install the bundles and compilation toolchain on your local PC.
### Prerequisites<a name="section17544943123315"></a> ### Prerequisites
You must install **Node.js** and HPM on your local PC. The installation procedure is as follows: You must install **Node.js** and HPM on your local PC. The installation procedure is as follows:
1. Install **Node.js**. 1. Install **Node.js**.
Download **Node.js** from its official website and install it on your local PC. Download **Node.js** from its official website, and install it on your local PC.
The [Node.js](https://nodejs.org/) version must be 12.x \(including npm 6.14.4\) or later. An LTS version is recommended. The [Node.js](https://nodejs.org/) version must be 12.x (including npm 6.14.4) or later. An LTS version is recommended.
2. Install the **hpm-cli** tool using **npm** delivered with **Node.js**. 2. Install the **hpm-cli** tool using **npm** delivered with **Node.js**.
Open the CMD window and run the following command: Open the CMD window, and run the following command:
```shell ```shell
npm install -g @ohos/hpm-cli npm install -g @ohos/hpm-cli
``` ```
3. Run the following command to check whether the installation is successful. If the HPM version is displayed, the installation is successful. 3. Run the following command to check whether the installation is successful. If the HPM version is displayed, the installation is successful.
```shell
hpm -V or hpm --version
```
```shell 4. Upgrade the HPM version as needed.
hpm -V or hpm --version
``` ```shell
npm update -g @ohos/hpm-cli
```
4. Run the following command to upgrade the HPM version:
```shell ### Procedure
npm update -g @ohos/hpm-cli
```
1. Search for distributions.
1. Access [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), and click **Device**. Then go to the **Open Source Distribution** page.
2. Enter a keyword, for example, **camera**, in the search box. All matched distributions are displayed.
3. Specify filter criteria, such as the OS, board, and kernel, to further filter the distributions.
4. Find your desired distribution, and click it to view details.
### How to Use<a name="section954619433333"></a> **Figure 1** HPM page
1. Search for distributions. ![](figures/hpm-page.png "hpm-page")
1. Access [DevEco Marketplace](https://repo.harmonyos.com/#/en/home), and click **Device**. Then go to the **Open Source Distribution** page.
2. Enter a keyword \(for example: **camera**\) in the search box. All matched distributions are found.
3. Specify filter criteria, such as the bundle type \(for example: **Board Support** or **Kernel Support**\), to further filter the distributions.
4. Find your desired distribution and click it to view details.
**Figure 1** HPM page<a name="fig349416264520"></a> 2. Learn more about the distribution.
![](figures/hpm-page.png "hpm-page") 1. Read carefully the information about the distribution to learn its application scenarios, features, components, usage, and customization methods.
2. Click **Download** if you want to download the distribution to your local PC.
3. Click **Device component tailoring** if you want to add or delete components of the distribution.
2. Learn more about the distribution. **Figure 2** Example distribution
1. Read carefully the information about the distribution to learn its application scenarios, features, bundles, usage, and customization methods, as shown in the following figure. ![](figures/example-distribution.png "example-distribution")
2. Click **Download** if you want to download the distribution to your local PC.
3. Click **Custom** if you want to add or delete bundles of the distribution.
**Figure 2** Example distribution<a name="fig142484411121"></a> 3. Customize components.
![](figures/example-distribution.png "example-distribution") 1. Access the **Device Component Tailoring** page.
2. Add or delete components.
- In the **Customizable Components** pane, click the plus sign. In the displayed dialog box, add required components.
- In the **Customizable Components** pane, click the minus sign next to a component to delete it.
3. Enter the basic information about your project, including the name, version, and description, on the right pane.
4. Click **Download**. The system generates the OpenHarmony code structure file (for example, **my_cust_dist.zip**) and saves it to your local PC.
3. Customize bundles. **Figure 3** Customizing components
1. Access the **Custom solution** page, as shown in the following figure.
2. Set the toggle switch next to a specific optional bundle to delete it from the distribution, or click **Add bundle** to add new bundles.
3. Enter the basic information about your project, including the bundle name, version, and description, on the right pane.
4. Click **Download**. The system generates the OpenHarmony code structure file \(for example, **my\_cust\_dist.zip**\) and saves it to your local PC.
**Figure 3** Customizing bundles<a name="fig1256020372197"></a> ![](figures/customizing-bundles.png "customizing-bundles")
![](figures/customizing-bundles.png "customizing-bundles")
4. Install bundles. 4. Install components.
1. Decompress the downloaded code structure file using CMD on Windows (or shell in Linux). 1. Decompress the downloaded code structure file using CMD on Windows (or shell in Linux).
2. In the generated directory, run the **hpm install** command to download and install bundles. If the **Install successful** message is displayed, the command has been executed successfully. 2. In the generated directory, run the **hpm install** command to download and install components. If the **Install successful** message is displayed, the command has been executed successfully.
3. Obtain the bundles. The downloaded bundles are stored in the **ohos\_bundles** folder under the project directory. \(The source code of some bundles will be copied to a specified directory after the bundles are installed.\) 3. The downloaded components will be stored in the **ohos_bundles** folder under the project directory. (The source code of some components will be copied to a specified directory after the components are installed.)
## Method 3: Acquiring Source Code from a Mirror Site<a name="section1186691118430"></a> ## Method 3: Acquiring Source Code from a Mirror Site
To ensure the download performance, you are advised to download the source code or the corresponding solution from the image library of the respective site listed in the table below. To ensure the download performance, you are advised to download the source code or the corresponding solution from the image library of the respective site listed in the table below.
The table below provides only the sites for downloading the latest OpenHarmony LTS code. For details about how to obtain the source code of earlier versions, see the [Release Notes](../../release-notes/Readme.md). The table below provides only the sites for downloading the latest OpenHarmony LTS code. For details about how to obtain the source code of earlier versions, see the [Release Notes](../../release-notes/Readme.md).
**Table 1** Sites for acquiring source code **Table 1** Sites for acquiring source code
| **LTS Code**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**| | **LTS Code**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
...@@ -191,13 +209,14 @@ The table below provides only the sites for downloading the latest OpenHarmony L ...@@ -191,13 +209,14 @@ The table below provides only the sites for downloading the latest OpenHarmony L
| **Compiler Toolchain**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**| | **Compiler Toolchain**| **Version**| **Site**| **SHA-256 Checksum**| **Software Package Size**|
| Compiler toolchain| - | [Download](https://repo.huaweicloud.com/openharmony/os/2.0/tool_chain/)| - | - | | Compiler toolchain| - | [Download](https://repo.huaweicloud.com/openharmony/os/2.0/tool_chain/)| - | - |
## Method 4: Acquiring Source Code from the GitHub Image Repository<a name="section23448418360"></a>
>![](../public_sys-resources/icon-note.gif) **NOTE** ## Method 4: Acquiring Source Code from the GitHub Image Repository
>
> **NOTE**<br>
> The image repository is synchronized at 23:00 (UTC +8:00) every day. > The image repository is synchronized at 23:00 (UTC +8:00) every day.
Method 1 \(recommended\): Use the **repo** tool to download the source code over SSH. \(You must have registered an SSH public key for access to GitHub. For details, see [Adding a new SSH key to your GitHub account](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account).\)
Method 1 (recommended): Use the **repo** tool to download the source code over SSH. (You must have registered an SSH public key for access to GitHub. For details, see [Adding a new SSH key to your GitHub account](https://docs.github.com/en/authentication/connecting-to-github-with-ssh/adding-a-new-ssh-key-to-your-github-account).)
```shell ```shell
repo init -u git@github.com:openharmony/manifest.git -b master --no-repo-verify repo init -u git@github.com:openharmony/manifest.git -b master --no-repo-verify
...@@ -207,23 +226,25 @@ repo forall -c 'git lfs pull' ...@@ -207,23 +226,25 @@ repo forall -c 'git lfs pull'
Method 2: Use the **repo** tool to download the source code over HTTPS. Method 2: Use the **repo** tool to download the source code over HTTPS.
```shell ```shell
repo init -u https://github.com/openharmony/manifest.git -b master --no-repo-verify repo init -u https://github.com/openharmony/manifest.git -b master --no-repo-verify
repo sync -c repo sync -c
repo forall -c 'git lfs pull' repo forall -c 'git lfs pull'
``` ```
## Source Code Directories<a name="section1072115612811"></a>
## Source Code Directories
The following table describes the OpenHarmony source code directories. The following table describes the OpenHarmony source code directories.
**Table 2** Source code directories **Table 2** Source code directories
| Directory| Description| | **Directory**| **Description**|
| -------- | -------- | | -------- | -------- |
| applications | Application samples, for example, **camera**.| | applications | Application samples, for example, **camera**.|
| base | Basic software service subsystem set and hardware service subsystem set.| | base | Basic software service subsystem set and hardware service subsystem set.|
| build | Bundle-based compilation, building, and configuration scripts.| | build | Component-based compilation, building, and configuration scripts.|
| docs | Reference documents.| | docs | Reference documents.|
| domains | Enhanced software service subsystem set.| | domains | Enhanced software service subsystem set.|
| drivers | Driver subsystem.| | drivers | Driver subsystem.|
...@@ -231,9 +252,7 @@ The following table describes the OpenHarmony source code directories. ...@@ -231,9 +252,7 @@ The following table describes the OpenHarmony source code directories.
| kernel | Kernel subsystem.| | kernel | Kernel subsystem.|
| prebuilts | Compiler and tool chain subsystem.| | prebuilts | Compiler and tool chain subsystem.|
| test | Test subsystem.| | test | Test subsystem.|
| third_party | Open-source third-party software.| | third_party | Open source third-party software.|
| utils | Commonly used development utilities.| | utils | Commonly used development utilities.|
| vendor | Vendor-provided software.| | vendor | Vendor-provided software.|
| build.py | Build script file.| | build.py | Build script file.|
<!--no_check-->
...@@ -7,7 +7,8 @@ OpenHarmony is an open OS that allows you to easily develop services and applica ...@@ -7,7 +7,8 @@ OpenHarmony is an open OS that allows you to easily develop services and applica
This environment combines chip security and system security features with upper-layer security services to secure hardware, the system, data, device interconnection, applications, and updates. This environment combines chip security and system security features with upper-layer security services to secure hardware, the system, data, device interconnection, applications, and updates.
**Figure 1** Security assurance
**Figure 1** Security assurance
![](figures/security-assurance-framework.png) ![](figures/security-assurance-framework.png)
...@@ -18,32 +19,36 @@ This environment combines chip security and system security features with upper- ...@@ -18,32 +19,36 @@ This environment combines chip security and system security features with upper-
### Security Mechanism ### Security Mechanism
- Boot root of trust - Boot root of trust
OpenHarmony devices use the public key infrastructure (PKI) to protect software integrity and ensure that the software source is valid and the software is not tampered with. OpenHarmony devices use the public key infrastructure (PKI) to protect software integrity and ensure that the software source is valid and the software is not tampered with.
In the device boot process, software signature verification is performed at each phase to form a secure boot chain. If signature verification fails at any phase, the device boot will be terminated. The hardware or software entity that initially performs signature verification in the secure boot chain is the boot root of trust. It must be valid and should not be tampered with. The boot root of trust can be a built-in code segment in the read-only memory (ROM). This code segment is written in the chip during the chip manufacturing and cannot be modified later. When the device is powered on and initialized, this code segment is executed first and used to verify software signatures. In the device boot process, software signature verification is performed at each phase to form a secure boot chain. If signature verification fails at any phase, the device boot will be terminated. The hardware or software entity that initially performs signature verification in the secure boot chain is the boot root of trust. It must be valid and should not be tampered with. The boot root of trust can be a built-in code segment in the read-only memory (ROM). This code segment is written in the chip during the chip manufacturing and cannot be modified later. When the device is powered on and initialized, this code segment is executed first and used to verify software signatures.
When you use the code for signature verification, ensure the validity of the PKI public keys. OpenHarmony devices use a storage medium such as eFUSE and one-time password (OTP) to store the public keys (for example, their hash values) and guarantee their validity. A public key is usually programed into the eFuse or OTP of a device during device manufacturing. When you use the code for signature verification, ensure the validity of the PKI public keys. OpenHarmony devices use a storage medium such as eFUSE and one-time password (OTP) to store the public keys (for example, their hash values) and guarantee their validity. A public key is usually programed into the eFuse or OTP of a device during device manufacturing.
- Hardware-isolated trusted environment - Hardware-isolated trusted environment
The hardware-isolated trusted environment complies with the design concept of the trusted computing system. There is a clear boundary between the trusted environment and untrusted one. OpenHarmony devices protect core sensitive data in the trusted environment. Even if OS vulnerabilities in the untrusted environment are exploited, sensitive data in the trusted environment is secure. The hardware-isolated trusted environment complies with the design concept of the trusted computing system. There is a clear boundary between the trusted environment and untrusted one. OpenHarmony devices protect core sensitive data in the trusted environment. Even if OS vulnerabilities in the untrusted environment are exploited, sensitive data in the trusted environment is secure.
The trusted environment of OpenHarmony devices is built based on a hardware security isolation mechanism. The chip isolation mechanism varies slightly on different OpenHarmony devices, and the most common mechanism is Arm TrustZone. On some RISC-V chip platforms, independent security cores may also be used to build a trusted environment. The trusted environment of OpenHarmony devices is built based on a hardware security isolation mechanism. The chip isolation mechanism varies slightly on different OpenHarmony devices, and the most common mechanism is Arm TrustZone. On some RISC-V chip platforms, independent security cores may also be used to build a trusted environment.
A specific, simplified OS iTrustee lite runs in the trusted environment to manage resources and schedule tasks in the environment and provide security services for OpenHarmony devices. Key management and data security are the most common security services in the trusted environment. A device has a unique hardware root key in the eFuse/OTP. Based on this root key and service context, the trusted environment generates multiple keys that provide key management and data encryption/decryption services for applications. During their whole lifecycle, core keys of devices stay in the trusted environment. The trusted environment also provides security services such as identity authentication, system status monitoring, and secure data storage to enhance device security. A specific, simplified OS iTrustee lite runs in the trusted environment to manage resources and schedule tasks in the environment and provide security services for OpenHarmony devices. Key management and data security are the most common security services in the trusted environment. A device has a unique hardware root key in the eFuse/OTP. Based on this root key and service context, the trusted environment generates multiple keys that provide key management and data encryption/decryption services for applications. During their whole lifecycle, core keys of devices stay in the trusted environment. The trusted environment also provides security services such as identity authentication, system status monitoring, and secure data storage to enhance device security.
- Hardware key engine - Hardware key engine
Cryptography is the basis of information security. Data encryption/decryption requires high efficiency and security of computing devices. Hardware encryption/decryption technologies use computer hardware to assist or even replace software to encrypt or decrypt data. Hardware-based encryption/decryption is more efficient and secure than software-based encryption/decryption. Cryptography is the basis of information security. Data encryption/decryption requires high efficiency and security of computing devices. Hardware encryption/decryption technologies use computer hardware to assist or even replace software to encrypt or decrypt data. Hardware-based encryption/decryption is more efficient and secure than software-based encryption/decryption.
Since some dedicated hardware resources are used for data encryption/decryption, the CPU can concurrently execute other computing tasks, which greatly improves performance and reduces the CPU load. In addition, a well-designed hardware key engine protects keys from leak even if the software is cracked and even defends against electromagnetic and radiation attacks from physical channels. Since some dedicated hardware resources are used for data encryption/decryption, the CPU can concurrently execute other computing tasks, which greatly improves performance and reduces the CPU load. In addition, a well-designed hardware key engine protects keys from leak even if the software is cracked and even defends against electromagnetic and radiation attacks from physical channels.
OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard (AES) and Rivest-Shamir-Adleman (RSA). OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard (AES) and Rivest-Shamir-Adleman (RSA).
### Recommended Practices ### Recommended Practices
- The boot root of trust consists of a built-in code segment in the chip and the root key of the device. The root of trust is written into the chip during manufacturing and cannot be modified in the device lifecycle. It is used to verify software certificates in the device boot process. The root key is the public key matching the private key of the device certificate signature. The private key is maintained on the PKI signature server and the public key is written to the device. To prevent attackers from tampering with the public key to bypass signature authentication, you can write the public key to media such as fuses on OpenHarmony devices. Considering that the fuse space is limited, you can store only the hash value of the public key in the fuse and verify the validity of the public key using the boot code. - The boot root of trust consists of a built-in code segment in the chip and the root key of the device. The root of trust is written into the chip during manufacturing and cannot be modified in the device lifecycle. It is used to verify software certificates in the device boot process. The root key is the public key matching the private key of the device certificate signature. The private key is maintained on the PKI signature server and the public key is written to the device. To prevent attackers from tampering with the public key to bypass signature authentication, you can write the public key to media such as fuses on OpenHarmony devices. Considering that the fuse space is limited, you can store only the hash value of the public key in the fuse and verify the validity of the public key using the boot code.
- Generally, a trusted execution environment (TEE) is built based on the Arm TrustZone technology, and can also adopt other isolation mechanisms, such as TrustZone-M and independent security cores, depending on the device form. A TEE OS must be deployed in the TEE to manage resources and schedule tasks. OpenHarmony provides iTrustee as the TEE OS. You can develop and deploy security services based on iTrustee. - Generally, a trusted execution environment (TEE) is built based on the Arm TrustZone technology, and can also adopt other isolation mechanisms, such as TrustZone-M and independent security cores, depending on the device form. A TEE OS must be deployed in the TEE to manage resources and schedule tasks. OpenHarmony provides iTrustee as the TEE OS. You can develop and deploy security services based on iTrustee.
Not all OpenHarmony devices need to support the TEE, for example, some devices with thin resources that run less sensitive services may not need the TEE. You can choose whether to support the TEE and how to implement the TEE based on service requirements. Not all OpenHarmony devices need to support the TEE, for example, some devices with thin resources that run less sensitive services may not need the TEE. You can choose whether to support the TEE and how to implement the TEE based on service requirements.
- The hardware key engine must provide key algorithms related to true random numbers, public keys, symmetric keys, and hash values. By deploying required drivers in OpenHarmony, you can provide unified key management and key algorithms for applications. - The hardware key engine must provide key algorithms related to true random numbers, public keys, symmetric keys, and hash values. By deploying required drivers in OpenHarmony, you can provide unified key management and key algorithms for applications.
...@@ -72,8 +77,8 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom ...@@ -72,8 +77,8 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom
The following figure shows how DAC works when a process accesses a file. The DAC first matches the process UID with the file UID, and then the process GID with the file GID. If the UID and GID both fail to match, DAC checks the **other** attribute of the file to determine whether the process is allowed to read, write, or execute the file. In addition, the system supports a privileged capability that is not subject to DAC mechanism (read, write, and execute) and can access files directly. Services with high permissions (such as system services) can manage files of applications with low permissions (such as third-party applications). The following figure shows how DAC works when a process accesses a file. The DAC first matches the process UID with the file UID, and then the process GID with the file GID. If the UID and GID both fail to match, DAC checks the **other** attribute of the file to determine whether the process is allowed to read, write, or execute the file. In addition, the system supports a privileged capability that is not subject to DAC mechanism (read, write, and execute) and can access files directly. Services with high permissions (such as system services) can manage files of applications with low permissions (such as third-party applications).
**Figure 2** How DAC works **Figure 2** How DAC works
![](figures/how-dac-works.png) ![](figures/how-dac-works.png)
- Capability mechanism - Capability mechanism
...@@ -94,14 +99,14 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom ...@@ -94,14 +99,14 @@ For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recom
- Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade (if available) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade. - Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade (if available) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade.
## Data Security ## Data security
### Security Mechanism ### Security Mechanism
OpenHarmony Universal KeyStore (HUKS) provides key and certificate management. For OpenHarmony, it mainly provides key management for HiChain (device identity authentication platform). The figure below shows the HUKS functions. OpenHarmony Universal KeyStore (HUKS) provides key and certificate management. For OpenHarmony, it mainly provides key management for HiChain (device identity authentication platform). The figure below shows the HUKS functions.
**Figure 3** HUKS functions **Figure 3** HUKS functions
![](figures/huks-functions.png) ![](figures/huks-functions.png)
...@@ -143,39 +148,35 @@ To use the device certification function, it is recommended that you use HiChain ...@@ -143,39 +148,35 @@ To use the device certification function, it is recommended that you use HiChain
To ensure secure transmit of user data between devices, a trust relationship and a secure data transmission channel must be established between the devices. The following figure shows how an IoT controller and an IoT device establish a trust relationship. To ensure secure transmit of user data between devices, a trust relationship and a secure data transmission channel must be established between the devices. The following figure shows how an IoT controller and an IoT device establish a trust relationship.
**Figure 4** Process of establishing a trust relationship between devices
**Figure 4** Process of establishing a trust relationship between devices
![](figures/how-an-iot-controller-and-an-iot-device-establish-a-trust-relationship.png) ![](figures/how-an-iot-controller-and-an-iot-device-establish-a-trust-relationship.png)
- IoT device interconnection security - IoT device interconnection security
A trust relationship can be established between an IoT device that runs OpenHarmony (such as an AI speaker, smart home device, and wearable) and an IoT controller. Encrypted user data is transmitted between the IoT device and IoT controller through a secure connection.
A trust relationship can be established between an IoT device that runs OpenHarmony (such as an AI speaker, smart home device, and wearable) and an IoT controller. Encrypted user data is transmitted between the IoT device and IoT controller through a secure connection.
- IoT service identifier of the IoT controller - IoT service identifier of the IoT controller
An IoT controller generates different identifiers for different IoT device management services to isolate these services. The identifier can be used for authentication and communication between an IoT controller and an IoT device. It is an Ed25519 public/private key pair generated using the elliptic curve cryptography.
An IoT controller generates different identifiers for different IoT device management services to isolate these services. The identifier can be used for authentication and communication between an IoT controller and an IoT device. It is an Ed25519 public/private key pair generated using the elliptic curve cryptography.
- IoT device identifier - IoT device identifier
An IoT device can generate its own device identifier for communicating with the IoT controller. It is also an Ed25519 public/private key pair generated using elliptic curve cryptography, with the private key stored on the IoT device. Each time the device is restored to factory settings, the public/private key pair will be reset. An IoT device can generate its own device identifier for communicating with the IoT controller. It is also an Ed25519 public/private key pair generated using elliptic curve cryptography, with the private key stored on the IoT device. Each time the device is restored to factory settings, the public/private key pair will be reset.
The identifier can be used for secure communication between the IoT controller and IoT device. After the devices exchange the service identifier or device identifier, they can negotiate the key and establish a secure communication channel.
The identifier can be used for secure communication between the IoT controller and IoT device. After the devices exchange the service identifier or device identifier, they can negotiate the key and establish a secure communication channel.
- P2P trusted binding between devices - P2P trusted binding between devices
When an IoT controller and an IoT device establish a trust relationship, they exchange identifiers. When an IoT controller and an IoT device establish a trust relationship, they exchange identifiers.
During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange (PAKE), and use the session key to encrypt the channel for exchanging identity public keys.
During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange (PAKE), and use the session key to encrypt the channel for exchanging identity public keys.
- Secure communication between the IoT controller and IoT device - Secure communication between the IoT controller and IoT device
When an IoT controller and an IoT device communicate with each other after establishing a trust relationship, they authenticate each other by using the locally stored identity public key of the peer. Bidirectional identity authentication and session key exchange are performed using the Station-to-Station (STS) protocol during each communication. The session key is used to encrypt the data transmission channel between the devices.
When an IoT controller and an IoT device communicate with each other after establishing a trust relationship, they authenticate each other by using the locally stored identity public key of the peer. Bidirectional identity authentication and session key exchange are performed using the Station-to-Station (STS) protocol during each communication. The session key is used to encrypt the data transmission channel between the devices.
## Application Security ## Application Security
...@@ -183,32 +184,30 @@ To ensure secure transmit of user data between devices, a trust relationship and ...@@ -183,32 +184,30 @@ To ensure secure transmit of user data between devices, a trust relationship and
### Security Mechanism ### Security Mechanism
- Application signature management - Application signature management
After developing and debugging an OpenHarmony application, sign the application installation package using a private key, which matches a public key. Generally, the OEM generates a public/private key pair, presets the public key in the device, and stores the private key on a local server that is not connected to the Internet to prevent private key leakage. After you finish developing an application, you can use an external device (such as a USB flash drive) to upload the installation package to the server where the private key is stored, calculate the signature, and download the signature to the external device. During application installation, the hash value of the bundle is calculated using the SHA-256 algorithm. The hash value, together with the signature and preset public key, is used for authentication. The application can be installed only after the authentication is successful. After developing and debugging an OpenHarmony application, sign the application installation package using a private key, which matches a public key. Generally, the OEM generates a public/private key pair, presets the public key in the device, and stores the private key on a local server that is not connected to the Internet to prevent private key leakage. After you finish developing an application, you can use an external device (such as a USB flash drive) to upload the installation package to the server where the private key is stored, calculate the signature, and download the signature to the external device. During application installation, the hash value of the bundle is calculated using the SHA-256 algorithm. The hash value, together with the signature and preset public key, is used for authentication. The application can be installed only after the authentication is successful.
In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer.
In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer.
- Application permission control
OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may require in the application configuration file. The permissions can be static or dynamic. Static permissions need to be registered during application installation, and dynamic permissions can be obtained only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor.
- Application permission control
**Table 1** OpenHarmony system permissions OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may require in the application configuration file. The permissions can be static or dynamic. Static permissions need to be registered during application installation, and dynamic permissions can be obtained only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor.
| Permission| **Authorization Mode**| **Description**| **Table 1** OpenHarmony system permissions
| -------- | -------- | -------- |
| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant (static permission)| Allows an application to listen for application changes.| | Permission| **Authorization Mode**| **Description**|
| ohos.permission.GET_BUNDLE_INFO | system_grant (static permission)| Allows an application to obtain information about other applications.| | -------- | -------- | -------- |
| ohos.permission.INSTALL_BUNDLE | system_grant (static permission)| Allows an application to install other applications.| | ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant (static permission)| Allows an application to listen for application changes.|
| ohos.permission.CAMERA | user_grant (dynamic permission)| Allows an application to use the camera to take photos and record videos at any time.| | ohos.permission.GET_BUNDLE_INFO | system_grant (static permission)| Allows an application to obtain information about other applications.|
| ohos.permission.MODIFY_AUDIO_SETTINGS | system_grant (static permission)| Allows an application to modify global audio settings, such as the volume and speaker for output.| | ohos.permission.INSTALL_BUNDLE | system_grant (static permission)| Allows an application to install other applications.|
| ohos.permission.READ_MEDIA | user_grant (dynamic permission)| Allows an application to read users' favorite videos.| | ohos.permission.CAMERA | user_grant (dynamic permission)| Allows an application to use the camera to take photos and record videos at any time.|
| ohos.permission.MICROPHONE | user_grant (dynamic permission)| Allows an application to use the microphone for audio recording at any time.| | ohos.permission.MODIFY_AUDIO_SETTINGS | system_grant (static permission)| Allows an application to modify global audio settings, such as the volume and speaker for output.|
| ohos.permission.WRITE_MEDIA | user_grant (dynamic permission)| Allows an application to write users' favorite music.| | ohos.permission.READ_MEDIA | user_grant (dynamic permission)| Allows an application to read users' favorite videos.|
| ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an application to manage distributed data transmission.| | ohos.permission.MICROPHONE | user_grant (dynamic permission)| Allows an application to use the microphone for audio recording at any time.|
| ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an application to use distributed virtualization features.| | ohos.permission.WRITE_MEDIA | user_grant (dynamic permission)| Allows an application to write users' favorite music.|
| ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an application to manage distributed data transmission.|
| ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an application to use distributed virtualization features.|
### Recommended Practices ### Recommended Practices
...@@ -217,4 +216,3 @@ When developing an application, determine the permissions required by your appli ...@@ -217,4 +216,3 @@ When developing an application, determine the permissions required by your appli
> **NOTE** > **NOTE**
> >
> The application configuration file varies depending on the application model. It is **config.json** for the application based on the FA model and **module.json5** for the application based on the stage mode. For details about the application models, see [Interpretation of the Application Model](../../application-dev/application-models/application-model-description.md). > The application configuration file varies depending on the application model. It is **config.json** for the application based on the FA model and **module.json5** for the application based on the stage mode. For details about the application models, see [Interpretation of the Application Model](../../application-dev/application-models/application-model-description.md).
# Privacy Protection # Privacy protection
## Overview ## Overview
Personal data plays an increasingly important role in social economy and daily life along with the development of the Internet and informatization. Meanwhile, personal data leakage risks are increasing. As consumer product developers, you shall take more effective measures to protect users' personal data and improve their trust in your products. To protect consumers' privacy and improve their experience on privacy, you should set high-level privacy protection policies for your product. Personal data plays an increasingly important role in social economy and daily life along with the development of the Internet and informatization. Meanwhile, personal data leakage risks are increasing. As a consumer product developer, you shall take more effective measures to protect users' personal data and improve their trust in your products. To protect consumers' privacy and improve their experience on privacy, you should set high-level privacy protection policies for your product.
**Basic Concepts** **Basic Concepts**
- **Personal data** - **Personal data**
Any information relating to an identified or identifiable natural person \("Data Subject"\) who can be identified, directly or indirectly, in particular by reference to an identifier such as a name, an identification number, location data, an online identifier or to one or more factors specific to the physical, physiological, genetic, mental, commercial, cultural, or social identity of that natural person. Personal data includes a natural person's email address, phone number, biometric information \(such as a fingerprint\), location data, IP address, healthcare information, religious belief, social security number, marital status, and so on. Any information relating to an identified or identifiable natural person \("Data Subject"\) who can be identified, directly or indirectly, in particular by reference to an identifier such as a name, an identification number, location data, an online identifier or to one or more factors specific to the physical, physiological, genetic, mental, commercial, cultural, or social identity of that natural person. Personal data includes a natural person's email address, phone number, biometric information \(such as a fingerprint\), location data, IP address, healthcare information, religious belief, social security number, marital status, and so on.
- **Sensitive personal data** - **Sensitive personal data**
Sensitive personal data, a critical subset of personal data, refers to the most private information of a data subject or information that may cause severe adverse impacts on a data subject once disclosed. Sensitive personal data defined in laws and regulations of EU and its members includes personal data revealing racial or ethnic origin, political opinions, religious or philosophical beliefs, trade-union membership, genetic data, biometric information, and data concerning health or sex life and sexual orientation. Sensitive personal data, as an important subset of personal data, refers to the most confidential information of a data subject or information that may adversely affect the data subject upon leakage. Sensitive personal data defined in laws and regulations of EU and its members includes personal data revealing racial or ethnic origin, political opinions, religious or philosophical beliefs, trade-union membership, genetic data, biometric information, and data concerning health or sex life and sexual orientation.
With reference to industry best practices, we also define the following data related to a natural person's identity as sensitive: bank card number, identification number, passport number, and passwords. More strict protection measures are usually required for processing sensitive personal data. With reference to industry best practices, we also define the following data related to a natural person's identity as sensitive: bank card number, identification number, passport number, and passwords. More strict protection measures are usually required for processing sensitive personal data.
- **Public available personal data** - **Public available personal data**
Personal data that is proactively disclosed by a data subject or that can be accessed on public web pages or applications, including posts and comments made on forums. Personal data that is proactively disclosed by a data subject or that can be accessed on public web pages or applications, including posts and comments made on forums.
- **User profile** - **User profile**
Any form of automated processing of personal data to assess a natural person in specific aspects, and in particular to analyze and predict the natural person's work performance, financial situation, health, personal preference, interest, creditability, behavior, and location or trace. Any form of automated processing of personal data to assess a natural person in specific aspects, and in particular to analyze and predict the natural person's work performance, financial situation, health, personal preference, interest, creditability, behavior, and location or trace.
- **Data controller** - **Data controller**
A natural or legal person, public authority, agency, or any other body that, alone or jointly with others, determines the purposes and means of personal data processing. A natural or legal person, public authority, agency, or any other body that, alone or jointly with others, determines the purposes and means of personal data processing.
- **Data processor** - **Data processor**
A natural or legal person, public authority, agency, or any other body that processes personal data on behalf of a data controller. A data processor must provide adequate protection following the data controller's requirements. A natural or legal person, public authority, agency, or any other body that processes personal data on behalf of a data controller. A data processor must provide adequate protection following the data controller's requirements.
- **Explicit consent** - **Explicit consent**
Explicit consent applies to the following scenarios where the General Data Protection Regulation \(GDPR\) allows the legitimate processing of personal data based on data subjects' explicit consent: Explicit consent applies to the following scenarios where the General Data Protection Regulation (GDPR) allows the legitimate processing of personal data based on data subjects' explicit consent:
- Processing of sensitive personal data - Processing of sensitive personal data
- Automated decision-making, including user profiles - Automated decision-making, including user profiles
- Transfer of personal data to countries without an adequate level of protection, which uses consent as the legal basis - Transfer of personal data to countries without an adequate level of protection, which uses consent as the legal basis
Explicit consent can be implemented as follows: Explicit consent can be implemented as follows:
- In the collection of specific data, display a privacy statement to notify data subjects of matters related to the processing of personal data, provide a check box which is deselected by default, and prompt data subjects to proactively select the option indicating that "I agree to process my personal data in the above manner" or click the "I agree" button. - In the collection of specific data, display a privacy statement to notify data subjects of matters related to the processing of personal data, provide a check box which is deselected by default, and prompt data subjects to proactively select the option indicating that "I agree to process my personal data in the above manner" or click the "I agree" button.
- Expressly present consent in writing and request data subjects to sign it. - Expressly present consent in writing and request data subjects to sign it.
- Ask data subjects to upload an electronic form with their signature in the system. - Ask data subjects to upload an electronic form with their signature in the system.
- Adopt the double verification method by requesting data subjects to consent via an email and then re-click the email link for verification or enter the SMS verification code. - Adopt the double verification method by requesting data subjects to consent via an email and then re-click the email link for verification or enter the SMS verification code.
- Users provide information proactively, such as scenarios where a user enters their identification number and bank card number to bind the bank card. - Users provide information proactively, such as scenarios where a user enters their identification number and bank card number to bind the bank card.
## Data Classification ## Data Classification
Data is classified into five levels: very high, high, moderate, low, and public based on the data protection objectives and consequences \(the impact of legal risks caused by data leakage or damage on individuals, organizations, or the public\). Data is classified into five levels: very high, high, moderate, low, and public based on the data protection objectives and consequences (the impact of legal risks caused by data leakage or damage on individuals, organizations, or the public).
**Table 1** Standards for data classification **Table 1** Standards for data classification
<a name="table1536524010291"></a> | **Level**| **Privacy Risk**| **Privacy Attribute**| **Typical Example**|
<table><thead align="left"><tr id="row444844052917"><th class="cellrowborder" valign="top" width="13.239999999999998%" id="mcps1.1.5.1.1"><p id="p2448740182911"><a name="p2448740182911"></a><a name="p2448740182911"></a><strong id="b2079915010139"><a name="b2079915010139"></a><a name="b2079915010139"></a>Level</strong></p> | -------- | -------- | -------- | -------- |
</th> | Very high| Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a catastrophic negative impact on that individual or group of individuals.| Sensitive personal data| DNA, race, religious belief, and sexual orientation; biometric information; original communication content; bank account password and magnetic track data|
<th class="cellrowborder" valign="top" width="26.05%" id="mcps1.1.5.1.2"><p id="p58515187465"><a name="p58515187465"></a><a name="p58515187465"></a><strong id="b52571858131320"><a name="b52571858131320"></a><a name="b52571858131320"></a>Privacy Risk</strong></p> | High| Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a severe negative impact on that individual or group of individuals.| Sensitive personal data| Social identity (such as ID card and passport number); web browsing history; tracks; content (such as images, audio, and video) uploaded to the cloud|
</th> | Moderate| Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a significant negative impact on that individual or group of individuals.| General personal data| Device ID (IMEI, SN, or OAID), user ID, basic personal information (name and address), mobile number, and email address.|
<th class="cellrowborder" valign="top" width="11.91%" id="mcps1.1.5.1.3"><p id="p2920544155210"><a name="p2920544155210"></a><a name="p2920544155210"></a><strong id="b104071711171410"><a name="b104071711171410"></a><a name="b104071711171410"></a>Privacy Attribute</strong></p> | Low| Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a limited negative impact on that individual or group of individuals.| General personal data| OS settings (including the OS version and country/region); device hardware information (device model, screen size, and screen resolution); network information (network connection status and access network information); device status (login time/duration)|
</th> | Public| Public data has no adverse impact on individuals or organizations.| Non-personal data| Publicly released product introduction, public meeting information, and external open-source code|
<th class="cellrowborder" valign="top" width="48.8%" id="mcps1.1.5.1.4"><p id="p174482040112912"><a name="p174482040112912"></a><a name="p174482040112912"></a><strong id="b192611421412"><a name="b192611421412"></a><a name="b192611421412"></a>Typical Example</strong></p>
</th> > **NOTE**
</tr> >
</thead> > For details about the definitions of privacy protection and data classification, see GDPR.
<tbody><tr id="row1844904062919"><td class="cellrowborder" valign="top" width="13.239999999999998%" headers="mcps1.1.5.1.1 "><p id="p1444934002910"><a name="p1444934002910"></a><a name="p1444934002910"></a>Very high</p>
</td>
<td class="cellrowborder" valign="top" width="26.05%" headers="mcps1.1.5.1.2 "><p id="p1013011148467"><a name="p1013011148467"></a><a name="p1013011148467"></a>Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a catastrophic negative impact on that individual or group of individuals.</p>
</td>
<td class="cellrowborder" valign="top" width="11.91%" headers="mcps1.1.5.1.3 "><p id="p1992019442526"><a name="p1992019442526"></a><a name="p1992019442526"></a>Sensitive personal data</p>
</td>
<td class="cellrowborder" valign="top" width="48.8%" headers="mcps1.1.5.1.4 "><p id="p544974014295"><a name="p544974014295"></a><a name="p544974014295"></a>DNA, race, religious belief, and sexual orientation; biometric information; original communication content; bank account password and magnetic track data</p>
</td>
</tr>
<tr id="row8449164062911"><td class="cellrowborder" valign="top" width="13.239999999999998%" headers="mcps1.1.5.1.1 "><p id="p24491040192916"><a name="p24491040192916"></a><a name="p24491040192916"></a>High</p>
</td>
<td class="cellrowborder" valign="top" width="26.05%" headers="mcps1.1.5.1.2 "><p id="p101301214144615"><a name="p101301214144615"></a><a name="p101301214144615"></a>Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a severe negative impact on that individual or group of individuals.</p>
</td>
<td class="cellrowborder" valign="top" width="11.91%" headers="mcps1.1.5.1.3 "><p id="p1592084417525"><a name="p1592084417525"></a><a name="p1592084417525"></a>Sensitive personal data</p>
</td>
<td class="cellrowborder" valign="top" width="48.8%" headers="mcps1.1.5.1.4 "><p id="p74501400297"><a name="p74501400297"></a><a name="p74501400297"></a>Social identity (such as ID card and passport number); web browsing history; tracks; content (such as images, audio, and video) uploaded to the cloud</p>
</td>
</tr>
<tr id="row1745074020293"><td class="cellrowborder" valign="top" width="13.239999999999998%" headers="mcps1.1.5.1.1 "><p id="p1145074072915"><a name="p1145074072915"></a><a name="p1145074072915"></a>Moderate</p>
</td>
<td class="cellrowborder" valign="top" width="26.05%" headers="mcps1.1.5.1.2 "><p id="p31311514124618"><a name="p31311514124618"></a><a name="p31311514124618"></a>Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a significant negative impact on that individual or group of individuals.</p>
</td>
<td class="cellrowborder" valign="top" width="11.91%" headers="mcps1.1.5.1.3 "><p id="p1092116445529"><a name="p1092116445529"></a><a name="p1092116445529"></a>General personal data</p>
</td>
<td class="cellrowborder" valign="top" width="48.8%" headers="mcps1.1.5.1.4 "><p id="p945144022910"><a name="p945144022910"></a><a name="p945144022910"></a>Device ID (such as IMEI, SN, and OAID) and user ID; basic personal information (name and address); mobile number and email address</p>
</td>
</tr>
<tr id="row144512407291"><td class="cellrowborder" valign="top" width="13.239999999999998%" headers="mcps1.1.5.1.1 "><p id="p145110408294"><a name="p145110408294"></a><a name="p145110408294"></a>Low</p>
</td>
<td class="cellrowborder" valign="top" width="26.05%" headers="mcps1.1.5.1.2 "><p id="p61311514154618"><a name="p61311514154618"></a><a name="p61311514154618"></a>Once data is identified or associated with an individual or group of individuals, its disclosure or improper use may have a limited negative impact on that individual or group of individuals.</p>
</td>
<td class="cellrowborder" valign="top" width="11.91%" headers="mcps1.1.5.1.3 "><p id="p29212442526"><a name="p29212442526"></a><a name="p29212442526"></a>General personal data</p>
</td>
<td class="cellrowborder" valign="top" width="48.8%" headers="mcps1.1.5.1.4 "><p id="p945217401298"><a name="p945217401298"></a><a name="p945217401298"></a>OS settings (including the OS version and country/region); device hardware information (device model, screen size, and screen resolution); network information (network connection status and access network information); device status (login time/duration)</p>
</td>
</tr>
<tr id="row135851553268"><td class="cellrowborder" valign="top" width="13.239999999999998%" headers="mcps1.1.5.1.1 "><p id="p55864518261"><a name="p55864518261"></a><a name="p55864518261"></a>Public</p>
</td>
<td class="cellrowborder" valign="top" width="26.05%" headers="mcps1.1.5.1.2 "><p id="p135861254267"><a name="p135861254267"></a><a name="p135861254267"></a>Public data has no adverse impact on individuals or organizations.</p>
</td>
<td class="cellrowborder" valign="top" width="11.91%" headers="mcps1.1.5.1.3 "><p id="p1921144115218"><a name="p1921144115218"></a><a name="p1921144115218"></a>Non-personal data</p>
</td>
<td class="cellrowborder" valign="top" width="48.8%" headers="mcps1.1.5.1.4 "><p id="p1058612512613"><a name="p1058612512613"></a><a name="p1058612512613"></a>Publicly released product introduction, public meeting information, and external open-source code</p>
</td>
</tr>
</tbody>
</table>
Note: For details about the definitions of privacy protection and data classification, see GDPR.
## General Privacy Design Rules ## General Privacy Design Rules
To help you better complete privacy design for OpenHarmony products, we sort out general privacy design requirements. Observe the following general privacy design requirements when designing your OpenHarmony products:
**Openness and Transparency in Data Collection and Use** **Openness and Transparency in Data Collection and Use**
When collecting personal data, clearly and explicitly notify users of the data to collect and how their personal data will be used. When collecting personal data, clearly and explicitly notify users of the data to collect and how their personal data will be used.
- Develop specific privacy processing policies for personal data at different levels. - Develop specific privacy processing policies for personal data at different levels.
- Explicit consent shall be obtained from the data subject before your product attempts to collect sensitive personal data.
- Generally, the collection of personal data requires the consent of the data subject or other legal authorizations.
- If non-personal data is to be collected in association with personal data at the moderate, high, or very high level, the data subject's consent or other legal authorization is required, and the consent or authorization shall be presented in the privacy statement.
- Develop and follow appropriate privacy policies. Comply with all applicable laws, policies, and regulations when collecting, using, retaining, and sharing users' personal data with any third parties. For example, prior to data collection, fully inform users of the types, purposes, processing methods, and retention periods of personal data to meet the requirements of data subjects' rights. - Explicit consent shall be obtained from the data subject before your product attempts to collect sensitive personal data.
- Generally, the collection of personal data requires the consent of the data subject or other legal authorizations.
- If non-personal data is to be collected in association with personal data at the moderate, high, or very high level, the data subject's consent or other legal authorization is required, and the consent or authorization shall be presented in the privacy statement.
- Develop and follow appropriate privacy policies. Comply with all applicable laws, policies, and regulations when collecting, using, retaining, and sharing users' personal data with any third parties. For example, prior to data collection, fully inform users of the types, purposes, processing methods, and retention periods of personal data to meet the requirements of data subjects' rights.
Guided by the preceding principles, we have designed some examples for your reference. The figures below are examples of a privacy notice and a privacy statement, respectively. Guided by the preceding principles, we have designed some examples for your reference. The figures below are examples of a privacy notice and a privacy statement, respectively.
**Figure 1** Examples of a privacy notice and a privacy statement **Figure 1** Example of a privacy notice
![](figures/privacy-notice.png)![](figures/privacy-statement.png) ![](figures/privacy-notice.png)
- Personal data shall be collected for specified, explicit, and legitimate purposes and not further processed in a manner that is incompatible with those purposes. If the purposes are changed or a user withdraws their consent, you shall obtain user consent again before using the data. The figures below are examples of a privacy statement update and content withdrawal, respectively.
**Figure 2** Example dialog showing a privacy statement update<a name="fig3591610523"></a> **Figure 2** Example of a privacy statement
![](figures/privacy-statement.png)
- Personal data shall be collected for specified, explicit, and legitimate purposes and not further processed in a manner that is incompatible with those purposes. If the purposes are changed or a user withdraws their consent, you shall obtain user consent again before using the data. The figures below are examples of a privacy statement update and content withdrawal, respectively.
**Figure 3** Example dialog showing a privacy notice or statement update
![](figures/privacy-statement-update.png) ![](figures/privacy-statement-update.png)
**Figure 3** Example dialog showing consent withdrawal<a name="fig12802152515583"></a> **Figure 4** Example dialog showing consent withdrawal
![](figures/consent-withdrawal-1.png)![](figures/consent-withdrawal-2.png) ![](figures/consent-withdrawal-1.png)
- You shall provide an entry for users to view the privacy statement. For example, you can provide an entry on the **About** page of your application to view the privacy statement, as shown in the following figure. **Figure 5** Example dialog showing consent withdrawal
**Figure 4** Example of About page providing an entry to the privacy statement<a name="fig11392538162011"></a> ![](figures/consent-withdrawal-2.png)
- You shall provide an entry for users to view the privacy statement. For example, you can provide an entry on the **About** page of your application to view the privacy statement, as shown in the following figure.
![](figures/privacy-statement-entry.png) **Figure 6** Example of About page providing an entry to the privacy statement
![](figures/privacy-statement-entry.png)
**Minimization in Data Collection and Use** **Minimization in Data Collection and Use**
Collect personal data only when they are adequate, relevant, and limited to what is necessary in relation to the purposes for which they are processed. Apply anonymization or pseudonymization to personal data if possible to reduce the risks to the data subjects concerned. Data shall only be collected and processed for a specified purpose, and no further unnecessary operations shall be conducted on them. Collect personal data only when they are adequate, relevant, and limited to what is necessary in relation to the purposes for which they are processed. Apply anonymization or pseudonymization to personal data if possible to reduce the risks to the data subjects concerned. Data shall only be collected and processed for a specified purpose, and no further unnecessary operations shall be conducted on them.
- When applying for sensitive permissions, adhere to permission minimization and apply for only the permissions required for obtaining necessary information or resources. For example, if your application can implement its functions without access to the camera, then it shall not request the user for the camera permission. - When applying for sensitive permissions, adhere to permission minimization and apply for only the permissions required for obtaining necessary information or resources. For example, if your application can implement its functions without access to the camera, then it shall not request the user for the camera permission.
- Comply with data collection minimization, and do not collect data irrelevant to services provided by the product. For example, a product that provides location services shall not collect users' web browsing history.
- The functions that use personal data shall be able to benefit users. The collected data shall not be used for functions irrelevant to users' normal use. No data shall be collected for any functions irrelevant to user operations. For example, sensitive personal data, such as biometric features and health data, shall not be used for non-core service functions like service improvement, advertising, and marketing.
- Printing sensitive personal data in logs is prohibited. If common personal data needs to be printed in logs, make sure the data is anonymized or pseudonymized.
Preferentially use identifiers that are resettable. For example, use the NetworkID and DVID as the device identifier in the distributed scenario; use the [OAID](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/oaid-0000001050783198) in the advertising scenario; use the [ODID](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/odid-0000001051063255) and [AAID](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/aaid-0000001051142988) in the application-based analysis scenario; and use the UUID in other scenarios where a unique identifier is required. Use permanent identifiers such as the sequence number and MAC address only when resettable identifiers cannot meet your service requirements. - Comply with data collection minimization, and do not collect data irrelevant to services provided by the product. For example, a product that provides location services shall not collect users' web browsing history.
- The functions that use personal data shall be able to benefit users. The collected data shall not be used for functions irrelevant to users' normal use. No data shall be collected for any function irrelevant to user operations. For example, sensitive personal data, such as biometric features and health data, shall not be used for non-core service functions like service improvement, advertising, and marketing.
- Printing sensitive personal data in logs is prohibited. If common personal data needs to be printed in logs, make sure the data is anonymized or pseudonymized.
Preferentially use identifiers that are resettable. For example, use the NetworkID and DVID as the device identifier in the distributed scenario; use the OAID in the advertising scenario; use the ODID and AAID in the application-based analysis scenario; and use the UUID in other scenarios where a unique identifier is required. Use permanent identifiers such as the sequence number and MAC address only when resettable identifiers cannot meet your service requirements.
**Data Processing Selection and Control** **Data Processing Selection and Control**
You shall obtain consent from users and comply with applicable laws and regulations for processing personal data and give users full control over their data. You shall obtain consent from users and comply with applicable laws and regulations for processing personal data and give users full control over their data.
- When applying for a certain sensitive permission, your product shall display a pop-up dialog to notify the user of the requested permission and the purpose of using the permission. The user shall be able to choose whether to grant the permission and how they would like to grant the permission. This ensures that permission granting and use are transparent, perceivable, and controllable. The following figure is an example dialog for requesting a sensitive permission. - When applying for a certain sensitive permission, your product shall display a pop-up dialog to notify the user of the requested permission and the purpose of using the permission. The user shall be able to choose whether to grant the permission and how they would like to grant the permission. This ensures that permission granting and use are transparent, perceivable, and controllable. The following figure is an example dialog for requesting a sensitive permission.
**Figure 5** Example dialog for requesting a sensitive permission<a name="fig20776134521514"></a> **Figure 7** Example dialog for requesting a sensitive permission
![](figures/sensitive-permission-request.png) ![](figures/sensitive-permission-request.png)
- Users shall have the right to modify or withdraw the permissions granted to your product. When a user does not agree to a permission or data collection, the user shall be allowed to use the functions irrelevant to the permission or data collection. For example, the user can refuse to grant the camera permission to social or communication apps on Smart TVs, when using product functions irrelevant to the camera, such as voice calls. - Users shall have the right to modify or withdraw the permissions granted to your product. When a user does not agree to a permission or data collection, the user shall be allowed to use the functions irrelevant to the permission or data collection. For example, the user can refuse to grant the camera permission to social or communication apps on Smart TVs, when using product functions irrelevant to the camera, such as voice calls.
- In scenarios where personal data is recorded, users shall be provided with the functions of adding, deleting, modifying, and viewing personal data.
- Your products shall provide a mechanism or method for securely deleting personal data when hardware is recycled or returned to the factory. - In scenarios where personal data is recorded, users shall be provided with the functions of adding, deleting, modifying, and viewing personal data.
- The download or upgrade of user system software or application software may involve the modification of users' private space. Users shall have the right to know and control such behavior. They shall be informed of such behavior and be given the option to agree or disagree with such behavior.
- Your products shall provide a mechanism or method for securely deleting personal data when hardware is recycled or returned to the factory.
- The download or upgrade of user system software or application software may involve the modification of users' private space. Users shall have the right to know and control such behavior. They shall be informed of such behavior and be given the option to agree or disagree with such behavior.
**Data Security** **Data Security**
Data processing security shall be ensured in technical terms, which include encrypted data storage and secure data transfer. Security mechanisms or measures shall be enabled by default for a system. Data processing security shall be ensured in technical terms, which include encrypted storage and secure transmission. Security mechanisms or measures shall be enabled by default for a system.
- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication (such as user name and password) allows only authenticated users to access data in multi-user scenarios. Access control, such as [permission control](../security/security-guidelines-overall.md) can be used to restrict certain applications.
- Secure storage of personal data on distributed devices must meet Huawei Universal KeyStore (HUKS) requirements, including secure storage of keys and data.
- A protection mechanism shall be available for personal data access, including identity authentication and access control. Identity authentication \(such as username and password\) allows only authenticated users to access data in multi-user scenarios. Access control \(for example, [permission control](../security/security-guidelines-overall.md)\) can be applied to restrict access to applications. - The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Device Interconnection Security](../security/security-guidelines-overall.md#device-interconnection-security).
- Secure storage of personal data on distributed devices must meet Huawei Universal Keystore \(HUKS\) requirements, including secure storage of keys and data.
- The transfer of personal data between distributed devices must meet the trust binding relationship between devices and security requirements of data transmission channels. For details, see [Device Interconnection Security](../security/security-guidelines-overall.md#device-interconnection-security). - Authentication data (such as passwords and fingerprints) shall be encrypted before being stored.
- Authentication data \(such as passwords and fingerprints\) shall be encrypted before being stored.
**Localization** **Localization**
User data shall be preferentially processed on the local device. Data that cannot be processed on the local device shall be preferentially processed on Device+ \(super device in the distributed scenario\). If any data cannot be processed on Device+, the data shall be anonymized before being transferred out of Device+ for processing. User data shall be preferentially processed on the local device. Data that cannot be processed on the local device shall be preferentially processed on a device of the Super Device. If any data cannot be processed on the Super Device, the data shall be anonymized before being transferred out of Super Device for processing.
**Minors' Data Protection** **Minors' Data Protection**
If your product is designed for minors or you can identify, based on the collected user age data, that the end user is a minor, you shall particularly analyze issues related to minors' personal data protection based on relevant national laws in the target market. Your product shall obtain explicit consent from the holders of parental responsibility over minors. If your product is designed for minors or you can identify, based on the collected user age data, that the end user is a minor, you shall particularly analyze issues related to minors' personal data protection based on relevant local laws in the target market. Your product shall obtain explicit consent from the holders of parental responsibility over minors.
## **Privacy Protection Requirements for Special Categories** ## **Privacy Protection Requirements for Special Categories**
In addition to these general privacy requirements, consumer hardware products have the following requirements for special categories. You shall comply with these requirements during product design. In addition to these general privacy requirements, consumer hardware products have the following requirements for special categories. You shall comply with these requirements during product design.
**Table 2** Privacy protection requirements for special categories **Table 2** Privacy protection requirements for special categories
<a name="table17143732123612"></a>
<table><thead align="left"><tr id="row1943617174010"><th class="cellrowborder" valign="top" width="23%" id="mcps1.1.3.1.1"><p id="p1194461794016"><a name="p1194461794016"></a><a name="p1194461794016"></a>Product Category</p>
</th>
<th class="cellrowborder" valign="top" width="77%" id="mcps1.1.3.1.2"><p id="p1894481764012"><a name="p1894481764012"></a><a name="p1894481764012"></a>Privacy Protection Requirements</p>
</th>
</tr>
</thead>
<tbody><tr id="row918893210367"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p718853216369"><a name="p718853216369"></a><a name="p718853216369"></a><strong id="b1150122319282"><a name="b1150122319282"></a><a name="b1150122319282"></a>Smart home</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p81884329366"><a name="p81884329366"></a><a name="p81884329366"></a>Biometric information (such as fingerprints, voiceprints, facial recognition, and irises) and user passwords involved in security products are sensitive personal data. They shall be processed using technical measures (for example, extracting the digest of biometric information) before being encrypted and stored in the products.</p>
</td>
</tr>
<tr id="row19189103223618"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p201891632163610"><a name="p201891632163610"></a><a name="p201891632163610"></a><strong id="b16184636153611"><a name="b16184636153611"></a><a name="b16184636153611"></a>Smart home</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p18189173243610"><a name="p18189173243610"></a><a name="p18189173243610"></a>For security products that involve audio, video, and images, their manufacturers, functioning as the data controller, shall provide an independent privacy notification and a brand log on their application UI. Transfer and storage of audio and video data shall be encrypted. Access to audio and video data of security products is permitted only after being authorized by the data subject.</p>
</td>
</tr>
<tr id="row121891432163614"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p121892320363"><a name="p121892320363"></a><a name="p121892320363"></a><strong id="b670294616282"><a name="b670294616282"></a><a name="b670294616282"></a>Smart home/Entertainment</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p51891432183615"><a name="p51891432183615"></a><a name="p51891432183615"></a>Cameras on products should be able to be physically disabled. For example, cameras can be hidden, shuttered, or re-oriented so that consumers can perceive that the cameras are disabled.</p>
</td>
</tr>
<tr id="row1218903210364"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p5189632163616"><a name="p5189632163616"></a><a name="p5189632163616"></a><strong id="b1067022117448"><a name="b1067022117448"></a><a name="b1067022117448"></a>Smart home/Entertainment</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p111891632153617"><a name="p111891632153617"></a><a name="p111891632153617"></a>Products with a microphone should provide an explicit display of the recording status. For example, the products can provide a status indicator that blinks when recording is started and turns off when recording is stopped.</p>
</td>
</tr>
<tr id="row31891932173619"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p11891132163618"><a name="p11891132163618"></a><a name="p11891132163618"></a><strong id="b12223353122815"><a name="b12223353122815"></a><a name="b12223353122815"></a>Mobile office</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p10189632183612"><a name="p10189632183612"></a><a name="p10189632183612"></a>In scenarios such as cross-device display and transfer of user data, your products shall obtain explicit consent from users and give them full control over their personal data.</p>
</td>
</tr>
<tr id="row1189232103617"><td class="cellrowborder" valign="top" width="23%" headers="mcps1.1.3.1.1 "><p id="p16189632183619"><a name="p16189632183619"></a><a name="p16189632183619"></a><strong id="b1225245962810"><a name="b1225245962810"></a><a name="b1225245962810"></a>In-vehicle infotainment (IVI)</strong></p>
</td>
<td class="cellrowborder" valign="top" width="77%" headers="mcps1.1.3.1.2 "><p id="p1018983263615"><a name="p1018983263615"></a><a name="p1018983263615"></a>1. Privacy notice and permission settings</p>
<p id="p1618914325366"><a name="p1618914325366"></a><a name="p1618914325366"></a>Do not let users read privacy policies and permission settings in the driving state.</p>
<p id="p1818973263617"><a name="p1818973263617"></a><a name="p1818973263617"></a>IVI applications shall consider the safety of vehicle use. The applications shall not require complex permission settings or reading of privacy policies when users are driving. For example, HiCar is usable only after users have set basic permissions and read privacy policies on their mobile phone.</p>
<p id="p518973210368"><a name="p518973210368"></a><a name="p518973210368"></a>The privacy statement shall be notified after the user identity is confirmed.</p>
<p id="p6189132113615"><a name="p6189132113615"></a><a name="p6189132113615"></a>Vehicle data involves vehicle owners, drivers, and passengers. The data subject shall be notified of the privacy statement. The recommended practice is to make a privacy statement after confirming the user identity. For an application that requires login, the privacy statement should be displayed after, instead of before, a user is logged in.</p>
<p id="p1818914329368"><a name="p1818914329368"></a><a name="p1818914329368"></a>2. Personal data protection for sharing applications</p>
<p id="p191892032103620"><a name="p191892032103620"></a><a name="p191892032103620"></a>Shared applications shall exit after the IVI is restarted, and the personal data of the current user shall be cleared or encrypted. The applications shall also provide the function to permanently delete historical data.</p>
<p id="p4189153213611"><a name="p4189153213611"></a><a name="p4189153213611"></a>3. Notifications</p>
<p id="p2189432103613"><a name="p2189432103613"></a><a name="p2189432103613"></a>As the IVI is used in an open environment, applications shall not directly display the message content on the IVI. Instead, the applications shall only notify users that there is an incoming message.</p>
</td>
</tr>
</tbody>
</table>
| **Product Category**| Privacy Protection Requirements|
| -------- | -------- |
| **Smart home**| Biometric information (such as fingerprints, voiceprints, facial recognition, and irises) and user passwords involved in security products are sensitive personal data. They shall be processed using technical measures (for example, extracting the digest of biometric information) before being encrypted and stored in the products.|
| **Smart home**| For security products that involve audio, video, and images, their manufacturers, functioning as the data controller, shall provide an independent privacy notification and a brand log on their application UI. Transfer and storage of audio and video data shall be encrypted. Access to audio and video data of security products is permitted only after being authorized by the data subject.|
| **Smart home/Entertainment**| Cameras on products should be able to be physically disabled. For example, cameras can be hidden, shuttered, or re-oriented so that consumers can perceive that the cameras are disabled.|
| **Smart home/Entertainment**| Products with a microphone should provide an explicit display of the recording status. For example, the products can provide a status indicator that blinks when recording is started and turns off when recording is stopped.|
| **Mobile office**| In scenarios such as cross-device display and transfer of user data, your products shall obtain explicit consent from users and give them full control over their personal data.|
| **Head unit**| 1. Privacy notice and permission settings<br>Do not let users read privacy policies and permission settings in the driving state.<br>IVI applications shall consider the safety of vehicle use. The applications shall not require complex permission settings or reading of privacy policies when users are driving. For example, HiCar is usable only after users have set basic permissions and read privacy policies on their mobile phone.<br>The privacy statement shall be notified after the user identity is confirmed.<br>Vehicle data involves vehicle owners, drivers, and passengers. The data subject shall be notified of the privacy statement. The recommended practice is to make a privacy statement after confirming the user identity. For an application that requires login, the privacy statement should be displayed after, instead of before, a user is logged in.<br>2. Personal data protection for sharing applications<br>Shared applications shall exit after the IVI is restarted, and the personal data of the current user shall be cleared or encrypted. The applications shall also provide the function to permanently delete historical data.<br>3. Notifications<br>As the IVI is used in an open environment, applications shall not directly display the message content on the IVI. Instead, the applications shall only notify users that there is an incoming message.|
# Telephony Subsystem Changelog
## cl.telephony.radio.1 isNrSupported API Change
NR is a proper noun and must be capitalized.
You need to adapt your application.
**Change Impact**
The JS API needs to be adapted for applications developed based on earlier versions. Otherwise, relevant functions will be affected.
**Key API/Component Changes**
- Involved APIs:
isNrSupported(): boolean;
isNrSupported(slotId: number): boolean;
- Before change:
```js
function isNrSupported(): boolean;
function isNrSupported(slotId: number): boolean;
```
- After change:
```js
function isNRSupported(): boolean;
function isNRSupported(slotId: number): boolean;
```
**Adaptation Guide**
Use the new API. The sample code is as follows:
```js
let result = radio.isNrSupported();
console.log("Result: "+ result);
```
```js
let slotId = 0;
let result = radio.isNRSupported(slotId);
console.log("Result: "+ result);
```
## cl.telephony.call.2 dial API Change
Changed the `dial` API to the `dialCall` API in the call module of the telephony subsystem since API version 9.
You need to adapt your application.
**Change Impact**
The `dial` API is deprecated and cannot be used anymore. Use the `dialCall` API instead. Otherwise, relevant functions will be affected.
**Key API/Component Changes**
- Involved APIs:
dial(phoneNumber: string, callback: AsyncCallback<boolean>): void;
dial(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean>): void;
dial(phoneNumber: string, options?: DialOptions): Promise<boolean>;
- Before change:
```js
function dial(phoneNumber: string, callback: AsyncCallback<boolean>): void;
function dial(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean>): void;
function dial(phoneNumber: string, options?: DialOptions): Promise<boolean>;
```
- After change:
```js
function dialCall(phoneNumber: string, callback: AsyncCallback<void>): void;
function dialCall(phoneNumber: string, options: DialCallOptions, callback: AsyncCallback<void>): void;
function dialCall(phoneNumber: string, options?: DialCallOptions): Promise<void>;
```
**Adaptation Guide**
The `dial` API is deprecated and cannot be used anymore. Use the `dialCall` API instead.
Use the new API. The sample code is as follows:
```js
call.dialCall("138xxxxxxxx", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
call.dialCall("138xxxxxxxx", {
accountId: 0,
videoState: 0,
dialScene: 0,
dialType: 0,
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
```js
try {
call.dialCall('138xxxxxxxx');
console.log(`dialCall success, promise: data->${JSON.stringify(data)}`);
} catch (error) {
console.log(`dialCall fail, promise: err->${JSON.stringify(error)}`);
}
```
# Globalization Subsystem Changelog
## cl.resourceManager.1 Addition of getStringSync and getStringByNameSync APIs
Added the **getStringSync** and **getStringByNameSync** APIs and error codes to obtain and format strings.
| Bundle Name | API |
| --------------- | ---------------------------------------------------- |
| ohos.resourceManager.d.ts | getStringSync(resId: number, ...args: Array<string \| number>): string; |
| ohos.resourceManager.d.ts | getStringSync(resource: Resource, ...args: Array<string \| number>): string; |
| ohos.resourceManager.d.ts | getStringByNameSync(resName: string, ...args: Array<string \| number>): string; |
**Change Impact**
In versions earlier than 4.0.6.2, only the values of string resources can be directly obtained. In 4.0.6.2 or later, the values of string resources can be formatted based on the input arguments for enhanced query.
The following error codes are added:
9001007 If the resource obtained by resId formatting error.
9001008 If the resource obtained by resName formatting error.
**Sample Code**
The following uses **getStringSync** as an example. Before the change, only example 1 is supported. After the change, both example 1 and example 2 are supported.
```
Example 1:
try {
this.context.resourceManager.getStringSync($r('app.string.test').id);
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`)
}
Example 2:
try {
this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 787, 98.78);
} catch (error) {
console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`)
}
```
**Adaptation Guide**
For details, see the API reference.
[API Reference](../../../application-dev/reference/apis/js-apis-resource-manager.md)
[Error Codes](../../../application-dev/reference/errorcodes/errorcode-resource-manager.md)
...@@ -64,7 +64,6 @@ ...@@ -64,7 +64,6 @@
- [跨端迁移(仅对系统应用开放)](hop-cross-device-migration.md) - [跨端迁移(仅对系统应用开放)](hop-cross-device-migration.md)
- [多端协同(仅对系统应用开放)](hop-multi-device-collaboration.md) - [多端协同(仅对系统应用开放)](hop-multi-device-collaboration.md)
- [订阅系统环境变量的变化](subscribe-system-environment-variable-changes.md) - [订阅系统环境变量的变化](subscribe-system-environment-variable-changes.md)
- [原子化服务支持分享](atomic-services-support-sharing.md)
- 了解进程模型 - 了解进程模型
- [进程模型概述](process-model-stage.md) - [进程模型概述](process-model-stage.md)
- 公共事件 - 公共事件
......
# 设置原子化服务支持分享
## 原子化服务分享
1. UIAbility组件提供了[UIAbility.onShare()](../reference/apis/js-apis-app-ability-uiAbility.md#onshare)生命周期方法,应用可通过此方法设置要分享的数据。其中,ohos.extra.param.key.contentTitle表示分享框中对分享内容title的描述,ohos.extra.param.key.shareAbstract表示分享框中对携带内容的摘要描述,ohos.extra.param.key.shareUrl表示服务的在线地址。以上三项分享数据均是开发者填充,且为Object对象,对象的key分别为title,abstract,url。
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility {
onShare(wantParams) {
console.log('onShare');
wantParams['ohos.extra.param.key.contentTitle'] = 'shareFeatureAbility';
wantParams['ohos.extra.param.key.shareAbstract'] = 'huawei employee';
wantParams['ohos.extra.param.key.shareUrl'] = 'w3.huawei.com';
}
}
```
2. 系统弹框调用[abilityManager.acquireShareData()](../reference/apis/js-apis-app-ability-abilityManager.md#acquiresharedata)接口发起原子化服务共享,根据missionId找到对应的UIAbility,调用其OnShare生命周期,收到共享数据。
```ts
import abilityManager from '@ohos.app.ability.abilityManager';
try {
abilityManager.acquireShareData(1, (err, wantParam) => {
if (err) {
console.error(`acquireShareData fail, err: ${JSON.stringify(err)}`);
} else {
console.log(`acquireShareData success, data: ${JSON.stringify(wantParam)}`);
}
});
} catch (paramError) {
console.error(`error.code: ${JSON.stringify(paramError.code)}, error.message: ${JSON.stringify(paramError.message)}`);
}
```
...@@ -41,8 +41,8 @@ ...@@ -41,8 +41,8 @@
- [资源分类与访问](resource-categories-and-access.md) - [资源分类与访问](resource-categories-and-access.md)
- 学习ArkTS语言 - 学习ArkTS语言
- [初识ArkTS语言](arkts-get-started.md) - [初识ArkTS语言](arkts-get-started.md)
- [ArkTS语言介绍](arkts/introduction-to-arkts.md) - [ArkTS语言介绍](introduction-to-arkts.md)
- [从TypeScript到ArkTS的迁移指导](arkts/typescript-to-arkts-migration-guide.md) - [从TypeScript到ArkTS的迁移指导](typescript-to-arkts-migration-guide.md)
- UI范式 - UI范式
- 基本语法 - 基本语法
- [基本语法概述](arkts-basic-syntax-overview.md) - [基本语法概述](arkts-basic-syntax-overview.md)
...@@ -74,8 +74,11 @@ ...@@ -74,8 +74,11 @@
- [其他状态管理概述](arkts-other-state-mgmt-functions-overview.md) - [其他状态管理概述](arkts-other-state-mgmt-functions-overview.md)
- [\@Watch装饰器:状态变量更改通知](arkts-watch.md) - [\@Watch装饰器:状态变量更改通知](arkts-watch.md)
- [$$语法:内置组件双向同步](arkts-two-way-sync.md) - [$$语法:内置组件双向同步](arkts-two-way-sync.md)
- [MVVM模式](arkts-mvvm.md)
- [状态管理优秀实践](arkts-state-management-best-practices.md)
- 渲染控制 - 渲染控制
- [渲染控制概述](arkts-rendering-control-overview.md) - [渲染控制概述](arkts-rendering-control-overview.md)
- [if/else:条件渲染](arkts-rendering-control-ifelse.md) - [if/else:条件渲染](arkts-rendering-control-ifelse.md)
- [ForEach:循环渲染](arkts-rendering-control-foreach.md) - [ForEach:循环渲染](arkts-rendering-control-foreach.md)
- [LazyForEach:数据懒加载](arkts-rendering-control-lazyforeach.md) - [LazyForEach:数据懒加载](arkts-rendering-control-lazyforeach.md)
- [渲染控制优秀实践](arkts-rendering-control-best-practices.md)
# MVVM模式
应用通过状态去渲染更新UI是程序设计中相对复杂,但又十分重要的,往往决定了应用程序的性能。程序的状态数据通常包含了数组、对象,或者是嵌套对象组合而成。在这些情况下,ArkUI采取MVVM = Model + View + ViewModel模式,其中状态管理模块起到的就是ViewModel的作用,将数据与视图绑定在一起,更新数据的时候直接更新视图。
- Model层:存储数据和相关逻辑的模型。它表示组件或其他相关业务逻辑之间传输的数据。Model是对原始数据的进一步处理。
- View层:在ArkUI中通常是\@Components修饰组件渲染的UI。
- ViewModel层:在ArkUI中,ViewModel是存储在自定义组件的状态变量、LocalStorage和AppStorage中的数据。
- 自定义组件通过执行其build()方法或者\@Builder装饰的方法来渲染UI,即ViewModel可以渲染View。
- View可以通过相应event handler来改变ViewModel,即事件驱动ViewModel的改变,另外ViewModel提供了\@Watch回调方法用于监听状态数据的改变。
- 在ViewModel被改变时,需要同步回Model层,这样才能保证ViewModel和Model的一致性,即应用自身数据的一致性。
- ViewModel结构设计应始终为了适配自定义组件的构建和更新,这也是将Model和ViewModel分开的原因。
目前很多关于UI构造和更新的问题,都是由于ViewModel的设计并没有很好的支持自定义组件的渲染,或者试图去让自定义组件强行适配Model层,而中间没有用ViewModel来进行分离。例如,一个应用程序直接将SQL数据库中的数据读入内存,这种数据模型不能很好的直接适配自定义组件的渲染,所以在应用程序开发中需要适配ViewModel层。
![zh-cn_image_0000001653986573](figures/zh-cn_image_0000001653986573.png)
根据上面涉及SQL数据库的示例,应用程序应设计为:
- Model:针对数据库高效操作的数据模型。
- ViewModel:针对ArkUI状态管理功能进行高效的UI更新的视图模型。
- 部署 converters/adapters: converters/adapters作用于Model和ViewModel的相互转换。
- converters/adapters可以转换最初从数据库读取的Model,来创建并初始化ViewModel。
- 在应用的使用场景中,UI会通过event handler改变ViewModel,此时converters/adapters需要将ViewModel的更新数据同步回Model。
虽然与强制将UI拟合到SQL数据库模式(MV模式)相比,MVVM的设计比较复杂,但应用程序开发人员可以通过ViewModel层的隔离,来简化UI的设计和实现,以此来收获更好的UI性能。
## ViewModel的数据源
ViewModel通常包含多个顶层数据源。\@State和\@Provide装饰的变量以及LocalStorage和AppStorage都是顶层数据源,其余装饰器都是与数据源做同步的数据。装饰器的选择取决于状态需要在自定义组件之间的共享范围。共享范围从小到大的排序是:
- \@State:组件级别的共享,通过命名参数机制传递,例如:CompA: ({ aProp: this.aProp }),表示传递层级(共享范围)是父子之间的传递。
- \@Provide:组件级别的共享,可以通过key和\@Consume绑定,因此不用参数传递,实现多层级的数据共享,共享范围大于\@State。
- LocalStorage:页面级别的共享,可以通过\@Entry在当前组件树上共享LocalStorage实例。
- AppStorage:应用全局的UI状态存储,和应用进程绑定,在整个应用内的状态数据的共享。
### \@State装饰的变量与一个或多个子组件共享状态数据
\@State可以初始化多种状态变量,\@Prop、\@Link和\@ObjectLink可以和其建立单向或双向同步,详情见[@State使用规范](arkts-state.md)
1. 使用Parent根节点中\@State装饰的testNum作为ViewModel数据项。将testNum传递给其子组件LinkChild和Sibling。
```ts
// xxx.ets
@Entry
@Component
struct Parent {
@State @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ testNum: $testNum })
Sibling({ testNum: $testNum })
}
}
}
```
2. LinkChild和Sibling中用\@Link和父组件的数据源建立双向同步。其中LinkChild中创建了LinkLinkChild和PropLinkChild。
```ts
@Component
struct Sibling {
@Link @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@Link @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ testNumGrand: $testNum })
PropLinkChild({ testNumGrand: this.testNum })
}
.height(200).width(200)
}
}
```
3. LinkLinkChild和PropLinkChild声明如下,PropLinkChild中的\@Prop和其父组件建立单向同步关系。
```ts
@Component
struct LinkLinkChild {
@Link @Watch("testNumChange") testNumGrand: number;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`LinkLinkChild: ${this.testNumGrand}`)
}
}
@Component
struct PropLinkChild {
@Prop @Watch("testNumChange") testNumGrand: number;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
```
![zh-cn_image_0000001638250945](figures/zh-cn_image_0000001638250945.png)
当LinkChild中的\@Link testNum更改时。
1. 更改首先同步到其父组件Parent,然后更改从Parent同步到Siling。
2. LinkChild中的\@Link testNum更改也同步给子组件LinkLinkChild和PropLinkChild。
\@State装饰器与\@Provide、LocalStorage、AppStorage的区别:
- \@State如果想要将更改传递给孙子节点,需要先将更改传递给子组件,再从子节点传递给孙子节点。
- 共享只能通过构造函数的参数传递,即命名参数机制CompA: ({ aProp: this.aProp })。
完整的代码示例如下:
```ts
@Component
struct LinkLinkChild {
@Link @Watch("testNumChange") testNumGrand: number;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`LinkLinkChild: ${this.testNumGrand}`)
}
}
@Component
struct PropLinkChild {
@Prop @Watch("testNumChange") testNumGrand: number;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
@Component
struct Sibling {
@Link @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@Link @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ testNumGrand: $testNum })
PropLinkChild({ testNumGrand: this.testNum })
}
.height(200).width(200)
}
}
@Entry
@Component
struct Parent {
@State @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ testNum: $testNum })
Sibling({ testNum: $testNum })
}
}
}
```
### \@Provide装饰的变量与任何后代组件共享状态数据
\@Provide装饰的变量可以与任何后代组件共享状态数据,其后代组件使用\@Consume创建双向同步,详情见[@Provide和@Consume](arkts-provide-and-consume.md)
因此,\@Provide-\@Consume模式比使用\@State-\@Link-\@Link从父组件将更改传递到孙子组件更方便。\@Provide-\@Consume适合在单个页面UI组件树中共享状态数据。
使用\@Provide-\@Consume模式时,\@Consume和其祖先组件中的\@Provide通过绑定相同的key连接,而不是在组件的构造函数中通过参数来进行传递。
以下示例通过\@Provide-\@Consume模式,将更改从父组件传递到孙子组件。
```ts
@Component
struct LinkLinkChild {
@Consume @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNum value ${this.testNum}`);
}
build() {
Text(`LinkLinkChild: ${this.testNum}`)
}
}
@Component
struct PropLinkChild {
@Prop @Watch("testNumChange") testNumGrand: number;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
@Component
struct Sibling {
@Consume @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@Consume @Watch("testNumChange") testNum: number;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ /* empty */ })
PropLinkChild({ testNumGrand: this.testNum })
}
.height(200).width(200)
}
}
@Entry
@Component
struct Parent {
@Provide @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ /* empty */ })
Sibling({ /* empty */ })
}
}
}
```
### 给LocalStorage实例中对应的属性建立双向或单向同步
通过\@LocalStorageLink和\@LocalStorageProp,给LocalStorage实例中的属性建立双向或单向同步。可以将LocalStorage实例视为\@State变量的Map,使用详情参考LocalStorage。
LocalStorage对象可以在ArkUI应用程序的几个页面上共享。因此,使用\@LocalStorageLink、\@LocalStorageProp和LocalStorage可以在应用程序的多个页面上共享状态。
以下示例中:
1. 创建一个LocalStorage实例,并通过\@Entry(storage)将其注入根节点。
2. 在Parent组件中初始化\@LocalStorageLink("testNum")变量时,将在LocalStorage实例中创建testNum属性,并设置指定的初始值为1,即\@LocalStorageLink("testNum") testNum: number = 1。
3. 在其子组件中,都使用\@LocalStorageLink或\@LocalStorageProp绑定同一个属性名key来传递数据。
LocalStorage可以被认为是\@State变量的Map,属性名作为Map中的key。
\@LocalStorageLink和LocalStorage中对应的属性的同步行为,和\@State和\@Link一致,都为双向数据同步。
以下为组件的状态更新图:
![zh-cn_image_0000001588450934](figures/zh-cn_image_0000001588450934.png)
```ts
@Component
struct LinkLinkChild {
@LocalStorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNum value ${this.testNum}`);
}
build() {
Text(`LinkLinkChild: ${this.testNum}`)
}
}
@Component
struct PropLinkChild {
@LocalStorageProp("testNum") @Watch("testNumChange") testNumGrand: number = 1;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
@Component
struct Sibling {
@LocalStorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@LocalStorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ /* empty */ })
PropLinkChild({ /* empty */ })
}
.height(200).width(200)
}
}
// create LocalStorage object to hold the data
const storage = new LocalStorage();
@Entry(storage)
@Component
struct Parent {
@LocalStorageLink("testNum") @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ /* empty */ })
Sibling({ /* empty */ })
}
}
}
```
### 给AppStorage中对应的属性建立双向或单向同步
AppStorage是LocalStorage的单例对象,ArkUI在应用程序启动时创建该对象,在页面中使用\@StorageLink和\@StorageProp为多个页面之间共享数据,具体使用方法和LocalStorage类似。
也可以使用PersistentStorage将AppStorage中的特定属性持久化到本地磁盘的文件中,再次启动的时候\@StorageLink和\@StorageProp会恢复上次应用退出的数据。详情请参考[PersistentStorage文档](arkts-persiststorage.md)
示例如下:
```ts
@Component
struct LinkLinkChild {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkLinkChild: testNum value ${this.testNum}`);
}
build() {
Text(`LinkLinkChild: ${this.testNum}`)
}
}
@Component
struct PropLinkChild {
@StorageProp("testNum") @Watch("testNumChange") testNumGrand: number = 1;
testNumChange(propName: string): void {
console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
}
build() {
Text(`PropLinkChild: ${this.testNumGrand}`)
.height(70)
.backgroundColor(Color.Red)
.onClick(() => {
this.testNumGrand += 1;
})
}
}
@Component
struct Sibling {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`Sibling: testNumChange value ${this.testNum}`);
}
build() {
Text(`Sibling: ${this.testNum}`)
}
}
@Component
struct LinkChild {
@StorageLink("testNum") @Watch("testNumChange") testNum: number = 1;
testNumChange(propName: string): void {
console.log(`LinkChild: testNumChange value ${this.testNum}`);
}
build() {
Column() {
Button('incr testNum')
.onClick(() => {
console.log(`LinkChild: before value change value ${this.testNum}`);
this.testNum = this.testNum + 1
console.log(`LinkChild: after value change value ${this.testNum}`);
})
Text(`LinkChild: ${this.testNum}`)
LinkLinkChild({ /* empty */
})
PropLinkChild({ /* empty */
})
}
.height(200).width(200)
}
}
@Entry
@Component
struct Parent {
@StorageLink("testNum") @Watch("testNumChange1") testNum: number = 1;
testNumChange1(propName: string): void {
console.log(`Parent: testNumChange value ${this.testNum}`)
}
build() {
Column() {
LinkChild({ /* empty */
})
Sibling({ /* empty */
})
}
}
}
```
## ViewModel的嵌套场景
大多数情况下,ViewModel数据项都是复杂类型的,例如,对象数组、嵌套对象或者这些类型的组合。对于嵌套场景,可以使用\@Observed搭配\@Prop或者\@ObjectLink来观察变化。
### \@Prop和\@ObjectLink嵌套数据结构
推荐设计单独的\@Component来渲染每一个数组或对象。此时,对象数组或嵌套对象(属性是对象的对象称为嵌套对象)需要两个\@Component,一个\@Component呈现外部数组/对象,另一个\@Component呈现嵌套在数组/对象内的类对象。 \@Prop、\@Link、\@ObjectLink修饰的变量只能观察到第一层的变化。
- 对于类:
- 可以观察到赋值的变化:this.obj=new ClassObj(...)
- 可以观察到对象属性的更改:this.obj.a=new ClassA(...)
- 不能观察更深层级的属性更改:this.obj.a.b = 47
- 对于数组:
- 可以观察到数组的整体赋值:this.arr=[...]
- 可以观察到数据项的删除、插入和替换:this.arr[1] = new ClassA(); this.arr.pop(); this.arr.push(new ClassA(...)))、this.arr.sort(...)
- 不能观察更深层级的数组变化:this.arr[1].b = 47
如果要观察嵌套类的内部对象的变化,可以使用\@ObjectLink或\@Prop。优先考虑\@ObjectLink,其通过嵌套对象内部属性的引用初始化自身。\@Prop会对嵌套在内部的对象的深度拷贝来进行初始化,以实现单向同步。在性能上\@Prop的深度拷贝比\@ObjectLink的引用拷贝慢很多。
\@ObjectLink或\@Prop可以用来存储嵌套内部的类对象,该类必须用\@Observed类装饰器装饰,否则类的属性改变并不会触发更新UI并不会刷新。\@Observed为其装饰的类实现自定义构造函数,此构造函数创建了一个类的实例,并使用ES6代理包装(由ArkUI框架实现),拦截修饰class属性的所有“get”和“set”。“set”观察属性值,当发生赋值操作时,通知ArkUI框架更新。“get”收集哪些UI组件依赖该状态变量,实现最小化UI更新。
如果嵌套场景中,嵌套数据内部是数组或者class时,需根据以下场景使用\@Observed类装饰器。
- 如果嵌套数据内部是class,直接被\@Observed装饰。
- 如果嵌套数据内部是数组,可以通过以下方式来观察数组变化。
```ts
@Observed class ObservedArray<T> extends Array<T> {
constructor(args: any[]) {
super(...args);
}
/* otherwise empty */
}
```
ViewModel为外层class。
```ts
class Outer {
innerArrayProp : ObservedArray<string>;
...
}
```
### 嵌套数据结构中\@Prop和\@ObjectLink之的区别
以下示例中:
- 父组件ViewB渲染\@State arrA:Array&lt;ClassA&gt;\@State可以观察新数组的分配、数组项插入、删除和替换。
- 子组件ViewA渲染每一个ClassA的对象。
- 类装饰器\@Observed ClassA与\@ObjectLink a: ClassA。
- 可以观察嵌套在Array内的ClassA对象的变化。
- 不使用\@Observed时:
ViewB中的this.arrA[Math.floor(this.arrA.length/2)].c=10将不会被观察到,相应的ViewA组件也不会更新。
对于数组中的第一个和第二个数组项,每个数组项都初始化了两个ViewA的对象,渲染了同一个ViewA实例。在一个ViewA中的属性赋值this.a.c += 1;时不会引发另外一个使用同一个ClassA初始化的ViewA的渲染更新。
![zh-cn_image_0000001588610894](figures/zh-cn_image_0000001588610894.png)
```ts
let NextID: number = 1;
// 类装饰器@Observed装饰ClassA
@Observed
class ClassA {
public id: number;
public c: number;
constructor(c: number) {
this.id = NextID++;
this.c = c;
}
}
@Component
struct ViewA {
@ObjectLink a: ClassA;
label: string = "ViewA1";
build() {
Row() {
Button(`ViewA [${this.label}] this.a.c= ${this.a.c} +1`)
.onClick(() => {
// 改变对象属性
this.a.c += 1;
})
}
}
}
@Entry
@Component
struct ViewB {
@State arrA: ClassA[] = [new ClassA(0), new ClassA(0)];
build() {
Column() {
ForEach(this.arrA,
(item) => {
ViewA({ label: `#${item.id}`, a: item })
},
(item) => item.id.toString()
)
Divider().height(10)
if (this.arrA.length) {
ViewA({ label: `ViewA this.arrA[first]`, a: this.arrA[0] })
ViewA({ label: `ViewA this.arrA[last]`, a: this.arrA[this.arrA.length-1] })
}
Divider().height(10)
Button(`ViewB: reset array`)
.onClick(() => {
// 替换整个数组,会被@State this.arrA观察到
this.arrA = [new ClassA(0), new ClassA(0)];
})
Button(`array push`)
.onClick(() => {
// 数组中插入数据,会被@State this.arrA观察到
this.arrA.push(new ClassA(0))
})
Button(`array shift`)
.onClick(() => {
// 数组中移除数据,会被@State this.arrA观察到
this.arrA.shift()
})
Button(`ViewB: chg item property in middle`)
.onClick(() => {
// 替换数组中的某个元素,会被@State this.arrA观察到
this.arrA[Math.floor(this.arrA.length / 2)] = new ClassA(11);
})
Button(`ViewB: chg item property in middle`)
.onClick(() => {
// 改变数组中某个元素的属性c,会被ViewA中的@ObjectLink观察到
this.arrA[Math.floor(this.arrA.length / 2)].c = 10;
})
}
}
}
```
在ViewA中,将\@ObjectLink替换为\@Prop。
```ts
@Component
struct ViewA {
@Prop a: ClassA;
label : string = "ViewA1";
build() {
Row() {
Button(`ViewA [${this.label}] this.a.c= ${this.a.c} +1`)
.onClick(() => {
// change object property
this.a.c += 1;
})
}
}
}
```
与用\@ObjectLink修饰不同,用\@ObjectLink修饰时,点击数组的第一个或第二个元素,后面两个ViewA会发生同步的变化。
\@Prop是单向数据同步,ViewA内的Button只会触发Button自身的刷新,不会传播到其他的ViewA实例中。在ViewA中的ClassA只是一个副本,并不是其父组件中\@State arrA : Array&lt;ClassA&gt;中的对象,也不是其他ViewA的ClassA,这使得数组的元素和ViewA中的元素表面是传入的同一个对象,实际上在UI上渲染使用的是两个互不相干的对象。
需要注意\@Prop和\@ObjectLink还有一个区别:\@ObjectLink装饰的变量是仅可读的,不能被赋值;\@Prop装饰的变量可以被赋值。
- \@ObjectLink实现双向同步,因为它是通过数据源的引用初始化的。
- \@Prop是单向同步,需要深拷贝数据源。
- 对于\@Prop赋值新的对象,就是简单地将本地的值覆写,但是对于实现双向数据同步的\@ObjectLink,覆写新的对象相当于要更新数据源中的数组项或者class的属性,这个对于 TypeScript/JavaScript是不能实现的。
## MVVM应用示例
以下示例深入探讨了嵌套ViewModel的应用程序设计,特别是自定义组件如何渲染一个嵌套的Object,该场景在实际的应用开发中十分常见。
开发一个电话簿应用,实现功能如下:
- 显示联系人和本机("Me")电话号码 。
- 选中联系人时,进入可编辑态”Edit“,可以更新该联系人详细信息,包括电话号码,住址。
- 在更新联系人信息时,只有在单击保存“Save Changes”之后,才会保存更改。
- 可以点击删除联系人”Delete Contact“,可以在联系人列表删除该联系人。
ViewModel需要包括:
- AddressBook(class)
- me (本机): 存储一个Person类。
- contacts(本机联系人):存储一个Person类数组。
AddressBook类声明如下:
```ts
export class AddressBook {
me: Person;
contacts: ObservedArray<Person>;
constructor(me: Person, contacts: Person[]) {
this.me = me;
this.contacts = new ObservedArray<Person>(contacts);
}
}
```
- Person (class)
- name : string
- address : Address
- phones: ObservedArray&lt;string&gt;
- Address (class)
- street : string
- zip : number
- city : string
Address类声明如下:
```ts
@Observed
export class Address {
street: string;
zip: number;
city: string;
constructor(street: string,
zip: number,
city: string) {
this.street = street;
this.zip = zip;
this.city = city;
}
}
```
Person类声明如下:
```ts
@Observed
export class Person {
id_: string;
name: string;
address: Address;
phones: ObservedArray<string>;
constructor(name: string,
street: string,
zip: number,
city: string,
phones: string[]) {
this.id_ = `${nextId}`;
nextId++;
this.name = name;
this.address = new Address(street, zip, city);
this.phones = new ObservedArray<string>(phones);
}
}
```
需要注意的是,因为phones是嵌套属性,如果要观察到phones的变化,需要extends array,并用\@Observed修饰它。ObservedArray类的声明如下。
```ts
@Observed
export class ObservedArray<T> extends Array<T> {
constructor(args?: any[]) {
console.log(`ObservedArray: ${JSON.stringify(args)} `)
if (Array.isArray(args)) {
super(...args);
} else {
super(args)
}
}
}
```
- selected : 对Person的引用。
更新流程如下:
1. 在根节点PageEntry中初始化所有的数据,将me和contacts和其子组件AddressBookView建立双向数据同步,selectedPerson默认为me,需要注意,selectedPerson并不是PageEntry数据源中的数据,而是数据源中,对某一个Person的引用。
PageEntry和AddressBookView声明如下:
```ts
@Component
struct AddressBookView {
@ObjectLink me : Person;
@ObjectLink contacts : ObservedArray<Person>;
@State selectedPerson: Person = undefined;
aboutToAppear() {
this.selectedPerson = this.me;
}
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start}) {
Text("Me:")
PersonView({person: this.me, phones: this.me.phones, selectedPerson: this.$selectedPerson})
Divider().height(8)
ForEach(this.contacts,
contact => {
PersonView({person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson})
},
contact => contact.id_
)
Divider().height(8)
Text("Edit:")
PersonEditView({ selectedPerson: this.$selectedPerson, name: this.selectedPerson.name, address: this.selectedPerson.address, phones: this.selectedPerson.phones })
}
.borderStyle(BorderStyle.Solid).borderWidth(5).borderColor(0xAFEEEE).borderRadius(5)
}
}
@Entry
@Component
struct PageEntry {
@Provide addrBook: AddressBook = new AddressBook(
new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["+358441234567", "+35891234567", "+49621234567889"]),
[
new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["+358449876543", "+3589456789"]),
new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["+358509876543", "+358910101010"]),
new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["+358400908070", "+35894445555"]),
]);
build() {
Column() {
AddressBookView({ me: this.addrBook.me, contacts: this.addrBook.contacts, selectedPerson: this.addrBook.me })
}
}
}
```
2. PersonView,即电话簿中联系人姓名和首选电话的View,当用户选中,即高亮当前Person,需要同步回其父组件AddressBookView的selectedPerson,所以需要通过\@Link建立双向同步。
PersonView声明如下:
```ts
// 显示联系人姓名和首选电话
// 为了更新电话号码,这里需要@ObjectLink person和@ObjectLink phones,
// 显示首选号码不能使用this.person.phones[0],因为@ObjectLink person只代理了Person的属性,数组内部的变化观察不到
// 触发onClick事件更新selectedPerson
@Component
struct PersonView {
@ObjectLink person : Person;
@ObjectLink phones : ObservedArray<string>;
@Link selectedPerson : Person;
build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
Text(this.person.name)
if (this.phones.length) {
Text(this.phones[0])
}
}
.height(55)
.backgroundColor(this.selectedPerson.name == this.person.name ? "#ffa0a0" : "#ffffff")
.onClick(() => {
this.selectedPerson = this.person;
})
}
}
```
3. 选中的Person会在PersonEditView中显示详细信息,对于PersonEditView的数据同步分为以下三种方式:
- 在Edit状态通过Input.onChange回调事件接受用户的键盘输入时,在点击“Save Changes”之前,这个修改是不希望同步会数据源的,但又希望刷新在当前的PersonEditView中,所以\@Prop深拷贝当前Person的详细信息;
- PersonEditView通过\@Link seletedPerson: Person和AddressBookView的``selectedPerson建立双向同步,当用户点击“Save Changes”的时候,\@Prop的修改将被赋值给\@Link seletedPerson: Person,这就意味这,数据将被同步回数据源。
- PersonEditView中通过\@Consume addrBook: AddressBook和根节点PageEntry建立跨组件层级的直接的双向同步关系,当用户在PersonEditView界面删除某一个联系人时,会直接同步回PageEntry,PageEntry的更新会通知AddressBookView刷新contracts的列表页。 PersonEditView声明如下:
```ts
// 渲染Person的详细信息
// @Prop装饰的变量从父组件AddressBookView深拷贝数据,将变化保留在本地, TextInput的变化只会在本地副本上进行修改。
// 点击 "Save Changes" 会将所有数据的复制通过@Prop到@Link, 同步到其他组件
@Component
struct PersonEditView {
@Consume addrBook : AddressBook;
/* 指向父组件selectedPerson的引用 */
@Link selectedPerson: Person;
/*在本地副本上编辑,直到点击保存*/
@Prop name: string;
@Prop address : Address;
@Prop phones : ObservedArray<string>;
selectedPersonIndex() : number {
return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_);
}
build() {
Column() {
TextInput({ text: this.name})
.onChange((value) => {
this.name = value;
})
TextInput({text: this.address.street})
.onChange((value) => {
this.address.street = value;
})
TextInput({text: this.address.city})
.onChange((value) => {
this.address.city = value;
})
TextInput({text: this.address.zip.toString()})
.onChange((value) => {
const result = parseInt(value);
this.address.zip= isNaN(result) ? 0 : result;
})
if(this.phones.length>0) {
ForEach(this.phones,
(phone, index) => {
TextInput({text: phone})
.width(150)
.onChange((value) => {
console.log(`${index}. ${value} value has changed`)
this.phones[index] = value;
})
},
(phone, index) => `${index}-${phone}`
)
}
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
Text("Save Changes")
.onClick(() => {
// 将本地副本更新的值赋值给指向父组件selectedPerson的引用
// 避免创建新对象,在现有属性上进行修改
this.selectedPerson.name = this.name;
this.selectedPerson.address.street = this.address.street
this.selectedPerson.address.city = this.address.city
this.selectedPerson.address.zip = this.address.zip
this.phones.forEach((phone : string, index : number) => { this.selectedPerson.phones[index] = phone } );
})
if (this.selectedPersonIndex()!=-1) {
Text("Delete Contact")
.onClick(() => {
let index = this.selectedPersonIndex();
console.log(`delete contact at index ${index}`);
// 删除当前联系人
this.addrBook.contacts.splice(index, 1);
// 删除当前selectedPerson,选中态前移一位
index = (index < this.addrBook.contacts.length) ? index : index-1;
// 如果contract被删除完,则设置me为选中态
this.selectedPerson = (index>=0) ? this.addrBook.contacts[index] : this.addrBook.me;
})
}
}
}
}
}
```
其中在关于\@ObjectLink和\@Link的区别要注意以下几点:
1. 在AddressBookView中实现和父组件PageView的双向同步,需要用\@ObjectLink me : Person和\@ObjectLink contacts : ObservedArray&lt;Person&gt;,而不能用\@Link,原因如下:
- \@Link需要和其数据源类型完全相同,且仅能观察到第一层的变化;
- \@ObjectLink可以被数据源的属性初始化,且代理了\@Observed装饰类的属性,可以观察到被装饰类属性的变化。
2. 当 联系人姓名 (Person.name) 或者首选电话号码 (Person.phones[0]) 发生更新时,PersonView也需要同步刷新,其中Person.phones[0]属于第二层的更新,如果使用\@Link将无法观察到,而且\@Link需要和其数据源类型完全相同。所以在PersonView中也需要使用\@ObjectLink,即\@ObjectLink person : Person和\@ObjectLink phones : ObservedArray&lt;string&gt;。
![zh-cn_image_0000001605293914](figures/zh-cn_image_0000001605293914.png)
在这个例子中,我们可以大概了解到如何构建ViewModel,在应用的根节点中,ViewModel的数据可能是可以巨大的嵌套数据,但是在ViewModel和View的适配和渲染中,我们尽可能将ViewModel的数据项和View相适配,这样的话在针对每一层的View,都是一个相对“扁平”的数据,仅观察当前层就可以了。
在应用实际开发中,也许我们无法避免去构建一个十分庞大的Model,但是我们可以在UI树状结构中合理地去拆分数据,使得ViewModel和View更好的适配,从而搭配最小化更新来实现高性能开发。
完整应用代码如下:
```ts
// ViewModel classes
let nextId = 0;
@Observed
export class ObservedArray<T> extends Array<T> {
constructor(args?: any[]) {
console.log(`ObservedArray: ${JSON.stringify(args)} `)
if (Array.isArray(args)) {
super(...args);
} else {
super(args)
}
}
}
@Observed
export class Address {
street: string;
zip: number;
city: string;
constructor(street: string,
zip: number,
city: string) {
this.street = street;
this.zip = zip;
this.city = city;
}
}
@Observed
export class Person {
id_: string;
name: string;
address: Address;
phones: ObservedArray<string>;
constructor(name: string,
street: string,
zip: number,
city: string,
phones: string[]) {
this.id_ = `${nextId}`;
nextId++;
this.name = name;
this.address = new Address(street, zip, city);
this.phones = new ObservedArray<string>(phones);
}
}
export class AddressBook {
me: Person;
contacts: ObservedArray<Person>;
constructor(me: Person, contacts: Person[]) {
this.me = me;
this.contacts = new ObservedArray<Person>(contacts);
}
}
//渲染出Person对象的名称和手机Observed数组<string>中的第一个号码
//为了更新电话号码,这里需要@ObjectLink person和@ObjectLink phones,
//不能使用this.person.phones,内部数组的更改不会被观察到。
// 在AddressBookView、PersonEditView中的onClick更新selectedPerson
@Component
struct PersonView {
@ObjectLink person: Person;
@ObjectLink phones: ObservedArray<string>;
@Link selectedPerson: Person;
build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
Text(this.person.name)
if (this.phones.length) {
Text(this.phones[0])
}
}
.height(55)
.backgroundColor(this.selectedPerson.name == this.person.name ? "#ffa0a0" : "#ffffff")
.onClick(() => {
this.selectedPerson = this.person;
})
}
}
// 渲染Person的详细信息
// @Prop装饰的变量从父组件AddressBookView深拷贝数据,将变化保留在本地, TextInput的变化只会在本地副本上进行修改。
// 点击 "Save Changes" 会将所有数据的复制通过@Prop到@Link, 同步到其他组件
@Component
struct PersonEditView {
@Consume addrBook: AddressBook;
/* 指向父组件selectedPerson的引用 */
@Link selectedPerson: Person;
/*在本地副本上编辑,直到点击保存*/
@Prop name: string;
@Prop address: Address;
@Prop phones: ObservedArray<string>;
selectedPersonIndex(): number {
return this.addrBook.contacts.findIndex((person) => person.id_ == this.selectedPerson.id_);
}
build() {
Column() {
TextInput({ text: this.name })
.onChange((value) => {
this.name = value;
})
TextInput({ text: this.address.street })
.onChange((value) => {
this.address.street = value;
})
TextInput({ text: this.address.city })
.onChange((value) => {
this.address.city = value;
})
TextInput({ text: this.address.zip.toString() })
.onChange((value) => {
const result = parseInt(value);
this.address.zip = isNaN(result) ? 0 : result;
})
if (this.phones.length > 0) {
ForEach(this.phones,
(phone, index) => {
TextInput({ text: phone })
.width(150)
.onChange((value) => {
console.log(`${index}. ${value} value has changed`)
this.phones[index] = value;
})
},
(phone, index) => `${index}-${phone}`
)
}
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {
Text("Save Changes")
.onClick(() => {
// 将本地副本更新的值赋值给指向父组件selectedPerson的引用
// 避免创建新对象,在现有属性上进行修改
this.selectedPerson.name = this.name;
this.selectedPerson.address.street = this.address.street
this.selectedPerson.address.city = this.address.city
this.selectedPerson.address.zip = this.address.zip
this.phones.forEach((phone: string, index: number) => {
this.selectedPerson.phones[index] = phone
});
})
if (this.selectedPersonIndex() != -1) {
Text("Delete Contact")
.onClick(() => {
let index = this.selectedPersonIndex();
console.log(`delete contact at index ${index}`);
// 删除当前联系人
this.addrBook.contacts.splice(index, 1);
// 删除当前selectedPerson,选中态前移一位
index = (index < this.addrBook.contacts.length) ? index : index - 1;
// 如果contract被删除完,则设置me为选中态
this.selectedPerson = (index >= 0) ? this.addrBook.contacts[index] : this.addrBook.me;
})
}
}
}
}
}
@Component
struct AddressBookView {
@ObjectLink me: Person;
@ObjectLink contacts: ObservedArray<Person>;
@State selectedPerson: Person = undefined;
aboutToAppear() {
this.selectedPerson = this.me;
}
build() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start }) {
Text("Me:")
PersonView({ person: this.me, phones: this.me.phones, selectedPerson: this.$selectedPerson })
Divider().height(8)
ForEach(this.contacts,
contact => {
PersonView({ person: contact, phones: contact.phones, selectedPerson: this.$selectedPerson })
},
contact => contact.id_
)
Divider().height(8)
Text("Edit:")
PersonEditView({
selectedPerson: this.$selectedPerson,
name: this.selectedPerson.name,
address: this.selectedPerson.address,
phones: this.selectedPerson.phones
})
}
.borderStyle(BorderStyle.Solid).borderWidth(5).borderColor(0xAFEEEE).borderRadius(5)
}
}
@Entry
@Component
struct PageEntry {
@Provide addrBook: AddressBook = new AddressBook(
new Person("Gigi", "Itamerenkatu 9", 180, "Helsinki", ["+358441234567", "+35891234567", "+49621234567889"]),
[
new Person("Oly", "Itamerenkatu 9", 180, "Helsinki", ["+358449876543", "+3589456789"]),
new Person("Sam", "Itamerenkatu 9", 180, "Helsinki", ["+358509876543", "+358910101010"]),
new Person("Vivi", "Itamerenkatu 9", 180, "Helsinki", ["+358400908070", "+35894445555"]),
]);
build() {
Column() {
AddressBookView({ me: this.addrBook.me, contacts: this.addrBook.contacts, selectedPerson: this.addrBook.me })
}
}
}
```
\ No newline at end of file
# 渲染控制优秀实践
为了帮助应用程序开发人员提高其应用程序质量,本章节面向开发者提供了多个在开发ArkUI应用中常见场景和易错问题,并给出了对应的解决方案。此外,还提供了同一场景下,推荐用法和不推荐用法的对比和解释说明,更直观地展示两者区别,从而帮助开发者学习如果正确地在应用开发中使用渲染控制,进行高性能开发。
## 在ForEach数据源中添加元素
在ForEach数据源中添加元素导致数组项ID重复。
### 不推荐用法
下面示例使用ForEach方法迭代数组this.arr的每个元素,在Text组件进行显示,并在单击Text('Add arr element')时添加新的数组元素。
```ts
@Entry
@Component
struct Index {
@State arr: number[] = [1,2,3];
build() {
Column() {
ForEach(this.arr,
(item) => {
Text(`Item ${item}`)
},
item => item.toString())
Text('Add arr element')
.fontSize(20)
.onClick(()=>{
this.arr.push(4); // arr新增的元素,其在ForEach内的键值均为'4'
console.log("Arr elements: ", this.arr);
})
}
}
}
```
点击两次Text('Add arr element')时,数组this.arr每次都会添加新元素 4。但是在ForEach循环渲染中,第三个参数(item)=&gt; item.toString()需要生成Array每一个item对应的id值。该Array Id被要求是唯一的和稳定的。
- 唯一性:键值生成函数生成的每个数组项的id是不同的。
- 稳定性:当数组项ID发生变化时,ArkUI框架认为该数组项被替换或更改。
- ArkUI框架会对重复的ID告警,这种情况下框架的行为是未知的,特别是UI的更新在该场景下可能不起作用。
因此上述示例中,框架不会显示第二次及以后新添加的文本元素。因为这个元素不再是唯一的,他们都含有相同的id4。 但是如果删除ForEach第三个键值生成函数(item) =&gt; item.toString(),则触发onClick事件后每一个新添加的Text元素都会得到更新。这是因为框架使用了默认的Array id生成函数,即(item: any, index : number) =&gt; '${index}__${JSON.stringify(item)}'。它的兼容性更好但可能会导致不必要的UI更新,因此仍建议应用定义自己的键值生成函数。
## ForEach数据源更新
ForEach数据源更新时,数组项ID与原数组项ID重复不会重新创建该数组项。
### 不推荐用法
下面的示例定义了Index和Child两个组件。父组件Index有arr数组成员变量,初始值包含数字1、2、3。Child定义\@Prop value,接收父组件中arr数组中的一个元素。
```ts
@Component
struct Child {
@Prop value: number;
build() {
Text(`${this.value}`)
.fontSize(50)
.onClick(() => {
this.value++ // 点击改变@Prop的值
})
}
}
@Entry
@Component
struct Index {
@State arr: number[] = [1, 2, 3];
build() {
Row() {
Column() {
// 对照组
Child({ value: this.arr[0] })
Child({ value: this.arr[1] })
Child({ value: this.arr[2] })
Divider().height(5)
ForEach(this.arr,
item => {
Child({ value: item })
},
item => item.toString() // 键值,标识id
)
Text('Parent: replace entire arr')
.fontSize(50)
.onClick(() => {
// 两个数组项内均含有'3',ForEach内的id没有发生变化
// 意味着ForEach不会更新该Child实例,@Prop也不会在父组件处被更新
this.arr = (this.arr[0] == 1) ? [3, 4, 5] : [1, 2, 3];
})
}
}
}
}
```
当触发文本组件Parent: replace entire arr的onClick事件时,状态变量数组arr根据自身第一个元素的值将被[3, 4, 5]或[1, 2, 3]替换,但是ForEach里初始被创建的\@Prop传入值为3的Child组件并不会更新。
因为,老数组和新数组初始均含有同一个值的元素(数字3),而且该元素生成的标识id在父组件里没有变化。因此ForEach没有识别出对应的Child实例需要被新的输入值更新,对应的子组件内\@Prop也没有更新。
![zh-cn_image_0000001604900446](figures/zh-cn_image_0000001604900446.png)
可以在arr中用一个唯一的元素代替重复的元素3来观察本事件的行为表现。当恰当的替换掉数组时,接下来应用的表现才是符合预期的。
\ No newline at end of file
# 状态管理优秀实践
为了帮助应用程序开发人员提高其应用程序质量,特别是在高效的状态管理方面。本章节面向开发者提供了多个在开发ArkUI应用中常见场景和易错问题,并给出了对应的解决方案。此外,还提供了同一场景下,推荐用法和不推荐用法的对比和解释说明,更直观地展示两者区别,从而帮助开发者学习如果正确地在应用开发中使用状态变量,进行高性能开发。
## 基础示例
下面的例子是关于\@Prop,\@Link,\@ObjectLink的初始化规则的,在学习下面这个例子前,我们首先需要了解:
- \@Prop:可以被父组件的\@State初始化,或者\@State是复杂类型Object和class时的属性,或者是数组时的数组项。
- \@ObjectLink:初始化规则和\@Prop相同,但需要被\@Observed装饰class的实例初始化。
- \@Link:必须和\@State或其他数据源类型完全相同。
### 不推荐用法
```ts
@Observed
class ClassA {
public c: number = 0;
constructor(c: number) {
this.c = c;
}
}
@Component
struct LinkChild {
@Link testNum: number;
build() {
Text(`LinkChild testNum ${this.testNum}`)
}
}
@Component
struct PropChild2 {
@Prop testNum: ClassA;
build() {
Text(`PropChild2 testNum ${this.testNum.c}`)
.onClick(() => {
this.testNum.c += 1;
})
}
}
@Component
struct PropChild3 {
@Prop testNum: ClassA;
build() {
Text(`PropChild3 testNum ${this.testNum.c}`)
}
}
@Component
struct ObjectLinkChild {
@ObjectLink testNum: ClassA;
build() {
Text(`ObjectLinkChild testNum ${this.testNum.c}`)
.onClick(() => {
// 问题4:ObjectLink不能被赋值
this.testNum = new ClassA(47);
})
}
}
@Entry
@Component
struct Parent {
@State testNum: ClassA[] = [new ClassA(1)];
build() {
Column() {
Text(`Parent testNum ${this.testNum.c}`)
.onClick(() => {
this.testNum[0].c += 1;
})
// 问题1:@Link装饰的变量需要和数据源@State类型一致
LinkChild({ testNum: this.testNum.c })
// 问题2:@Prop本地没有初始化,也没有从父组件初始化
PropChild2()
// 问题3:PropChild3没有改变@Prop testNum: ClassA的值,所以这时最优的选择是使用@ObjectLink
PropChild3({ testNum: this.testNum[0] })
ObjectLinkChild({ testNum: this.testNum[0] })
}
}
}
```
上面的例子有以下几个错误:
1. \@Component LinkChild:\@Link testNum: number从父组件的LinkChild({testNum:this.testNum.c})。\@Link的数据源必须是装饰器装饰的状态变量,简而言之,\@Link装饰的数据必须和数据源类型相同,比如\@Link: T和\@State : T。所以,这里应该改为\@Link testNum: ClassA,从父组件初始化的方式为LinkChild({testNum: $testNum})。
2. \@Component PropChild2:\@Prop可以本地初始化,也可以从父组件初始化,但是必须初始化,对于\@Prop testNum: ClassA没有本地初始化,所以必须从父组件初始化PropChild1({testNum: this.testNum})。
3. \@Component PropChild3:没有改变\@Prop testNum: ClassA的值,所以这时较优的选择是使用\@ObjectLink,因为\@Prop是会深拷贝数据,具有拷贝的性能开销,所以这个时候\@ObjectLink是比\@Link和\@Prop更优的选择。
4. 点击ObjectLinkChild给\@ObjectLink装饰的变量赋值:this.testNum = new ClassA(47); 也是不允许的,对于实现双向数据同步的\@ObjectLink,赋值相当于要更新父组件中的数组项或者class的属性,这个对于 TypeScript/JavaScript是不能实现的。框架对于这种行为会发生运行时报错。
5. 如果是非嵌套场景,比如Parent里声明的变量为 \@State testNum: ClassA = new ClassA(1),ClassA就不需要被\@Observed修饰,因为\@State已经具备了观察第一层变化的能力,不需要再使用\@Observed来加一层代理。
### 推荐用法
```ts
@Observed
class ClassA {
public c: number = 0;
constructor(c: number) {
this.c = c;
}
}
@Component
struct LinkChild {
@Link testNum: ClassA;
build() {
Text(`LinkChild testNum ${this.testNum?.c}`)
}
}
@Component
struct PropChild1 {
@Prop testNum: ClassA = new ClassA(1);
build() {
Text(`PropChild1 testNum ${this.testNum?.c}`)
.onClick(() => {
this.testNum = new ClassA(48);
})
}
}
@Component
struct ObjectLinkChild {
@ObjectLink testNum: ClassA;
build() {
Text(`ObjectLinkChild testNum ${this.testNum.c}`)
// @ObjectLink装饰的变量可以更新属性
.onClick(() => {
this.testNum.c += 1;
})
}
}
@Entry
@Component
struct Parent {
@State testNum: ClassA[] = [new ClassA(1)];
build() {
Column() {
Text(`Parent testNum ${this.testNum.c}`)
.onClick(() => {
this.testNum[0].c += 1;
})
// @Link装饰的变量需要和数据源@State类型一致
LinkChild({ testNum: this.testNum[0] })
// @Prop本地有初始化,不需要再从父组件初始化
PropChild1()
// 当子组件不需要发生本地改变时,优先使用@ObjectLink,因为@Prop是会深拷贝数据,具有拷贝的性能开销,所以这个时候@ObjectLink是比@Link和@Prop更优的选择
ObjectLinkChild({ testNum: this.testNum[0] })
}
}
}
```
## 基础嵌套对象属性更改失效
在应用开发中,有很多嵌套对象场景,例如,开发者更新了某个属性,但UI没有进行对应的更新。
每个装饰器都有自己可以观察的能力,并不是所有的改变都可以被观察到,只有可以被观察到的变化才会进行UI更新。\@Observed装饰器可以观察到嵌套对象的属性变化,其他装饰器仅能观察到第二层的变化。
### 不推荐用法
下面的例子中,一些UI组件并不会更新。
```ts
class ClassA {
a: number;
constructor(a: number) {
this.a = a;
}
getA(): number {
return this.a;
}
setA(a: number): void {
this.a = a;
}
}
class ClassC {
c: number;
constructor(c: number) {
this.c = c;
}
getC(): number {
return this.c;
}
setC(c: number): void {
this.c = c;
}
}
class ClassB extends ClassA {
b: number = 47;
c: ClassC;
constructor(a: number, b: number, c: number) {
super(a);
this.b = b;
this.c = new ClassC(c);
}
getB(): number {
return this.b;
}
setB(b: number): void {
this.b = b;
}
getC(): number {
return this.c.getC();
}
setC(c: number): void {
return this.c.setC(c);
}
}
@Entry
@Component
struct MyView {
@State b: ClassB = new ClassB(10, 20, 30);
build() {
Column({ space: 10 }) {
Text(`a: ${this.b.a}`)
Button("Change ClassA.a")
.onClick(() => {
this.b.a += 1;
})
Text(`b: ${this.b.b}`)
Button("Change ClassB.b")
.onClick(() => {
this.b.b += 1;
})
Text(`c: ${this.b.c.c}`)
Button("Change ClassB.ClassC.c")
.onClick(() => {
// 点击时上面的Text组件不会刷新
this.b.c.c += 1;
})
}
}
}
```
- 最后一个Text组件Text('c: ${this.b.c.c}'),当点击该组件时UI不会刷新。 因为,\@State b : ClassB 只能观察到this.b属性的变化,比如this.b.a, this.b.b 和this.b.c的变化,但是无法观察嵌套在属性中的属性,即this.b.c.c(属性c是内嵌在b中的对象classC的属性)。
- 为了观察到嵌套与内部的ClassC的属性,需要做如下改变:
- 构造一个子组件,用于单独渲染ClassC的实例。 该子组件可以使用\@ObjectLink c : ClassC或\@Prop c : ClassC。通常会使用\@ObjectLink,除非子组件需要对其ClassC对象进行本地修改。
- 嵌套的ClassC必须用\@Observed修饰。当在ClassB中创建ClassC对象时(本示例中的ClassB(10, 20, 30)),它将被包装在ES6代理中,当ClassC属性更改时(this.b.c.c += 1),该代码将修改通知到\@ObjectLink变量。
### 推荐用法
以下示例使用\@Observed/\@ObjectLink来观察嵌套对象的属性更改。
```ts
class ClassA {
a: number;
constructor(a: number) {
this.a = a;
}
getA() : number {
return this.a; }
setA( a: number ) : void {
this.a = a; }
}
@Observed
class ClassC {
c: number;
constructor(c: number) {
this.c = c;
}
getC() : number {
return this.c; }
setC(c : number) : void {
this.c = c; }
}
class ClassB extends ClassA {
b: number = 47;
c: ClassC;
constructor(a: number, b: number, c: number) {
super(a);
this.b = b;
this.c = new ClassC(c);
}
getB() : number {
return this.b; }
setB(b : number) : void {
this.b = b; }
getC() : number {
return this.c.getC(); }
setC(c : number) : void {
return this.c.setC(c); }
}
@Component
struct ViewClassC {
@ObjectLink c : ClassC;
build() {
Column({space:10}) {
Text(`c: ${this.c.getC()}`)
Button("Change C")
.onClick(() => {
this.c.setC(this.c.getC()+1);
})
}
}
}
@Entry
@Component
struct MyView {
@State b : ClassB = new ClassB(10, 20, 30);
build() {
Column({space:10}) {
Text(`a: ${this.b.a}`)
Button("Change ClassA.a")
.onClick(() => {
this.b.a +=1;
})
Text(`b: ${this.b.b}`)
Button("Change ClassB.b")
.onClick(() => {
this.b.b += 1;
})
ViewClassC({c: this.b.c}) // Text(`c: ${this.b.c.c}`)的替代写法
Button("Change ClassB.ClassC.c")
.onClick(() => {
this.b.c.c += 1;
})
}
}
}
```
## 复杂嵌套对象属性更改失效
### 不推荐用法
以下示例创建了一个带有\@ObjectLink装饰变量的子组件,用于渲染一个含有嵌套属性的ParentCounter,用\@Observed装饰嵌套在ParentCounter中的SubCounter。
```ts
let nextId = 1;
@Observed
class SubCounter {
counter: number;
constructor(c: number) {
this.counter = c;
}
}
@Observed
class ParentCounter {
id: number;
counter: number;
subCounter: SubCounter;
incrCounter() {
this.counter++;
}
incrSubCounter(c: number) {
this.subCounter.counter += c;
}
setSubCounter(c: number): void {
this.subCounter.counter = c;
}
constructor(c: number) {
this.id = nextId++;
this.counter = c;
this.subCounter = new SubCounter(c);
}
}
@Component
struct CounterComp {
@ObjectLink value: ParentCounter;
build() {
Column({ space: 10 }) {
Text(`${this.value.counter}`)
.fontSize(25)
.onClick(() => {
this.value.incrCounter();
})
Text(`${this.value.subCounter.counter}`)
.onClick(() => {
this.value.incrSubCounter(1);
})
Divider().height(2)
}
}
}
@Entry
@Component
struct ParentComp {
@State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
build() {
Row() {
Column() {
CounterComp({ value: this.counter[0] })
CounterComp({ value: this.counter[1] })
CounterComp({ value: this.counter[2] })
Divider().height(5)
ForEach(this.counter,
item => {
CounterComp({ value: item })
},
item => item.id.toString()
)
Divider().height(5)
// 第一个点击事件
Text('Parent: incr counter[0].counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].incrCounter();
// 每次触发时自增10
this.counter[0].incrSubCounter(10);
})
// 第二个点击事件
Text('Parent: set.counter to 10')
.fontSize(20).height(50)
.onClick(() => {
// 无法将value设置为10,UI不会刷新
this.counter[0].setSubCounter(10);
})
Text('Parent: reset entire counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
})
}
}
}
}
```
对于Text('Parent: incr counter[0].counter')的onClick事件,this.counter[0].incrSubCounter(10)调用incrSubCounter方法使SubCounter的counter值增加10,UI同步刷新。
但是,在Text('Parent: set.counter to 10')的onClick中调用this.counter[0].setSubCounter(10),SubCounter的counter值却无法重置为10。
incrSubCounter和setSubCounter都是同一个SubCounter的函数。在第一个点击处理时调用incrSubCounter可以正确更新UI,而第二个点击处理调用setSubCounter时却没有更新UI。实际上incrSubCounter和setSubCounter两个函数都不能触发Text('${this.value.subCounter.counter}')的更新,因为\@ObjectLink value : ParentCounter仅能观察其代理ParentCounter的属性,对于this.value.subCounter.counter是SubCounter的属性,无法观察到嵌套类的属性。
但是,第一个click事件调用this.counter[0].incrCounter()将CounterComp自定义组件中\@ObjectLink value: ParentCounter标记为已更改。此时触发Text('${this.value.subCounter.counter}')的更新。 如果在第一个点击事件中删除this.counter[0].incrCounter(),也无法更新UI。
### 推荐用法
对于上述问题,为了直接观察SubCounter中的属性,以便this.counter[0].setSubCounter(10)操作有效,可以利用下面的方法:
```ts
@ObjectLink valueParentCounter;
@ObjectLink subValueSubCounter;
```
该方法使得\@ObjectLink分别代理了ParentCounter和SubCounter的属性,这样对于这两个类的属性的变化都可以观察到,即都会对UI视图进行刷新。即使删除了上面所说的this.counter[0].incrCounter(),UI也会进行正确的刷新。
该方法可用于实现“两个层级”的观察,即外部对象和内部嵌套对象的观察。但是该方法只能用于\@ObjectLink装饰器,无法作用于\@Prop(\@Prop通过深拷贝传入对象)。详情参考@Prop与@ObjectLink的差异。
```ts
let nextId = 1;
@Observed
class SubCounter {
counter: number;
constructor(c: number) {
this.counter = c;
}
}
@Observed
class ParentCounter {
id: number;
counter: number;
subCounter: SubCounter;
incrCounter() {
this.counter++;
}
incrSubCounter(c: number) {
this.subCounter.counter += c;
}
setSubCounter(c: number): void {
this.subCounter.counter = c;
}
constructor(c: number) {
this.id = nextId++;
this.counter = c;
this.subCounter = new SubCounter(c);
}
}
@Component
struct CounterComp {
@ObjectLink value: ParentCounter;
@ObjectLink subValue: SubCounter;
build() {
Column({ space: 10 }) {
Text(`${this.value.counter}`)
.fontSize(25)
.onClick(() => {
this.value.incrCounter();
})
Text(`${this.subValue.counter}`)
.onClick(() => {
this.subValue.counter += 1;
})
Divider().height(2)
}
}
}
@Entry
@Component
struct ParentComp {
@State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
build() {
Row() {
Column() {
CounterComp({ value: this.counter[0], subValue: this.counter[0].subCounter })
CounterComp({ value: this.counter[1], subValue: this.counter[1].subCounter })
CounterComp({ value: this.counter[2], subValue: this.counter[2].subCounter })
Divider().height(5)
ForEach(this.counter,
item => {
CounterComp({ value: item, subValue: item.subCounter })
},
item => item.id.toString()
)
Divider().height(5)
Text('Parent: reset entire counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
})
Text('Parent: incr counter[0].counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].incrCounter();
this.counter[0].incrSubCounter(10);
})
Text('Parent: set.counter to 10')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].setSubCounter(10);
})
}
}
}
}
```
## \@Prop与\@ObjectLink的差异
在下面的示例代码中,\@ObjectLink修饰的变量是对数据源的引用,即在this.value.subValue和this.subValue都是同一个对象的不同引用,所以在点击CounterComp的click handler,改变this.value.subCounter.counter,this.subValue.counter也会改变,对应的组件Text(`this.subValue.counter: ${this.subValue.counter}`)会刷新。
```ts
let nextId = 1;
@Observed
class SubCounter {
counter: number;
constructor(c: number) {
this.counter = c;
}
}
@Observed
class ParentCounter {
id: number;
counter: number;
subCounter: SubCounter;
incrCounter() {
this.counter++;
}
incrSubCounter(c: number) {
this.subCounter.counter += c;
}
setSubCounter(c: number): void {
this.subCounter.counter = c;
}
constructor(c: number) {
this.id = nextId++;
this.counter = c;
this.subCounter = new SubCounter(c);
}
}
@Component
struct CounterComp {
@ObjectLink value: ParentCounter;
@ObjectLink subValue: SubCounter;
build() {
Column({ space: 10 }) {
Text(`this.subValue.counter: ${this.subValue.counter}`)
.fontSize(30)
Text(`this.value.counter:increase 7 `)
.fontSize(30)
.onClick(() => {
// click handler, Text(`this.subValue.counter: ${this.subValue.counter}`) will update
this.value.incrSubCounter(7);
})
Divider().height(2)
}
}
}
@Entry
@Component
struct ParentComp {
@State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
build() {
Row() {
Column() {
CounterComp({ value: this.counter[0], subValue: this.counter[0].subCounter })
CounterComp({ value: this.counter[1], subValue: this.counter[1].subCounter })
CounterComp({ value: this.counter[2], subValue: this.counter[2].subCounter })
Divider().height(5)
ForEach(this.counter,
item => {
CounterComp({ value: item, subValue: item.subCounter })
},
item => item.id.toString()
)
Divider().height(5)
Text('Parent: reset entire counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
})
Text('Parent: incr counter[0].counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].incrCounter();
this.counter[0].incrSubCounter(10);
})
Text('Parent: set.counter to 10')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].setSubCounter(10);
})
}
}
}
}
```
\@ObjectLink图示如下:
![zh-cn_image_0000001651665921](figures/zh-cn_image_0000001651665921.png)
### 不推荐用法
如果用\@Prop替代\@ObjectLink。点击第一个click handler,UI刷新正常。但是点击第二个onClick事件,\@Prop 对变量做了一个本地拷贝,CounterComp的第一个Text并不会刷新。
this.value.subCounter和this.subValue并不是同一个对象。所以this.value.subCounter的改变,并没有改变this.subValue的拷贝对象,Text(`this.subValue.counter: ${this.subValue.counter}`)不会刷新。
```ts
@Component
struct CounterComp {
@Prop value: ParentCounter;
@Prop subValue: SubCounter;
build() {
Column({ space: 10 }) {
Text(`this.subValue.counter: ${this.subValue.counter}`)
.fontSize(20)
.onClick(() => {
// 1st click handler
this.subValue.counter += 7;
})
Text(`this.value.counter:increase 7 `)
.fontSize(20)
.onClick(() => {
// 2nd click handler
this.value.incrSubCounter(7);
})
Divider().height(2)
}
}
}
```
\@Prop拷贝的关系图示如下:
![zh-cn_image_0000001602146116](figures/zh-cn_image_0000001602146116.png)
### 推荐用法
可以通过从ParentComp到CounterComp仅拷贝一份\@Prop value: ParentCounter,同时必须避免再多拷贝一份SubCounter。
- 在CounterComp组件中只使用一个\@Prop counter:Counter。
- 添加另一个子组件SubCounterComp,其中包含\@ObjectLink subCounter: SubCounter。此\@ObjectLink可确保观察到SubCounter对象属性更改,并且UI更新正常。
- \@ObjectLink subCounter: SubCounter与CounterComp中的\@Prop counter:Counter的this.counter.subCounter共享相同的SubCounter对象。
```ts
@Component
struct SubCounterComp {
@ObjectLink subValue: SubCounter;
build() {
Text(`SubCounterComp: this.subValue.counter: ${this.subValue.counter}`)
.onClick(() => {
// 2nd click handler
this.subValue.incrSubCounter(7);
})
}
}
@Component
struct CounterComp {
@Prop value: ParentCounter;
build() {
Column({ space: 10 }) {
Text(`this.value.incrCounter(): this.value.counter: ${this.value.counter}`)
.fontSize(20)
.onClick(() => {
// 1st click handler
this.value.incrCounter();
})
SubCounterComp({ subValue: this.value.subCounter })
Text(`this.value.incrSubCounter()`)
.onClick(() => {
// 3rd click handler
this.value.incrSubCounter(77);
})
Divider().height(2)
}
}
}
@Entry
@Component
struct ParentComp {
@State counter: ParentCounter[] = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
build() {
Row() {
Column() {
CounterComp({ value: this.counter[0] })
CounterComp({ value: this.counter[1] })
CounterComp({ value: this.counter[2] })
Divider().height(5)
ForEach(this.counter,
item => {
CounterComp({ value: item })
},
item => item.id.toString()
)
Divider().height(5)
Text('Parent: reset entire counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter = [new ParentCounter(1), new ParentCounter(2), new ParentCounter(3)];
})
Text('Parent: incr counter[0].counter')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].incrCounter();
this.counter[0].incrSubCounter(10);
})
Text('Parent: set.counter to 10')
.fontSize(20).height(50)
.onClick(() => {
this.counter[0].setSubCounter(10);
})
}
}
}
}
```
拷贝关系图示如下:
![zh-cn_image_0000001653949465](figures/zh-cn_image_0000001653949465.png)
## 应用在渲染期间禁止改变状态变量
在学习本示例之前,我们要先明确一个概念,在ArkUI状态管理中,状态驱动UI更新。
![zh-cn_image_0000001651365257](figures/zh-cn_image_0000001651365257.png)
所以,不能在自定义组件的build()或\@Builder方法里直接改变状态变量,这可能会造成循环渲染的风险,下面以build()方法举例示意。
### 不推荐用法
在下面的示例中,Text('${this.count++}')在build渲染方法里直接改变了状态变量。
```ts
@Entry
@Component
struct CompA {
@State col1: Color = Color.Yellow;
@State col2: Color = Color.Green;
@State count: number = 1;
build() {
Column() {
// 应避免直接在Text组件内改变count的值
Text(`${this.count++}`)
.width(50)
.height(50)
.fontColor(this.col1)
.onClick(() => {
this.col2 = Color.Red;
})
Button("change col1").onClick(() =>{
this.col1 = Color.Pink;
})
}
.backgroundColor(this.col2)
}
}
```
在ArkUI中,Text('${this.count++}')在全量更新或最小化更新会产生不同的影响:
- 全量更新: ArkUI可能会陷入一个无限的重渲染的循环里,因为Text组件的每一次渲染都会改变应用的状态,就会再引起下一轮渲染的开启。 当 this.col2 更改时,都会执行整个build构建函数,因此,Text(`${this.count++}`)绑定的文本也会更改,每次重新渲染Text(`${this.count++}`),又会使this.count状态变量更新,导致新一轮的build执行,从而陷入无限循环。
- 最小化更新: 当 this.col2 更改时,只有Column组件会更新,Text组件不会更改。 只当 this.col1 更改时,会去更新整个Text组件,其所有属性函数都会执行,所以会看到Text(`${this.count++}`)自增。因为目前UI以组件为单位进行更新,如果组件上某一个属性发生改变,会更新整体的组件。所以整体的更新链路是:this.col2 = Color.Red -&gt; Text组件整体更新-&gt;this.count++-&gt;Text组件整体更新。
### 推荐用法
建议应用的开发方法在事件处理程序中执行count++操作。
```ts
@Entry
@Component
struct CompA {
@State col1: Color = Color.Yellow;
@State col2: Color = Color.Green;
@State count: number = 1;
build() {
Column() {
Text(`${this.count}`)
.width(50)
.height(50)
.backgroundColor(this.col1)
.onClick(() => {
this.count++;
})
}
.backgroundColor(this.col2)
}
}
```
build函数中更改应用状态的行为可能会比上面的示例更加隐蔽,比如:
-\@Builder,\@Extend或\@Styles方法内改变状态变量 。
- 在计算参数时调用函数中改变应用状态变量,例如 Text('${this.calcLabel()}')。
- 对当前数组做出修改,sort()改变了数组this.arr,随后的filter方法会返回一个新的数组。
```ts
@State arr : Array<..> = [ ... ];
ForEach(this.arr.sort().filter(....),
item => {
...
})
```
正确的执行方式为:filter返回一个新数组,后面的sort方法才不会改变原数组this.arr,示例:
```ts
ForEach(this.arr.filter(....).sort(),
item => {
...
})
```
## 使用状态变量强行更新
### 不推荐用法
```ts
@Entry
@Component
struct CompA {
@State needsUpdate: boolean = true;
realState1: Array<number> = [4, 1, 3, 2]; // 未使用状态变量装饰器
realState2: Color = Color.Yellow;
updateUI(param: any): any {
const triggerAGet = this.needsUpdate;
return param;
}
build() {
Column({ space: 20 }) {
ForEach(this.updateUI(this.realState1),
item => {
Text(`${item}`)
})
Text("add item")
.onClick(() => {
// 改变realState1不会触发UI视图更新
this.realState1.push(this.realState1[this.realState1.length-1] + 1);
// 触发UI视图更新
this.needsUpdate = !this.needsUpdate;
})
Text("chg color")
.onClick(() => {
// 改变realState2不会触发UI视图更新
this.realState2 = this.realState2 == Color.Yellow ? Color.Red : Color.Yellow;
// 触发UI视图更新
this.needsUpdate = !this.needsUpdate;
})
}.backgroundColor(this.updateUI(this.realState2))
.width(200).height(500)
}
}
```
上述示例存在以下问题:
- 应用程序希望控制UI更新逻辑,但在ArkUI中,UI更新的逻辑应该是由框架来检测应用程序状态变量的更改去实现。
- this.needsUpdate是一个自定义的UI状态变量,应该仅应用于其绑定的UI组件。变量this.realState1、this.realState2没有被装饰,他们的变化将不会触发UI刷新。
- 但是在该应用中,用户试图通过this.needsUpdate的更新来带动常规变量this.realState1、this.realState2的更新。此方法不合理且更新性能较差,如果只想更新背景颜色,且不需要更新ForEach,但this.needsUpdate值的变化也会带动ForEach更新。
### 推荐用法
要解决此问题,应将realState1和realState2成员变量用\@State装饰。一旦完成此操作,就不再需要变量needsUpdate。
```ts
@Entry
@Component
struct CompA {
@State realState1: Array<number> = [4, 1, 3, 2];
@State realState2: Color = Color.Yellow;
build() {
Column({ space: 20 }) {
ForEach(this.realState1,
item => {
Text(`${item}`)
})
Text("add item")
.onClick(() => {
// 改变realState1触发UI视图更新
this.realState1.push(this.realState1[this.realState1.length-1] + 1);
})
Text("chg color")
.onClick(() => {
// 改变realState2触发UI视图更新
this.realState2 = this.realState2 == Color.Yellow ? Color.Red : Color.Yellow;
})
}.backgroundColor(this.realState2)
.width(200).height(500)
}
}
```
\ No newline at end of file
...@@ -1566,7 +1566,7 @@ function main() { ...@@ -1566,7 +1566,7 @@ function main() {
### ArkUI示例 ### ArkUI示例
以下示例提供了一个完整的基于ArkUI的应用程序,以展示其GUI编程功能。有关ArkUI功能的更多详细信息,请参见ArkUI[指导手册](../arkts-get-started.md) 以下示例提供了一个完整的基于ArkUI的应用程序,以展示其GUI编程功能。有关ArkUI功能的更多详细信息,请参见ArkUI[指导手册](arkts-get-started.md)
```typescript ```typescript
// ViewModel classes --------------------------- // ViewModel classes ---------------------------
......
...@@ -202,7 +202,7 @@ ...@@ -202,7 +202,7 @@
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](js-apis-arkui-drawableDescriptor.md)
- [@ohos.arkui.inspector (布局回调)](js-apis-arkui-inspector.md) - [@ohos.arkui.inspector (布局回调)](js-apis-arkui-inspector.md)
- [@ohos.arkui.UIContext (UIContext)](js-apis-arkui-UIContext.md) - [@ohos.arkui.UIContext (UIContext)](js-apis-arkui-UIContext.md)
- [@ohos.componentUtils (componentUtils)](js-apis-componentUtils.md) - [@ohos.arkui.componentUtils (componentUtils)](js-apis-arkui-componentUtils.md)
- [@ohos.curves (插值计算)](js-apis-curve.md) - [@ohos.curves (插值计算)](js-apis-curve.md)
- [@ohos.font (注册自定义字体)](js-apis-font.md) - [@ohos.font (注册自定义字体)](js-apis-font.md)
- [@ohos.matrix4 (矩阵变换)](js-apis-matrix4.md) - [@ohos.matrix4 (矩阵变换)](js-apis-matrix4.md)
......
...@@ -39,7 +39,7 @@ Ability初次启动原因,该类型为枚举,可配合[Ability](js-apis-app- ...@@ -39,7 +39,7 @@ Ability初次启动原因,该类型为枚举,可配合[Ability](js-apis-app-
| CALL | 2 | 通过[startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall)接口启动ability。 | | CALL | 2 | 通过[startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall)接口启动ability。 |
| CONTINUATION | 3 | 跨端设备迁移启动ability。 | | CONTINUATION | 3 | 跨端设备迁移启动ability。 |
| APP_RECOVERY | 4 | 设置应用恢复后,应用故障时自动恢复启动ability。 | | APP_RECOVERY | 4 | 设置应用恢复后,应用故障时自动恢复启动ability。 |
| SHARE<sup>10+</sup> | 5 | 通过[acquireShareData](js-apis-app-ability-abilityManager.md#acquiresharedata)接口启动ability。 | | SHARE<sup>10+</sup> | 5 | 通过原子化服务分享启动ability。 |
**示例:** **示例:**
......
...@@ -315,7 +315,7 @@ class MyUIAbility extends UIAbility { ...@@ -315,7 +315,7 @@ class MyUIAbility extends UIAbility {
onShare(wantParam:{ [key: string]: Object }): void; onShare(wantParam:{ [key: string]: Object }): void;
ability设置分享数据。其中,ohos.extra.param.key.contentTitle表示分享框中对分享内容title的描述,ohos.extra.param.key.shareAbstract表示分享框中对携带内容的摘要描述,ohos.extra.param.key.shareUrl表示服务的在线地址。以上三项分享数据均是开发者填充,且为Object对象,对象的key分别为title,abstract,url ability设置分享数据,ohos.extra.param.key.shareUrl表示服务的在线地址
**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore **系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
...@@ -332,9 +332,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'; ...@@ -332,9 +332,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility { class MyUIAbility extends UIAbility {
onShare(wantParams) { onShare(wantParams) {
console.log('onShare'); console.log('onShare');
wantParams['ohos.extra.param.key.contentTitle'] = 'shareFeatureAbility'; wantParams['ohos.extra.param.key.shareUrl'] = 'example.com';
wantParams['ohos.extra.param.key.shareAbstract'] = 'huawei employee';
wantParams['ohos.extra.param.key.shareUrl'] = 'w3.huawei.com';
} }
} }
``` ```
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
import cloudData from '@ohos.data.cloudData'; import cloudData from '@ohos.data.cloudData';
``` ```
## Action ## ClearAction
清除本地下载的云端数据的行为枚举。 清除本地下载的云端数据的行为枚举。
...@@ -347,9 +347,9 @@ try { ...@@ -347,9 +347,9 @@ try {
} }
``` ```
### clean ### clear
static clean(accountId: string, appActions: {[bundleName: string]: Action}, callback: AsyncCallback&lt;void&gt;):void static clear(accountId: string, appActions: {[bundleName: string]: ClearAction}, callback: AsyncCallback&lt;void&gt;):void
清除本地下载的云端数据,使用callback异步回调。 清除本地下载的云端数据,使用callback异步回调。
...@@ -361,26 +361,26 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}, cal ...@@ -361,26 +361,26 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}, cal
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------- | ----------------------------------------- | ---- | -------------------------------- | | ---------- | --------------------------------------------------- | ---- | -------------------------------- |
| accountId | string | 是 | 具体打开的云帐号ID。 | | accountId | string | 是 | 具体打开的云帐号ID。 |
| appActions | {[bundleName: string]: [Action](#action)} | 是 | 要清除数据的应用信息及清除规则。 | | appActions | {[bundleName: string]: [ClearAction](#clearaction)} | 是 | 要清除数据的应用信息及清除规则。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**示例:** **示例:**
```js ```js
let action = cloudData.Action; let action = cloudData.ClearAction;
let account = "test_id"; let account = "test_id";
let bundleName1 = "test_bundleName1"; let bundleName1 = "test_bundleName1";
let bundleName2 = "test_bundleName2"; let bundleName2 = "test_bundleName2";
let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO }; let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO };
try { try {
cloudData.Config.clean(account, appActions, function (err) { cloudData.Config.clear(account, appActions, function (err) {
if (err === undefined) { if (err === undefined) {
console.info('Succeeding in cleaning cloud data'); console.info('Succeeding in clearing cloud data');
} else { } else {
console.error(`Failed to clean cloud data. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to clear cloud data. Code: ${err.code}, message: ${err.message}`);
} }
}); });
} catch (error) { } catch (error) {
...@@ -388,9 +388,9 @@ try { ...@@ -388,9 +388,9 @@ try {
} }
``` ```
### clean ### clear
static clean(accountId: string, appActions: {[bundleName: string]: Action}): Promise&lt;void&gt; static clear(accountId: string, appActions: {[bundleName: string]: ClearAction}): Promise&lt;void&gt;
清除本地下载的云端数据,使用Promise异步回调。 清除本地下载的云端数据,使用Promise异步回调。
...@@ -402,10 +402,10 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}): Pro ...@@ -402,10 +402,10 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}): Pro
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------- | ----------------------------------------- | ---- | -------------------------------- | | ---------- | --------------------------------------------------- | ---- | -------------------------------- |
| accountId | string | 是 | 具体打开的云帐号ID。 | | accountId | string | 是 | 具体打开的云帐号ID。 |
| appActions | {[bundleName: string]: [Action](#action)} | 是 | 要清除数据的应用信息及清除规则。 | | appActions | {[bundleName: string]: [ClearAction](#clearaction)} | 是 | 要清除数据的应用信息及清除规则。 |
**返回值:** **返回值:**
...@@ -416,16 +416,16 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}): Pro ...@@ -416,16 +416,16 @@ static clean(accountId: string, appActions: {[bundleName: string]: Action}): Pro
**示例:** **示例:**
```js ```js
let action = cloudData.Action; let action = cloudData.ClearAction;
let account = "test_id"; let account = "test_id";
let bundleName1 = "test_bundleName1"; let bundleName1 = "test_bundleName1";
let bundleName2 = "test_bundleName2"; let bundleName2 = "test_bundleName2";
let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO }; let appActions = { [bundleName1]: action.CLEAR_CLOUD_INFO, [bundleName2]: action.CLEAR_CLOUD_DATA_AND_INFO };
try { try {
cloudData.Config.clean(account, appActions).then(() => { cloudData.Config.clear(account, appActions).then(() => {
console.info('Succeeding in cleaning cloud data'); console.info('Succeeding in clearing cloud data');
}).catch((err) => { }).catch((err) => {
console.error(`Failed to clean cloud data. Code: ${err.code}, message: ${err.message}`); console.error(`Failed to clear cloud data. Code: ${err.code}, message: ${err.message}`);
}); });
} catch (error) { } catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
......
...@@ -216,6 +216,8 @@ FA模型示例: ...@@ -216,6 +216,8 @@ FA模型示例:
```js ```js
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// 获取context // 获取context
let context = featureAbility.getContext() let context = featureAbility.getContext()
...@@ -234,6 +236,8 @@ Stage模型示例: ...@@ -234,6 +236,8 @@ Stage模型示例:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
var store;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) { relationalStore.deleteRdbStore(this.context, "RdbTest.db", function (err) {
...@@ -287,6 +291,8 @@ FA模型示例: ...@@ -287,6 +291,8 @@ FA模型示例:
```js ```js
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// 获取context // 获取context
let context = featureAbility.getContext(); let context = featureAbility.getContext();
...@@ -304,6 +310,8 @@ Stage模型示例: ...@@ -304,6 +310,8 @@ Stage模型示例:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
var store;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db"); let promise = relationalStore.deleteRdbStore(this.context, "RdbTest.db");
...@@ -353,6 +361,8 @@ FA模型示例: ...@@ -353,6 +361,8 @@ FA模型示例:
```js ```js
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// 获取context // 获取context
let context = featureAbility.getContext() let context = featureAbility.getContext()
const STORE_CONFIG = { const STORE_CONFIG = {
...@@ -375,6 +385,8 @@ Stage模型示例: ...@@ -375,6 +385,8 @@ Stage模型示例:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
var store;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
const STORE_CONFIG = { const STORE_CONFIG = {
...@@ -434,6 +446,8 @@ FA模型示例: ...@@ -434,6 +446,8 @@ FA模型示例:
```js ```js
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
var store;
// 获取context // 获取context
let context = featureAbility.getContext(); let context = featureAbility.getContext();
const STORE_CONFIG = { const STORE_CONFIG = {
...@@ -455,6 +469,8 @@ Stage模型示例: ...@@ -455,6 +469,8 @@ Stage模型示例:
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility' import UIAbility from '@ohos.app.ability.UIAbility'
var store;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
const STORE_CONFIG = { const STORE_CONFIG = {
...@@ -704,12 +720,12 @@ class EntryAbility extends UIAbility { ...@@ -704,12 +720,12 @@ class EntryAbility extends UIAbility {
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ---------------------------------------- | | ---------- | ------ | ---- | ---------------------------------------- |
| total | number | 是 | 表示数据库表中需要端云同步的总行数。 | | total | number | 是 | 表示数据库表中需要端云同步的总行数。 |
| success | number | 是 | 表示数据库表中端云同步成功的行数。 | | successful | number | 是 | 表示数据库表中端云同步成功的行数。 |
| failed | number | 是 | 表示数据库表中端云同步失败的行数。 | | failed | number | 是 | 表示数据库表中端云同步失败的行数。 |
| remained | number | 是 | 表示数据库表中端云同步剩余未执行的行数。 | | remained | number | 是 | 表示数据库表中端云同步剩余未执行的行数。 |
## TableDetails<sup>10+</sup> ## TableDetails<sup>10+</sup>
...@@ -2432,7 +2448,7 @@ store.query(predicates, function (err, resultSet) { ...@@ -2432,7 +2448,7 @@ store.query(predicates, function (err, resultSet) {
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2480,7 +2496,7 @@ store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, ...@@ -2480,7 +2496,7 @@ store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err,
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2530,7 +2546,7 @@ let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); ...@@ -2530,7 +2546,7 @@ let promise = store.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
promise.then((resultSet) => { promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2585,7 +2601,7 @@ store.query("EMPLOYEE", predicates, function (err, resultSet) { ...@@ -2585,7 +2601,7 @@ store.query("EMPLOYEE", predicates, function (err, resultSet) {
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2639,7 +2655,7 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu ...@@ -2639,7 +2655,7 @@ store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], fu
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2695,7 +2711,7 @@ let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY" ...@@ -2695,7 +2711,7 @@ let promise = store.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY"
promise.then((resultSet) => { promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2766,7 +2782,7 @@ store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALAR ...@@ -2766,7 +2782,7 @@ store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALAR
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2837,7 +2853,7 @@ let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME", ...@@ -2837,7 +2853,7 @@ let promise = store.remoteQuery(deviceId, "EMPLOYEE", predicates, ["ID", "NAME",
promise.then((resultSet) => { promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2884,7 +2900,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo ...@@ -2884,7 +2900,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2930,7 +2946,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['s ...@@ -2930,7 +2946,7 @@ store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['s
} }
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -2978,7 +2994,7 @@ let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK. ...@@ -2978,7 +2994,7 @@ let promise = store.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.
promise.then((resultSet) => { promise.then((resultSet) => {
console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`); console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。 // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while(resultSet.goToNextRow()) { while (resultSet.goToNextRow()) {
const id = resultSet.getLong(resultSet.getColumnIndex("ID")); const id = resultSet.getLong(resultSet.getColumnIndex("ID"));
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
...@@ -3533,7 +3549,48 @@ promise.then(() => { ...@@ -3533,7 +3549,48 @@ promise.then(() => {
### setDistributedTables<sup>10+</sup> ### setDistributedTables<sup>10+</sup>
setDistributedTables(tables: Array&lt;string&gt;, type: number, config: DistributedConfig, callback: AsyncCallback&lt;void&gt;): void setDistributedTables(tables: Array&lt;string&gt;, type: DistributedType, callback: AsyncCallback&lt;void&gt;): void
设置分布式数据库表,使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------- | ---- | ---------------------------- |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式数据库表表名。 |
| type | [DistributedType](#distributedtype10) | 是 | 表的分布式类型。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**错误码:**
以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)
| **错误码ID** | **错误信息** |
| ------------ | ------------ |
| 14800000 | Inner error. |
| 14800051 |The type of the distributed table does not match.|
**示例:**
```js
store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, function (err) {
if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return;
}
console.info(`SetDistributedTables successfully.`);
})
```
###
### setDistributedTables<sup>10+</sup>
setDistributedTables(tables: Array&lt;string&gt;, type: DistributedType, config: DistributedConfig, callback: AsyncCallback&lt;void&gt;): void
设置分布式数据库表,使用callback异步回调。 设置分布式数据库表,使用callback异步回调。
...@@ -3546,16 +3603,25 @@ setDistributedTables(tables: Array&lt;string&gt;, type: number, config: Distribu ...@@ -3546,16 +3603,25 @@ setDistributedTables(tables: Array&lt;string&gt;, type: number, config: Distribu
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | --- | --------------- | | -------- | ----------------------------------- | --- | --------------- |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式数据库表表名。 | | tables | Array&lt;string&gt; | 是 | 要设置的分布式数据库表表名。 |
| type | number | 是 | 表的分布式类型。目前支持的入参值为: relationalStore.DistributedType.DISTRIBUTED_DEVICE、relationalStore.DistributedType.DISTRIBUTED_CLOUD。<br> 当type为relationalStore.DistributedType.DISTRIBUTED_DEVICE时,表示表在不同设备之间分布式。<br> 当type为relationalStore.DistributedType.DISTRIBUTED_CLOUD时,表示表在设备和云端之间分布式。 | | type | [DistributedType](#distributedtype10) | 是 | 表的分布式类型。 |
| config | [DistributedConfig](#distributedconfig10) | 是 | 表的分布式配置信息。 | | config | [DistributedConfig](#distributedconfig10) | 是 | 表的分布式配置信息。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**错误码:**
以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)
| **错误码ID** | **错误信息** |
| ------------ | ------------------------------------------------- |
| 14800000 | Inner error. |
| 14800051 | The type of the distributed table does not match. |
**示例:** **示例:**
```js ```js
let config = new relationalStore.DistributedConfig(); store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
config.autoSync = true; autoSync: true
store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config, function (err) { }, function (err) {
if (err) { if (err) {
console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`); console.error(`SetDistributedTables failed, code is ${err.code},message is ${err.message}`);
return; return;
...@@ -3566,7 +3632,7 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB ...@@ -3566,7 +3632,7 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB
### setDistributedTables<sup>10+</sup> ### setDistributedTables<sup>10+</sup>
setDistributedTables(tables: Array&lt;string>, type?: number, config?: DistributedConfig): Promise&lt;void> setDistributedTables(tables: Array&lt;string>, type?: DistributedType, config?: DistributedConfig): Promise&lt;void>
设置分布式数据库表,使用Promise异步回调。 设置分布式数据库表,使用Promise异步回调。
...@@ -3578,8 +3644,8 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB ...@@ -3578,8 +3644,8 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ | | ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式数据库表表名。 | | tables | Array&lt;string&gt; | 是 | 要设置的分布式数据库表表名。 |
| type | number | 否 | 表的分布式类型。默认值是relationalStore.DistributedType.DISTRIBUTED_DEVICE。<br> 目前支持的入参值为: relationalStore.DistributedType.DISTRIBUTED_DEVICE、relationalStore.DistributedType.DISTRIBUTED_CLOUD。<br/> 当type为relationalStore.DistributedType.DISTRIBUTED_DEVICE时,表示表在不同设备之间分布式。<br/> 当type为relationalStore.DistributedType.DISTRIBUTED_CLOUD时,表示表在设备和云端之间分布式。 | | type | [DistributedType](#distributedtype10) | 否 | 表的分布式类型。默认值是relationalStore.DistributedType.DISTRIBUTED_DEVICE。 |
| config | [DistributedConfig](#distributedconfig10) | 否 | 表的分布式配置信息。不传入时默认autoSync为false,即只支持手动同步。 | | config | [DistributedConfig](#distributedconfig10) | 否 | 表的分布式配置信息。不传入时默认autoSync为false,即只支持手动同步。 |
**返回值** **返回值**
...@@ -3588,12 +3654,21 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB ...@@ -3588,12 +3654,21 @@ store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIB
| ------------------- | ------------------------- | | ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 | | Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)
| **错误码ID** | **错误信息** |
| ------------ | ------------------------------------------------- |
| 14800000 | Inner error. |
| 14800051 | The type of the distributed table does not match. |
**示例:** **示例:**
```js ```js
let config = new relationalStore.DistributedConfig(); let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, {
config.autoSync = true; autoSync: true
let promise = store.setDistributedTables(["EMPLOYEE"], relationalStore.DistributedType.DISTRIBUTED_CLOUD, config); });
promise.then(() => { promise.then(() => {
console.info(`SetDistributedTables successfully.`); console.info(`SetDistributedTables successfully.`);
}).catch((err) => { }).catch((err) => {
...@@ -3860,7 +3935,7 @@ cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;, callback: A ...@@ -3860,7 +3935,7 @@ cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;, callback: A
**示例:** **示例:**
```js ```js
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) { store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
console.info(`Progess: ${progressDetails}`); console.info(`Progess: ${progressDetails}`);
}, function (err) { }, function (err) {
if (err) { if (err) {
...@@ -3901,7 +3976,7 @@ function progress(progressDetail) { ...@@ -3901,7 +3976,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`); console.info(`progress: ${progressDetail}`);
} }
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => { store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
console.info('Cloud sync succeeded'); console.info('Cloud sync succeeded');
}).catch((err) => { }).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
...@@ -3931,7 +4006,7 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetail ...@@ -3931,7 +4006,7 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetail
```js ```js
const tables = ["table1", "table2"]; const tables = ["table1", "table2"];
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) { store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
console.info(`Progess: ${progressDetails}`); console.info(`Progess: ${progressDetails}`);
}, function (err) { }, function (err) {
if (err) { if (err) {
...@@ -3974,7 +4049,7 @@ function progress(progressDetail) { ...@@ -3974,7 +4049,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`); console.info(`progress: ${progressDetail}`);
} }
relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => { store.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
console.info('Cloud sync succeeded'); console.info('Cloud sync succeeded');
}).catch((err) => { }).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
......
...@@ -48,10 +48,10 @@ createData(mimeType: string, value: ValueType): PasteData ...@@ -48,10 +48,10 @@ createData(mimeType: string, value: ValueType): PasteData
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |--------------------------------------------------------------------------------------------------------|
| mimeType | string | 是 | 自定义数据的MIME类型。 | | mimeType | string | 是 | 剪贴板数据对应的MIME类型,可以是[常量](#常量)中已定义的类型,包括HTML类型,WANT类型,纯文本类型,URI类型,PIXELMAP类型;也可以是自定义的MIME类型,开发者可自定义此参数值。 |
| value | [ValueType](#valuetype9) | 是 | 自定义数据内容。 | | value | [ValueType](#valuetype9) | 是 | 自定义数据内容。 |
**返回值:** **返回值:**
...@@ -59,13 +59,21 @@ createData(mimeType: string, value: ValueType): PasteData ...@@ -59,13 +59,21 @@ createData(mimeType: string, value: ValueType): PasteData
| -------- | -------- | | -------- | -------- |
| [PasteData](#pastedata) | 剪贴板内容对象。 | | [PasteData](#pastedata) | 剪贴板内容对象。 |
**示例:** **示例1:**
```js ```js
let dataXml = new ArrayBuffer(256); let dataXml = new ArrayBuffer(256);
let pasteData = pasteboard.createData('app/xml', dataXml); let pasteData = pasteboard.createData('app/xml', dataXml);
``` ```
**示例2:**
```js
let dataText = 'hello';
let pasteData = pasteboard.createData(pasteboard.MIMETYPE_TEXT_PLAIN, dataText);
```
## pasteboard.createRecord<sup>9+</sup> ## pasteboard.createRecord<sup>9+</sup>
createRecord(mimeType: string, value: ValueType):PasteDataRecord; createRecord(mimeType: string, value: ValueType):PasteDataRecord;
...@@ -76,10 +84,10 @@ createRecord(mimeType: string, value: ValueType):PasteDataRecord; ...@@ -76,10 +84,10 @@ createRecord(mimeType: string, value: ValueType):PasteDataRecord;
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- |-------------------|
| mimeType | string | 是 | 自定义数据的MIME类型。 | | mimeType | string | 是 | 剪贴板数据对应的MIME类型,可以是[常量](#常量)中已定义的类型,包括HTML类型,WANT类型,纯文本类型,URI类型,PIXELMAP类型;也可以是自定义的MIME类型,开发者可自定义此参数值。 |
| value | [ValueType](#valuetype9) | 是 | 自定义数据内容。 | | value | [ValueType](#valuetype9) | 是 | 自定义数据内容。 |
**返回值:** **返回值:**
...@@ -87,13 +95,20 @@ createRecord(mimeType: string, value: ValueType):PasteDataRecord; ...@@ -87,13 +95,20 @@ createRecord(mimeType: string, value: ValueType):PasteDataRecord;
| -------- | -------- | | -------- | -------- |
| [PasteDataRecord](#pastedatarecord7) | 一条新建的自定义数据内容条目。 | | [PasteDataRecord](#pastedatarecord7) | 一条新建的自定义数据内容条目。 |
**示例:** **示例1:**
```js ```js
let dataXml = new ArrayBuffer(256); let dataXml = new ArrayBuffer(256);
let pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); let pasteDataRecord = pasteboard.createRecord('app/xml', dataXml);
``` ```
**示例2:**
```js
let dataUri = 'dataability:///com.example.myapplication1/user.txt';
let record = pasteboard.createRecord(pasteboard.MIMETYPE_TEXT_URI, dataUri);
```
## pasteboard.getSystemPasteboard ## pasteboard.getSystemPasteboard
getSystemPasteboard(): SystemPasteboard getSystemPasteboard(): SystemPasteboard
......
...@@ -16,6 +16,302 @@ ...@@ -16,6 +16,302 @@
```ts ```ts
import taskpool from '@ohos.taskpool'; import taskpool from '@ohos.taskpool';
``` ```
## taskpool.execute
execute(func: Function, ...args: unknown[]): Promise\<unknown>
将待执行的函数放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式不可取消任务。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
| func | Function | 是 | 执行的逻辑需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| args | unknown[] | 否 | 执行逻辑的函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。默认值为undefined。 |
**返回值:**
| 类型 | 说明 |
| ----------------- | ------------------------------------ |
| Promise\<unknown> | execute是异步方法,返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | -------------------------------------------- |
| 10200003 | Worker initialization failure. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
taskpool.execute(printArgs, 100).then((value) => { // 100: test number
console.log("taskpool result: " + value);
});
```
## taskpool.execute
execute(task: Task, priority?: Priority): Promise\<unknown>
将创建好的任务放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式可尝试调用cancel进行任务取消。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task | [Task](#task) | 是 | 需要在任务池中执行的任务。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务的优先级,该参数默认值为taskpool.Priority.MEDIUM。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------- |
| Promise\<unknown> | 返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------- |
| 10200003 | Worker initialization failure. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
let task = new taskpool.Task(printArgs, 100); // 100: test number
taskpool.execute(task).then((value) => {
console.log("taskpool result: " + value);
});
```
## taskpool.execute<sup>10+</sup>
execute(group: TaskGroup, priority?: Priority): Promise<unknown[]>
将创建好的任务组放入taskpool内部任务队列等待,等待分发到工作线程执行。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | --------------------------- | ---- | -------------------------------------------------------------- |
| group | [TaskGroup](#taskgroup) | 是 | 需要在任务池中执行的任务组。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务组的优先级,该参数默认值为taskpool.Priority.MEDIUM。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------------------------- |
| Promise\<unknown[]> | execute是异步方法,返回Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------- |
| 10200006 | An exception occurred during serialization. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
let taskGroup1 = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
taskGroup1.addTask(printArgs, 20); // 20: test number
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
```
## taskpool.cancel
cancel(task: Task): void
取消任务池中的任务。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------- | ---- | -------------------- |
| task | [Task](#task) | 是 | 需要取消执行的任务。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | -------------------------------------------- |
| 10200015 | The task does not exist when it is canceled. |
| 10200016 | The task is executing when it is canceled. |
从API version10开始,此接口调用时不再涉及上报错误码10200016。
**正在执行的任务取消示例:**
```ts
@Concurrent
function inspectStatus(arg) {
// 第一时间检查取消并回复
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t = Date.now();
while (Date.now() - t < 2000) {
continue;
}
// 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number
let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
console.log("taskpool test occur error: " + err);
});
let res2 = taskpool.execute(task2);
let res3 = taskpool.execute(task3);
let res4 = taskpool.execute(task4);
let res5 = taskpool.execute(task5);
let res6 = taskpool.execute(task6);
// 1s后取消task
setTimeout(()=>{
taskpool.cancel(task1);}, 1000);
```
## taskpool.cancel<sup>10+</sup>
cancel(group: TaskGroup): void
取消任务池中的任务组。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------- | ---- | -------------------- |
| group | [TaskGroup](#taskgroup) | 是 | 需要取消执行的任务组。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------- |
| 10200018 | The task group does not exist when it is canceled. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
let t = Date.now();
while (Date.now() - t < 2000) {
continue;
}
console.log("printArgs: " + args);
return args;
}
let taskGroup1 = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2 = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res)=>{
console.info("taskGroup1 res is:" + res)
});
taskpool.execute(taskGroup2).then((res)=>{
console.info("taskGroup2 res is:" + res)
});
setTimeout(()=>{
try {
taskpool.cancel(taskGroup2);
} catch (e) {
console.log("taskGroup.cancel occur error:" + e);
}
}, 1000);
```
## taskpool.getTaskPoolInfo<sup>10+</sup>
getTaskPoolInfo(): TaskPoolInfo
获取任务池内部信息。
**系统能力:** SystemCapability.Utils.Lang
**返回值:**
| 类型 | 说明 |
| ----------------------------------- | ------------------ |
| [TaskPoolInfo](#taskpoolinfo10) | 任务池的内部信息。 |
**示例:**
```ts
let taskpoolInfo:TaskPoolInfo = taskpool.getTaskPoolInfo();
```
## Priority ## Priority
...@@ -217,175 +513,50 @@ console.info("testTransfer view1 byteLength: " + view1.byteLength); ...@@ -217,175 +513,50 @@ console.info("testTransfer view1 byteLength: " + view1.byteLength);
**系统能力:** SystemCapability.Utils.Lang **系统能力:** SystemCapability.Utils.Lang
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- | | --------- | --------- | ---- | ---- | ------------------------------------------------------------------------- |
| function | Function | 是 | 是 | 创建任务时需要传入的函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 | | function | Function | 是 | 是 | 创建任务时需要传入的函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| arguments | unknown[] | 是 | 是 | 创建任务传入函数所需的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。 | | arguments | unknown[] | 是 | 是 | 创建任务传入函数所需的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。 |
## TaskGroup<sup>10+</sup>
表示任务组。使用以下方法前,需要先构造TaskGroup。
### constructor<sup>10+</sup>
constructor()
TaskGroup的构造函数。
**系统能力:** SystemCapability.Utils.Lang
**示例:**
```ts
let taskGroup = new taskpool.TaskGroup();
```
### addTask<sup>10+</sup>
addTask(func: Function, ...args: unknown[]): void
将待执行的函数添加到任务组中。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
| func | Function | 是 | 任务执行需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| args | unknown[] | 否 | 任务执行函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。默认值为undefined。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
let taskGroup = new taskpool.TaskGroup();
taskGroup.addTask(printArgs, 100); // 100: test number
```
### addTask<sup>10+</sup>
addTask(task: Task): void
将创建好的任务添加到任务组中。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------------------------------------- |
| task | [Task](#task) | 是 | 需要添加到任务组中的任务。 |
**错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 |
| -------- | --------------------------------------- |
| 10200014 | The function is not mark as concurrent. |
**示例:**
```ts
@Concurrent
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
let taskGroup = new taskpool.TaskGroup();
let task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup.addTask(task);
```
## taskpool.execute
execute(func: Function, ...args: unknown[]): Promise\<unknown>
将待执行的函数放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式不可取消任务。
**系统能力:** SystemCapability.Utils.Lang
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | --------- | ---- | ---------------------------------------------------------------------- |
| func | Function | 是 | 执行的逻辑需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| args | unknown[] | 否 | 执行逻辑的函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。默认值为undefined。 |
**返回值:** ## TaskGroup<sup>10+</sup>
表示任务组。使用以下方法前,需要先构造TaskGroup。
| 类型 | 说明 | ### constructor<sup>10+</sup>
| ----------------- | ------------------------------------ |
| Promise\<unknown> | execute是异步方法,返回Promise对象。 |
**错误码:** constructor()
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md) TaskGroup的构造函数
| 错误码ID | 错误信息 | **系统能力:** SystemCapability.Utils.Lang
| -------- | -------------------------------------------- |
| 10200003 | Worker initialization failure. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:** **示例:**
```ts ```ts
@Concurrent let taskGroup = new taskpool.TaskGroup();
function printArgs(args) {
console.log("printArgs: " + args);
return args;
}
taskpool.execute(printArgs, 100).then((value) => { // 100: test number
console.log("taskpool result: " + value);
});
``` ```
## taskpool.execute ### addTask<sup>10+</sup>
execute(task: Task, priority?: Priority): Promise\<unknown> addTask(func: Function, ...args: unknown[]): void
创建好的任务放入taskpool内部任务队列等待,等待分发到工作线程执行。当前执行模式可尝试调用cancel进行任务取消 待执行的函数添加到任务组中
**系统能力:** SystemCapability.Utils.Lang **系统能力:** SystemCapability.Utils.Lang
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---------------------------------------- | | ------ | --------- | ---- | ---------------------------------------------------------------------- |
| task | [Task](#task) | 是 | 需要在任务池中执行的任务。 | | func | Function | 是 | 任务执行需要传入函数,支持的函数返回值类型请查[序列化支持类型](#序列化支持类型)。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务的优先级,该参数默认值为taskpool.Priority.MEDIUM。 | | args | unknown[] | 否 | 任务执行函数所需要的参数,支持的参数类型请查[序列化支持类型](#序列化支持类型)。默认值为undefined。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------- |
| Promise\<unknown> | 返回Promise对象。 |
**错误码:** **错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md) 以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ------------------------------------------- | | -------- | --------------------------------------- |
| 10200003 | Worker initialization failure. | | 10200014 | The function is not mark as concurrent. |
| 10200006 | An exception occurred during serialization. |
| 10200014 | The function is not mark as concurrent. |
**示例:** **示例:**
...@@ -396,40 +567,31 @@ function printArgs(args) { ...@@ -396,40 +567,31 @@ function printArgs(args) {
return args; return args;
} }
let task = new taskpool.Task(printArgs, 100); // 100: test number let taskGroup = new taskpool.TaskGroup();
taskpool.execute(task).then((value) => { taskGroup.addTask(printArgs, 100); // 100: test number
console.log("taskpool result: " + value);
});
``` ```
## taskpool.execute<sup>10+</sup> ### addTask<sup>10+</sup>
execute(group: TaskGroup, priority?: Priority): Promise<unknown[]> addTask(task: Task): void
将创建好的任务组放入taskpool内部任务队列等待,等待分发到工作线程执行 将创建好的任务添加到任务组中
**系统能力:** SystemCapability.Utils.Lang **系统能力:** SystemCapability.Utils.Lang
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------- | --------------------------- | ---- | -------------------------------------------------------------- | | -------- | --------------------- | ---- | ---------------------------------------- |
| group | [TaskGroup](#taskgroup) | 是 | 需要在任务池中执行的任务组。 | | task | [Task](#task) | 是 | 需要添加到任务组中的任务。 |
| priority | [Priority](#priority) | 否 | 等待执行的任务组的优先级,该参数默认值为taskpool.Priority.MEDIUM。 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------------------------- |
| Promise\<unknown[]> | execute是异步方法,返回Promise对象。 |
**错误码:** **错误码:**
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md) 以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md)
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ------------------------------------------- | | -------- | --------------------------------------- |
| 10200006 | An exception occurred during serialization. | | 10200014 | The function is not mark as concurrent. |
**示例:** **示例:**
...@@ -440,152 +602,72 @@ function printArgs(args) { ...@@ -440,152 +602,72 @@ function printArgs(args) {
return args; return args;
} }
let taskGroup1 = new taskpool.TaskGroup(); let taskGroup = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number let task = new taskpool.Task(printArgs, 200); // 200: test number
taskGroup1.addTask(printArgs, 20); // 20: test number taskGroup.addTask(task);
taskGroup1.addTask(printArgs, 30); // 30: test number
let taskGroup2 = new taskpool.TaskGroup();
let task1 = new taskpool.Task(printArgs, 100); // 100: test number
let task2 = new taskpool.Task(printArgs, 200); // 200: test number
let task3 = new taskpool.Task(printArgs, 300); // 300: test number
taskGroup2.addTask(task1);
taskGroup2.addTask(task2);
taskGroup2.addTask(task3);
taskpool.execute(taskGroup1).then((res) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
taskpool.execute(taskGroup2).then((res) => {
console.info("taskpool execute res is:" + res);
}).catch((e) => {
console.error("taskpool execute error is:" + e);
});
``` ```
## taskpool.cancel
cancel(task: Task): void ## State<sup>10+</sup>
取消任务池中的任务 表示任务(Task)状态的枚举
**系统能力:** SystemCapability.Utils.Lang **系统能力:** SystemCapability.Utils.Lang
**参数:** | 名称 | 值 | 说明 |
| --------- | -------- | ------------- |
| WAITING | 1 | 任务正在等待。 |
| RUNNING | 2 | 任务正在执行。 |
| CANCELED | 3 | 任务已被取消。 |
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------- | ---- | -------------------- |
| task | [Task](#task) | 是 | 需要取消执行的任务。 |
**错误码:** ## TaskInfo<sup>10+</sup>
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md) 任务的内部信息
| 错误码ID | 错误信息 | **系统能力:** SystemCapability.Utils.Lang
| -------- | -------------------------------------------- |
| 10200015 | The task does not exist when it is canceled. |
| 10200016 | The task is executing when it is canceled. |
从API version10开始,此接口调用时不再涉及上报错误码10200016。 ### 属性
**正在执行的任务取消示例:** **系统能力:** SystemCapability.Utils.Lang
```ts | 名称 | 类型 | 可读 | 可写 | 说明 |
@Concurrent | -------- | ------------------ | ---- | ---- | ------------------------------------------------------------- |
function inspectStatus(arg) { | taskId | number | 是 | 否 | 任务的ID。 |
// 第一时间检查取消并回复 | state | [State](#state10) | 是 | 否 | 任务的状态。 |
if (taskpool.Task.isCanceled()) { | duration | number | 是 | 否 | 任务执行至当前所用的时间,单位为ms。当返回为0时,表示任务未执行;返回为空时,表示没有任务执行 |
console.log("task has been canceled before 2s sleep.");
return arg + 2;
}
// 2s sleep
let t = Date.now();
while (Date.now() - t < 2000) {
continue;
}
// 第二次检查取消并作出响应
if (taskpool.Task.isCanceled()) {
console.log("task has been canceled after 2s sleep.");
return arg + 3;
}
return arg + 1;
}
let task1 = new taskpool.Task(inspectStatus, 100); // 100: test number ## ThreadInfo<sup>10+</sup>
let task2 = new taskpool.Task(inspectStatus, 200); // 200: test number
let task3 = new taskpool.Task(inspectStatus, 300); // 300: test number
let task4 = new taskpool.Task(inspectStatus, 400); // 400: test number
let task5 = new taskpool.Task(inspectStatus, 500); // 500: test number
let task6 = new taskpool.Task(inspectStatus, 600); // 600: test number
taskpool.execute(task1).then((res)=>{
console.log("taskpool test result: " + res);
}).catch((err) => {
console.log("taskpool test occur error: " + err);
});
let res2 = taskpool.execute(task2);
let res3 = taskpool.execute(task3);
let res4 = taskpool.execute(task4);
let res5 = taskpool.execute(task5);
let res6 = taskpool.execute(task6);
// 1s后取消task
setTimeout(()=>{
taskpool.cancel(task1);}, 1000);
```
## taskpool.cancel<sup>10+</sup> 工作线程的内部信息。
cancel(group: TaskGroup): void **系统能力:** SystemCapability.Utils.Lang
取消任务池中的任务组。 ### 属性
**系统能力:** SystemCapability.Utils.Lang **系统能力:** SystemCapability.Utils.Lang
**参数:** | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | ---------------------- | ---- | ---- | -------------------------------------------------------- |
| tid | number | 是 | 否 | 工作线程的标识符。返回为空时,代表没有任务执行。 |
| taskIds | number[] | 是 | 否 | 在当前线程上运行的任务id列表。返回为空时,代表没有任务执行。 |
| priority | [Priority](#priority) | 是 | 否 | 当前线程的优先级。返回为空时,代表没有任务执行。 |
| 参数名 | 类型 | 必填 | 说明 | ## TaskPoolInfo<sup>10+</sup>
| ------- | ----------------------- | ---- | -------------------- |
| group | [TaskGroup](#taskgroup) | 是 | 需要取消执行的任务组。 |
**错误码:** 任务池的内部信息。
以下错误码的详细介绍请参见[语言基础类库错误码](../errorcodes/errorcode-utils.md) **系统能力:** SystemCapability.Utils.Lang
| 错误码ID | 错误信息 | ### 属性
| -------- | ------------------------------------------------------- |
| 10200018 | The task group does not exist when it is canceled. |
**示例:** **系统能力:** SystemCapability.Utils.Lang
```ts | 名称 | 类型 | 可读 | 可写 | 说明 |
@Concurrent | ------------- | -------------------------------- | ---- | ---- | -------------------- |
function printArgs(args) { | threadInfos | [ThreadInfo[]](#threadinfo10) | 是 | 否 | 工作线程的内部信息。 |
let t = Date.now(); | taskInfos | [TaskInfo[]](#taskinfo10) | 是 | 否 | 任务的内部信息。 |
while (Date.now() - t < 2000) {
continue;
}
console.log("printArgs: " + args);
return args;
}
let taskGroup1 = new taskpool.TaskGroup();
taskGroup1.addTask(printArgs, 10); // 10: test number
let taskGroup2 = new taskpool.TaskGroup();
taskGroup2.addTask(printArgs, 100); // 100: test number
taskpool.execute(taskGroup1).then((res)=>{
console.info("taskGroup1 res is:" + res)
});
taskpool.execute(taskGroup2).then((res)=>{
console.info("taskGroup2 res is:" + res)
});
setTimeout(()=>{
try {
taskpool.cancel(taskGroup2);
} catch (e) {
console.log("taskGroup.cancel occur error:" + e);
}
}, 1000);
```
## 其他说明 ## 其他说明
...@@ -832,4 +914,65 @@ async function taskpoolGroupCancelTest() { ...@@ -832,4 +914,65 @@ async function taskpoolGroupCancelTest() {
} }
taskpoolGroupCancelTest() taskpoolGroupCancelTest()
```
**示例八**
```ts
// 分别创建执行100个高、中、低优先级的任务,查看其各项信息
@Concurrent
function delay() {
let start = new Date().getTime();
while (new Date().getTime() - start < 500) {
continue;
}
}
let highCount = 0;
let mediumCount = 0;
let lowCount = 0;
let allCount = 100;
for (let i = 0; i < allCount; i++) {
let task1 = new taskpool.Task(delay);
let task2 = new taskpool.Task(delay);
let task3 = new taskpool.Task(delay);
taskpool.execute(task1, taskpool.Priority.LOW).then(() => {
lowCount++;
}).catch((e) => {
console.error("low task error: " + e);
})
taskpool.execute(task2, taskpool.Priority.MEDIUM).then(() => {
mediumCount++;
}).catch((e) => {
console.error("medium task error: " + e);
})
taskpool.execute(task3, taskpool.Priority.HIGH).then(() => {
highCount++;
}).catch((e) => {
console.error("high task error: " + e);
})
}
let start = new Date().getTime();
while (new Date().getTime() - start < 1000) {
continue;
}
let taskpoolInfo = taskpool.getTaskPoolInfo();
let tid = 0;
let taskIds = [];
let priority = 0;
let taskId = 0;
let state = 0;
let duration = 0;
for(let threadInfo of taskpoolInfo.threadInfos) {
tid = threadInfo.tid;
taskIds.length = threadInfo.taskIds.length;
priority = threadInfo.priority;
console.info("taskpool---tid is:" + tid + ", taskIds is:" + taskIds + ", priority is:" + priority);
}
for(let taskInfo of taskpoolInfo.taskInfos) {
taskId = taskInfo.taskId;
state = taskInfo.state;
duration = taskInfo.duration;
console.info("taskpool---taskId is:" + taskId + ", state is:" + state + ", duration is:" + duration);
}
``` ```
\ No newline at end of file
...@@ -4324,6 +4324,10 @@ export default class EntryAbility extends UIAbility { ...@@ -4324,6 +4324,10 @@ export default class EntryAbility extends UIAbility {
通过WebCookie可以控制Web组件中的cookie的各种行为,其中每个应用中的所有web组件共享一个WebCookieManager实例。 通过WebCookie可以控制Web组件中的cookie的各种行为,其中每个应用中的所有web组件共享一个WebCookieManager实例。
> **说明:**
>
> 目前调用WebCookieManager下的方法,都需要先加载Web组件。
### getCookie ### getCookie
static getCookie(url: string): string static getCookie(url: string): string
...@@ -4785,6 +4789,10 @@ struct WebComponent { ...@@ -4785,6 +4789,10 @@ struct WebComponent {
通过WebStorage可管理Web SQL数据库接口和HTML5 Web存储接口,每个应用中的所有Web组件共享一个WebStorage。 通过WebStorage可管理Web SQL数据库接口和HTML5 Web存储接口,每个应用中的所有Web组件共享一个WebStorage。
> **说明:**
>
> 目前调用WebStorage下的方法,都需要先加载Web组件。
### deleteOrigin ### deleteOrigin
static deleteOrigin(origin : string): void static deleteOrigin(origin : string): void
...@@ -5245,6 +5253,10 @@ struct WebComponent { ...@@ -5245,6 +5253,10 @@ struct WebComponent {
web组件数据库管理对象。 web组件数据库管理对象。
> **说明:**
>
> 目前调用WebDataBase下的方法,都需要先加载Web组件。
### getHttpAuthCredentials ### getHttpAuthCredentials
static getHttpAuthCredentials(host: string, realm: string): Array\<string> static getHttpAuthCredentials(host: string, realm: string): Array\<string>
...@@ -5423,6 +5435,10 @@ struct WebComponent { ...@@ -5423,6 +5435,10 @@ struct WebComponent {
web组件地理位置权限管理对象。 web组件地理位置权限管理对象。
> **说明:**
>
> 目前调用GeolocationPermissions下的方法,都需要先加载Web组件。
### 需要权限 ### 需要权限
访问地理位置时需添加权限:ohos.permission.LOCATION、ohos.permission.APPROXIMATELY_LOCATION、ohos.permission.LOCATION_IN_BACKGROUND,具体权限说明请参考[位置服务](./js-apis-geolocation.md) 访问地理位置时需添加权限:ohos.permission.LOCATION、ohos.permission.APPROXIMATELY_LOCATION、ohos.permission.LOCATION_IN_BACKGROUND,具体权限说明请参考[位置服务](./js-apis-geolocation.md)
......
...@@ -165,7 +165,7 @@ ...@@ -165,7 +165,7 @@
strokeColor: '#0081ff', strokeColor: '#0081ff',
fillColor: '#cce5ff', fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716], data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true, gradient: false,
} }
], ],
lineOps: { lineOps: {
......
...@@ -204,4 +204,4 @@ export default { ...@@ -204,4 +204,4 @@ export default {
}; };
``` ```
![image-animator](figures/image-animator.gif) ![image-animator](figures/image-animator-lite.gif)
...@@ -71,4 +71,4 @@ ...@@ -71,4 +71,4 @@
} }
``` ```
![image](figures/image.png) ![image](figures/image-lite.png)
\ No newline at end of file \ No newline at end of file
...@@ -115,4 +115,4 @@ export default { ...@@ -115,4 +115,4 @@ export default {
} }
``` ```
![marquee](figures/marquee.gif) ![marquee](figures/marquee-lite.gif)
\ No newline at end of file \ No newline at end of file
...@@ -142,4 +142,4 @@ export default { ...@@ -142,4 +142,4 @@ export default {
} }
``` ```
![picker-view](figures/picker-view.png) ![picker-view](figures/picker-view-lite.png)
\ No newline at end of file \ No newline at end of file
...@@ -122,4 +122,4 @@ export default { ...@@ -122,4 +122,4 @@ export default {
} }
``` ```
![progress](figures/progress.png) ![progress](figures/progress-lite.png)
\ No newline at end of file \ No newline at end of file
...@@ -63,10 +63,10 @@ ...@@ -63,10 +63,10 @@
```html ```html
<!-- xxx.hml --> <!-- xxx.hml -->
<div class="container"> <div class="container">
<qrcode value="{{qr_value}}" class="qrCode" style="color: {{qr_color}};background-color: {{qr_bcol}};"></qrcode> <qrcode value="{{qr_value}}" class="qrCode" style="color: {{qr_col}};background-color: {{qr_bcol}};"></qrcode>
<input type="button" onclick="changeColor" class="button">Color</input> <input type="button" onclick="changeColor" class="button">Color</input>
<input type="button" onclick="changeBackgroundColor" class="button">BackgroundColor</input> <input type="button" onclick="changeBackgroundColor" class="button">BackgroundColor</input>
<input type="button" onclick="changeColor" class="button">Value</input> <input type="button" onclick="changeValue" class="button">Value</input>
</div> </div>
``` ```
...@@ -93,33 +93,33 @@ ...@@ -93,33 +93,33 @@
```javascript ```javascript
// xxx.js // xxx.js
export default { export default {
data: { data: {
qr_col: '#87ceeb', qr_col: '#87ceeb',
qr_bcol: '#f0ffff', qr_bcol: '#f0ffff',
qr_value: 'value' qr_value: 'value'
}, },
changeColor() { changeColor() {
if (this.qr_col == '#87ceeb') { if (this.qr_col == '#87ceeb') {
this.qr_col = '#fa8072'; this.qr_col = '#fa8072';
} else { } else {
this.qr_col = '#87ceeb'; this.qr_col = '#87ceeb';
}
},
changeBackgroundColor() {
if (this.qr_bcol == '#f0ffff') {
this.qr_bcol = '#ffffe0';
} else {
this.qr_bcol = '#f0ffff';
}
},
changeValue() {
if (this.qr_value == 'value') {
this.qr_value = 'change';
} else {
this.qr_value = 'value';
}
} }
},
changeBackgroundColor() {
if (this.qr_bcol == '#f0ffff') {
this.qr_bcol = '#ffffe0';
} else {
this.qr_bcol = '#f0ffff';
}
},
changeValue() {
if (this.qr_value == 'value') {
this.qr_value = 'change';
} else {
this.qr_value = 'value';
}
}
} }
``` ```
![qrcode](figures/qrcode.gif) ![qrcode](figures/qrcode-lite.gif)
\ No newline at end of file \ No newline at end of file
...@@ -99,4 +99,4 @@ export default { ...@@ -99,4 +99,4 @@ export default {
} }
``` ```
![slider](figures/slider.png) ![slider](figures/slider-lite.png)
\ No newline at end of file \ No newline at end of file
...@@ -96,4 +96,4 @@ export default { ...@@ -96,4 +96,4 @@ export default {
} }
``` ```
![switch](figures/switch.gif) ![switch](figures/switch-lite.gif)
\ No newline at end of file \ No newline at end of file
...@@ -96,4 +96,4 @@ export default { ...@@ -96,4 +96,4 @@ export default {
} }
``` ```
![text](figures/text.png) ![text](figures/text-lite.png)
\ No newline at end of file \ No newline at end of file
...@@ -120,4 +120,4 @@ export default { ...@@ -120,4 +120,4 @@ export default {
} }
``` ```
![list](figures/list.png) ![list](figures/list-lite.png)
...@@ -109,4 +109,4 @@ export default { ...@@ -109,4 +109,4 @@ export default {
} }
``` ```
![swiper](figures/swiper.gif) ![swiper](figures/swiper-lite.gif)
...@@ -45,8 +45,8 @@ Grid(scroller?: Scroller) ...@@ -45,8 +45,8 @@ Grid(scroller?: Scroller)
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| columnsTemplate | string | 设置当前网格布局列的数量,不设置时默认1列。<br/>例如,&nbsp;'1fr&nbsp;1fr&nbsp;2fr'&nbsp;是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。<br/>‘repeat(auto-fit, 90px)’是设置最小列宽值为90,自动计算列数和实际列宽。<br/>**说明:** <br/>设置为'0fr'时,该列的列宽为0,不显示GridItem。设置为其他非法值时,GridItem显示为固定1列。 | | columnsTemplate | string | 设置当前网格布局列的数量或最小列宽值,不设置时默认1列。<br/>例如,&nbsp;'1fr&nbsp;1fr&nbsp;2fr'&nbsp;是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。<br/>‘repeat(auto-fit, 90px)’是设置最小列宽值为90,自动计算列数和实际列宽。<br/>**说明:** <br/>设置为'0fr'时,该列的列宽为0,不显示GridItem。设置为其他非法值时,GridItem显示为固定1列。 |
| rowsTemplate | string | 设置当前网格布局行的数量,不设置时默认1行。<br/>例如,&nbsp;'1fr&nbsp;1fr&nbsp;2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。<br/>‘repeat(auto-fit, 90px)’是设置最小行高值为90,自动计算行数和实际行高。<br/>**说明:** <br/>设置为'0fr',则这一行的行宽为0,这一行GridItem不显示。设置为其他非法值,按固定1行处理。 | | rowsTemplate | string | 设置当前网格布局行的数量或最小行高值,不设置时默认1行。<br/>例如,&nbsp;'1fr&nbsp;1fr&nbsp;2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。<br/>‘repeat(auto-fit, 90px)’是设置最小行高值为90,自动计算行数和实际行高。<br/>**说明:** <br/>设置为'0fr',则这一行的行宽为0,这一行GridItem不显示。设置为其他非法值,按固定1行处理。 |
| columnsGap | [Length](ts-types.md#length) | 设置列与列的间距。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时,按默认值显示。 | | columnsGap | [Length](ts-types.md#length) | 设置列与列的间距。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时,按默认值显示。 |
| rowsGap | [Length](ts-types.md#length) | 设置行与行的间距。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时,按默认值显示。 | | rowsGap | [Length](ts-types.md#length) | 设置行与行的间距。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时,按默认值显示。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 |
......
...@@ -21,6 +21,9 @@ ...@@ -21,6 +21,9 @@
## AppStorage ## AppStorage
AppStorage具体UI使用说明,详见[AppStorage(应用全局的UI状态存储)](../../quick-start/arkts-appstorage.md)
### link<sup>10+</sup> ### link<sup>10+</sup>
static link<T>(propName: string): SubscribedAbstractProperty<T> static link<T>(propName: string): SubscribedAbstractProperty<T>
...@@ -698,6 +701,9 @@ let res: number = AppStorage.Size(); // 1 ...@@ -698,6 +701,9 @@ let res: number = AppStorage.Size(); // 1
## LocalStorage<sup>9+</sup> ## LocalStorage<sup>9+</sup>
LocalStorage具体UI使用说明,详见[LocalStorage(页面级UI状态存储)](../../quick-start/arkts-localstorage.md)
### constructor<sup>9+</sup> ### constructor<sup>9+</sup>
constructor(initializingProperties?: Object) constructor(initializingProperties?: Object)
...@@ -735,9 +741,7 @@ static getShared(): LocalStorage ...@@ -735,9 +741,7 @@ static getShared(): LocalStorage
| [LocalStorage](#localstorage9) | 返回LocalStorage实例。 | | [LocalStorage](#localstorage9) | 返回LocalStorage实例。 |
```ts getShared具体使用,见[在UI页面通过getShared接口获取在通过loadContent共享的LocalStorage实例](../../quick-start/arkts-localstorage.md#将localstorage实例从uiability共享到一个或多个视图)
let storage: LocalStorage = LocalStorage.getShared();
```
### has<sup>9+</sup> ### has<sup>9+</sup>
...@@ -1161,6 +1165,10 @@ link.set(50); // PropB -> 49, link.get() --> undefined ...@@ -1161,6 +1165,10 @@ link.set(50); // PropB -> 49, link.get() --> undefined
## PersistentStorage ## PersistentStorage
PersistentStorage具体UI使用说明,详见[PersistentStorage(持久化存储UI状态)](../../quick-start/arkts-persiststorage.md)
### PersistPropsOptions ### PersistPropsOptions
| 参数名 | 类型 | 必填 | 参数描述 | | 参数名 | 类型 | 必填 | 参数描述 |
...@@ -1196,9 +1204,7 @@ static persistProp&lt;T&gt;(key: string, defaultValue: T): void ...@@ -1196,9 +1204,7 @@ static persistProp&lt;T&gt;(key: string, defaultValue: T): void
**示例:** **示例:**
```ts persistProp具体使用,见[从AppStorage中访问PersistentStorage初始化的属性](../../quick-start/arkts-persiststorage.md#从appstorage中访问persistentstorage初始化的属性)
PersistentStorage.persistProp('highScore', '0');
```
### deleteProp<sup>10+</sup> ### deleteProp<sup>10+</sup>
...@@ -1352,6 +1358,9 @@ let keys: Array<string> = PersistentStorage.Keys(); ...@@ -1352,6 +1358,9 @@ let keys: Array<string> = PersistentStorage.Keys();
## Environment ## Environment
Environment具体使用说明,详见[Environment(设备环境查询)](../../quick-start/arkts-environment.md)
### EnvPropsOptions ### EnvPropsOptions
| 参数名 | 类型 | 必填 | 参数描述 | | 参数名 | 类型 | 必填 | 参数描述 |
...@@ -1386,21 +1395,7 @@ static envProp&lt;S&gt;(key: string, value: S): boolean ...@@ -1386,21 +1395,7 @@ static envProp&lt;S&gt;(key: string, value: S): boolean
**示例:** **示例:**
```ts envProp具体使用,见[从UI中访问Environment参数](../../quick-start/arkts-environment.md#从ui中访问environment参数)
Environment.envProp('accessibilityEnabled', 'default');
```
### 内置环境变量说明
| key | 类型 | 说明 |
| -------------------- | --------------- | ---------------------------------------- |
| accessibilityEnabled | string | 无障碍屏幕朗读是否启用。 |
| colorMode | ColorMode | 深浅色模式,可选值为:<br/>-&nbsp;ColorMode.LIGHT:浅色模式;<br/>-&nbsp;ColorMode.DARK:深色模式。 |
| fontScale | number | 字体大小比例。 |
| fontWeightScale | number | 字重比例。 |
| layoutDirection | LayoutDirection | 布局方向类型,可选值为:<br/>-&nbsp;LayoutDirection.LTR:从左到右;<br/>-&nbsp;LayoutDirection.RTL:从右到左。 |
| languageCode | string | 当前系统语言,小写字母,例如zh。 |
### envProps<sup>10+</sup> ### envProps<sup>10+</sup>
...@@ -1525,4 +1520,16 @@ Environment.EnvProps([{ key: 'accessibilityEnabled', defaultValue: 'default' }, ...@@ -1525,4 +1520,16 @@ Environment.EnvProps([{ key: 'accessibilityEnabled', defaultValue: 'default' },
}, { key: 'prop', defaultValue: 'hhhh' }]); }, { key: 'prop', defaultValue: 'hhhh' }]);
let keys: Array<string> = Environment.Keys(); // accessibilityEnabled, languageCode, prop let keys: Array<string> = Environment.Keys(); // accessibilityEnabled, languageCode, prop
``` ```
\ No newline at end of file
## 内置环境变量说明
| key | 类型 | 说明 |
| -------------------- | --------------- | ---------------------------------------- |
| accessibilityEnabled | string | 无障碍屏幕朗读是否启用。 |
| colorMode | ColorMode | 深浅色模式,可选值为:<br/>-&nbsp;ColorMode.LIGHT:浅色模式;<br/>-&nbsp;ColorMode.DARK:深色模式。 |
| fontScale | number | 字体大小比例。 |
| fontWeightScale | number | 字重比例。 |
| layoutDirection | LayoutDirection | 布局方向类型,可选值为:<br/>-&nbsp;LayoutDirection.LTR:从左到右;<br/>-&nbsp;LayoutDirection.RTL:从右到左。 |
| languageCode | string | 当前系统语言,小写字母,例如zh。 |
\ No newline at end of file
...@@ -7,12 +7,13 @@ ...@@ -7,12 +7,13 @@
> 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
> >
> 已实现默认拖拽效果组件:[Image](../arkui-ts/ts-basic-components-image.md)、[Text](../arkui-ts/ts-basic-components-text.md)、[TextArea](../arkui-ts/ts-basic-components-textarea.md)、[Search](../arkui-ts/ts-basic-components-search.md)。 > 已实现默认拖拽效果组件:[Image](../arkui-ts/ts-basic-components-image.md)、[Text](../arkui-ts/ts-basic-components-text.md)、[TextArea](../arkui-ts/ts-basic-components-textarea.md)、[Search](../arkui-ts/ts-basic-components-search.md)。
>
> 应用中的预置资源文件不支持拖拽(即应用在安装前的HAP包中已经存在的资源文件)。
## 事件 ## 事件
| 名称 | 支持冒泡 | 功能描述 | | 名称 | 支持冒泡 | 功能描述 |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onDragStart(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;&nbsp;[CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明)) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。<br/>- event:拖拽事件信息,详见[DragEvent](#dragevent说明)<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/> 返回值:拖拽过程中显示的组件信息。<br/>触发条件:长按时间 >= 500ms。<br> 事件优先级:长触发时间 < 500ms长按事件 > 拖拽事件<br> 其他: 拖拽事件 > 长按事件。 | | onDragStart(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;&nbsp;[CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo说明)) | 否 | 第一次拖拽此事件绑定的组件时,触发回调。<br/>- event:拖拽事件信息,详见[DragEvent](#dragevent说明)<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/> 返回值:拖拽过程中显示的组件信息。<br/>触发条件:长按时间 >= 500ms。<br> 事件优先级:长触发时间 < 500ms长按事件 > 拖拽事件<br> 其他: 拖拽事件 > 长按事件。 |
| onDragEnter(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽进入组件范围内时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 | | onDragEnter(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽进入组件范围内时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 |
| onDragMove(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽在组件范围内移动时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 | | onDragMove(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽在组件范围内移动时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 |
| onDragLeave(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽离开组件范围内时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 | | onDragLeave(event:&nbsp;(event?:&nbsp;[DragEvent](#dragevent说明),&nbsp;extraParams?:&nbsp;string)&nbsp;=&gt;&nbsp;void) | 否 | 拖拽离开组件范围内时,触发回调。<br/>- event:拖拽事件信息,包括拖拽点坐标。<br/>- extraParams:拖拽事件额外信息,详见[extraParams](#extraparams说明)说明。<br/>当监听了onDrop事件时,此事件才有效。 |
...@@ -90,7 +91,15 @@ struct Index { ...@@ -90,7 +91,15 @@ struct Index {
let records: Array<udmf.UnifiedRecord> = event.getData().getRecords(); let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
if (records.length !== 0) { if (records.length !== 0) {
callback(event); callback(event);
return; return true;
}
return false;
}
getDataFromUdmf(event: DragEvent, callback: (data: DragEvent)=>void)
{
if(this.getDataFromUdmfRetry(event, callback)) {
return;
} }
setTimeout(()=>{ setTimeout(()=>{
this.getDataFromUdmfRetry(event, callback); this.getDataFromUdmfRetry(event, callback);
...@@ -174,7 +183,7 @@ struct Index { ...@@ -174,7 +183,7 @@ struct Index {
.border({color: Color.Black, width: 1}) .border({color: Color.Black, width: 1})
.allowDrop([udmf.UnifiedDataType.IMAGE]) .allowDrop([udmf.UnifiedDataType.IMAGE])
.onDrop((dragEvent: DragEvent)=> { .onDrop((dragEvent: DragEvent)=> {
this.getDataFromUdmfRetry(dragEvent, (event)=>{ this.getDataFromUdmf(dragEvent, (event)=>{
let records: Array<udmf.UnifiedRecord> = event.getData().getRecords(); let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
let rect: Rectangle = event.getPreviewRect(); let rect: Rectangle = event.getPreviewRect();
this.imageWidth = Number(rect.width); this.imageWidth = Number(rect.width);
...@@ -197,7 +206,7 @@ struct Index { ...@@ -197,7 +206,7 @@ struct Index {
.margin(15) .margin(15)
.allowDrop([udmf.UnifiedDataType.TEXT]) .allowDrop([udmf.UnifiedDataType.TEXT])
.onDrop((dragEvent: DragEvent)=>{ .onDrop((dragEvent: DragEvent)=>{
this.getDataFromUdmfRetry(dragEvent, event => { this.getDataFromUdmf(dragEvent, event => {
let records:Array<udmf.UnifiedRecord> = event.getData().getRecords(); let records:Array<udmf.UnifiedRecord> = event.getData().getRecords();
this.targetText = (<udmf.Text>(records[0])).details['value']; this.targetText = (<udmf.Text>(records[0])).details['value'];
}) })
...@@ -215,7 +224,7 @@ struct Index { ...@@ -215,7 +224,7 @@ struct Index {
}.width('100%').height(100).margin(20).border({color: Color.Black, width: 1}) }.width('100%').height(100).margin(20).border({color: Color.Black, width: 1})
.allowDrop([udmf.UnifiedDataType.PLAIN_TEXT]) .allowDrop([udmf.UnifiedDataType.PLAIN_TEXT])
.onDrop((dragEvent)=>{ .onDrop((dragEvent)=>{
this.getDataFromUdmfRetry(dragEvent, event=>{ this.getDataFromUdmf(dragEvent, event=>{
let records: Array<udmf.UnifiedRecord> = event.getData().getRecords(); let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
let plainText: udmf.PlainText = <udmf.PlainText>(records[0]); let plainText: udmf.PlainText = <udmf.PlainText>(records[0]);
this.abstractContent = plainText.abstract; this.abstractContent = plainText.abstract;
......
...@@ -174,3 +174,20 @@ The data group id is not valid. ...@@ -174,3 +174,20 @@ The data group id is not valid.
从应用市场申请dataGroupId,并正确传入该参数。 从应用市场申请dataGroupId,并正确传入该参数。
## 14800051 分布式表类型不匹配
**错误信息**
The type of the distributed table does not match.
**错误描述**
对同一数据库表设置的分布式表类型前后不一致。
**可能原因**
对同一数据库表设置的分布式表类型前后不一致,分布式表类型可见[DistributedType](../apis/js-apis-data-relationalStore.md#distributedtype10)
**处理步骤**
对同一数据库表设置的分布式表类型保持一致,属于端端同步的分布式表不可再设置为用于端云的同步表。
\ No newline at end of file
...@@ -44,7 +44,12 @@ ...@@ -44,7 +44,12 @@
- [drawing_text_typography.h](drawing__text__typography_8h.md) - [drawing_text_typography.h](drawing__text__typography_8h.md)
- [drawing_types.h](drawing__types_8h.md) - [drawing_types.h](drawing__types_8h.md)
- [external_window.h](external__window_8h.md) - [external_window.h](external__window_8h.md)
- [image_mdk.h](image__mdk_8h.md)
- [image_mdk_common.h](image__mdk__common_8h.md)
- [image_pixel_map_mdk.h](image__pixel__map__mdk_8h.md)
- [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) - [image_pixel_map_napi.h](image__pixel__map__napi_8h.md)
- [image_receiver_mdk.h](image__receiver__mdk_8h.md)
- [image_source_mdk.h](image__source__mdk_8h.md)
- [log.h](log_8h.md) - [log.h](log_8h.md)
- [native_buffer.h](native__buffer_8h.md) - [native_buffer.h](native__buffer_8h.md)
- [native_image.h](native__image_8h.md) - [native_image.h](native__image_8h.md)
...@@ -105,8 +110,23 @@ ...@@ -105,8 +110,23 @@
- [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md) - [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](_o_h_ext_data_handle.md) - [OHExtDataHandle](_o_h_ext_data_handle.md)
- [OHHDRMetaData](_o_h_h_d_r_meta_data.md) - [OHHDRMetaData](_o_h_h_d_r_meta_data.md)
- [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)
- [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md)
- [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)
- [OhosImageDecodingOps](_ohos_image_decoding_ops.md)
- [OhosImageReceiverInfo](_ohos_image_receiver_info.md)
- [OhosImageRegion](_ohos_image_region.md)
- [OhosImageSize](_ohos_image_size.md)
- [OhosImageSource](_ohos_image_source.md)
- [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md)
- [OhosImageSourceInfo](_ohos_image_source_info.md)
- [OhosImageSourceOps](_ohos_image_source_ops.md)
- [OhosImageSourceProperty](_ohos_image_source_property.md)
- [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md)
- [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md)
- [OhosImageSourceUpdateData](_ohos_image_source_update_data.md)
- [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) - [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md)
- [OhosPixelMapInfo](_ohos_pixel_map_info.md) - [OhosPixelMapInfos](_ohos_pixel_map_infos.md)
- [RawFileDescriptor](_raw_file_descriptor.md) - [RawFileDescriptor](_raw_file_descriptor.md)
- [Region](_region.md) - [Region](_region.md)
- [Rect](_rect.md) - [Rect](_rect.md)
......
...@@ -36,4 +36,4 @@ ...@@ -36,4 +36,4 @@
| [getReal](_r_d_b.md#getreal) | 函数指针,以double形式获取当前行中指定列的值。 | | [getReal](_r_d_b.md#getreal) | 函数指针,以double形式获取当前行中指定列的值。 |
| [getBlob](_r_d_b.md#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 | | [getBlob](_r_d_b.md#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 |
| [isNull](_r_d_b.md#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 | | [isNull](_r_d_b.md#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 |
| [close](_r_d_b.md#close) | 函数指针,关闭结果集。 | | [destroy](_r_d_b.md#destroy-14) | 函数指针,关闭结果集。 |
...@@ -45,4 +45,4 @@ ...@@ -45,4 +45,4 @@
| [in](_r_d_b.md#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 | | [in](_r_d_b.md#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 |
| [notIn](_r_d_b.md#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 | | [notIn](_r_d_b.md#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 |
| [clear](_r_d_b.md#clear-12) | 函数指针,清空谓词。 | | [clear](_r_d_b.md#clear-12) | 函数指针,清空谓词。 |
| [destroyPredicates](_r_d_b.md#destroypredicates) | 销毁OH_Predicates对象,并回收该对象占用的内存。 | | [destroy](_r_d_b.md#destroy-24) | 销毁OH_Predicates对象,并回收该对象占用的内存。 |
...@@ -21,6 +21,9 @@ ...@@ -21,6 +21,9 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [path](_r_d_b.md#path) | 数据库文件路径。 | | [selfSize](_r_d_b.md#selfsize) | 该结构体的大小。 |
| [dataBaseDir](_r_d_b.md#databasedir) | 数据库文件路径。 |
| [bundleName](_r_d_b.md#bundlename) | 应用包名。 |
| [moduleName](_r_d_b.md#modulename) | 应用模块名。 |
| [isEncrypt](_r_d_b.md#isencrypt) | 指定数据库是否加密。 | | [isEncrypt](_r_d_b.md#isencrypt) | 指定数据库是否加密。 |
| [securityLevel](_r_d_b.md#securitylevel) | 设置数据库安全级别&nbsp;[OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel)。 | | [securityLevel](_r_d_b.md#securitylevel) | 数据库安全级别。 |
...@@ -29,4 +29,4 @@ ...@@ -29,4 +29,4 @@
| [putBlob](_r_d_b.md#putblob) | 将const uint8_t \*值放入给定列名的OH_VBucket对象中。 | | [putBlob](_r_d_b.md#putblob) | 将const uint8_t \*值放入给定列名的OH_VBucket对象中。 |
| [putNull](_r_d_b.md#putnull) | 将NULL值放入给定列名的OH_VBucket对象中。 | | [putNull](_r_d_b.md#putnull) | 将NULL值放入给定列名的OH_VBucket对象中。 |
| [clear](_r_d_b.md#clear-22) | 清空OH_VBucket对象。 | | [clear](_r_d_b.md#clear-22) | 清空OH_VBucket对象。 |
| [destroyValuesBucket](_r_d_b.md#destroyvaluesbucket) | 销毁OH_VBucket对象,并回收该对象占用的内存。 | | [destroy](_r_d_b.md#destroy-34) | 销毁OH_VBucket对象,并回收该对象占用的内存。 |
...@@ -26,4 +26,4 @@ ...@@ -26,4 +26,4 @@
| [putDouble](_r_d_b.md#putdouble) | 将double类型的单个参数或者数组转换为OH_VObject类型的值。 | | [putDouble](_r_d_b.md#putdouble) | 将double类型的单个参数或者数组转换为OH_VObject类型的值。 |
| [putText](_r_d_b.md#puttext-22) | 将char \*类型的字符数组转换为OH_VObject类型的值。 | | [putText](_r_d_b.md#puttext-22) | 将char \*类型的字符数组转换为OH_VObject类型的值。 |
| [putTexts](_r_d_b.md#puttexts) | 将char \*类型的字符串数组转换为OH_VObject类型的值。 | | [putTexts](_r_d_b.md#puttexts) | 将char \*类型的字符串数组转换为OH_VObject类型的值。 |
| [destroyValueObject](_r_d_b.md#destroyvalueobject) | 销毁OH_VObject对象,并回收该对象占用的内存。 | | [destroy](_r_d_b.md#destroy-44) | 销毁OH_VObject对象,并回收该对象占用的内存。 |
# OHOS::Media::OhosImageComponent
## 概述
定义图像组成信息。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [byteBuffer](#bytebuffer) | 像素数据地址 |
| [size](#size) | 内存中的像素数据大小 |
| [componentType](#componenttype) | 像素数据类型 |
| [rowStride](#rowstride) | 像素数据行宽 |
| [pixelStride](#pixelstride) | 像素数据的像素大小 |
## 结构体成员变量说明
### byteBuffer
```
uint8_t* OHOS::Media::OhosImageComponent::byteBuffer
```
**描述:**
像素数据地址
### componentType
```
int32_t OHOS::Media::OhosImageComponent::componentType
```
**描述:**
像素数据类型
### pixelStride
```
int32_t OHOS::Media::OhosImageComponent::pixelStride
```
**描述:**
像素数据的像素大小
### rowStride
```
int32_t OHOS::Media::OhosImageComponent::rowStride
```
**描述:**
像素数据行宽
### size
```
size_t OHOS::Media::OhosImageComponent::size
```
**描述:**
内存中的像素数据大小
# OHOS::Media::OhosImageRect
## 概述
定义图像矩形信息。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [x](#x) | 矩形x坐标值 |
| [y](#y) | 矩形y坐标值 |
| [width](#width) | 矩形宽度值,用pixels表示 |
| [height](#height) | 矩形高度值,用pixels表示 |
## 结构体成员变量说明
### height
```
int32_t OHOS::Media::OhosImageRect::height
```
**描述:**
矩形高度值,用pixels表示
### width
```
int32_t OHOS::Media::OhosImageRect::width
```
**描述:**
矩形宽度值,用pixels表示
### x
```
int32_t OHOS::Media::OhosImageRect::x
```
**描述:**
矩形x坐标值
### y
```
int32_t OHOS::Media::OhosImageRect::y
```
**描述:**
矩形y坐标值
# OHOS::Media::OhosPixelMapInfo
## 概述
用于定义 pixel map 的相关信息。
**起始版本:**
8
**废弃起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [width](#width) | 图片的宽,用pixels表示 |
| [height](#height) | 图片的高,用pixels表示 |
| [rowSize](#rowsize) | 每行的bytes数 |
| [pixelFormat](#pixelformat) | Pixel 的格式 |
## 结构体成员变量说明
### height
```
uint32_t OHOS::Media::OhosPixelMapInfo::height
```
**描述:**
图片的高, 用pixels表示
### pixelFormat
```
int32_t OHOS::Media::OhosPixelMapInfo::pixelFormat
```
**描述:**
Pixel 的格式
### rowSize
```
uint32_t OHOS::Media::OhosPixelMapInfo::rowSize
```
**描述:**
每行的bytes数
### width
```
uint32_t OHOS::Media::OhosPixelMapInfo::width
```
**描述:**
图片的宽, 用pixels表示
# OhosImageDecodingOps
## 概述
定义图像源解码选项。 此选项给[OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap)[OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [editable](image.md#editable) | 定义输出的像素位图是否可编辑 |
| [pixelFormat](image.md#pixelformat-23) | 定义输出的像素格式 |
| [fitDensity](image.md#fitdensity) | 定义解码目标的像素密度 |
| [index](image.md#index) | 定义图像源解码指数 |
| [sampleSize](image.md#samplesize) | 定义解码样本大小选项 |
| [rotate](image.md#rotate) | 定义解码旋转选项 |
| [size](image.md#size-27) | 定义解码目标像素宽高的大小 |
| [region](image.md#region) | 定义图像源解码的像素范围 |
# OhosImageReceiverInfo
## 概述
定义**ImageReceiver**的相关信息。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| width | 消费端接收图片时的默认图像宽度,用pixels表示 |
| height | 消费端接收图片时的默认图像高度,用pixels表示 |
| format | 通过接收器创建图像格式OHOS_IMAGE_FORMAT_JPEG |
| capicity | 图片缓存数量的最大值 |
# OhosImageRegion
## 概述
定义图像源解码的范围选项。 [OhosImageDecodingOps](_ohos_image_decoding_ops.md), [OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap) and [OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist).
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [x](image.md#x) | 起始x坐标,用pixels表示 |
| [y](image.md#y) | 起始y坐标,用pixels表示 |
| [width](image.md#width) | 宽度范围,用pixels表示 |
| [height](image.md#height) | 高度范围,用pixels表示 |
# OhosImageSize
## 概述
定义图像大小。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [width](#width) | 像素中的图像宽度,用pixels表示 |
| [height](#height) | 像素中的图像高度,用pixels表示 |
## 结构体成员变量说明
### height
```
int32_t OhosImageSize::height
```
**描述:**
像素中的图像高度,用pixels表示
### width
```
int32_t OhosImageSize::width
```
**描述:**
像素中的图像宽度,用pixels表示
# OhosImageSource
## 概述
定义图像源输入资源,每次仅接收一种类型。由[OH_ImageSource_Create](image.md#oh_imagesource_create)获取。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [uri](image.md#uri) = nullptr | 图像源资源标识符,接受文件资源或者base64资源 |
| [uriSize](image.md#urisize) = 0 | 图像源资源长度 |
| [fd](image.md#fd) = -1 | 图像源文件资源描述符 |
| [buffer](image.md#buffer-12) = nullptr | 图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区 |
| [bufferSize](image.md#buffersize-12) = 0 | 图像源缓冲区资源大小 |
# OhosImageSourceDelayTimeList
## 概述
定义图像源延迟时间列表。由[OH_ImageSource_GetDelayTime](image.md#oh_imagesource_getdelaytime)获取。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [delayTimeList](image.md#delaytimelist) | 图像源延迟时间列表头地址 |
| [size](image.md#size-47) = 0 | 图像源延迟时间列表大小 |
# OhosImageSourceInfo
## 概述
定义图像源信息,由[OH_ImageSource_GetImageInfo](image.md#oh_imagesource_getimageinfo)获取。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [pixelFormat](image.md#pixelformat-33) | 图像源像素格式, 由[OH_ImageSource_Create()](image.md#oh_imagesource_create)设置 |
| [colorSpace](image.md#colorspace) | 图像源色彩空间 |
| [alphaType](image.md#alphatype) | 图像源透明度类型 |
| [density](image.md#density-22) | 图像源密度, 由 [OH_ImageSource_Create()](image.md#oh_imagesource_create)设置 |
| [size](image.md#size-37) | 图像源像素宽高的大小 |
# OhosImageSourceOps
## 概述
定义图像源选项信息。 此选项给[OH_ImageSource_Create](image.md#oh_imagesource_create)[OH_ImageSource_CreateIncremental](image.md#oh_imagesource_createincremental)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [density](image.md#density-12) | 图像源像素密度 |
| [pixelFormat](image.md#pixelformat-13) | 图像源像素格式,通常用于描述YUV缓冲区 |
| [size](image.md#size-17) | 图像源像素宽高的大小 |
# OhosImageSourceProperty
## 概述
定义图像源属性键值字符串。 此选项给[OH_ImageSource_GetImageProperty](image.md#oh_imagesource_getimageproperty) and [OH_ImageSource_ModifyImageProperty](image.md#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [value](image.md#value) = nullptr | 定义图像源属性键值字符串头地址 |
| [size](image.md#size-77) = 0 | 定义图像源属性键值字符串大小 |
# OhosImageSourceSupportedFormat
## 概述
定义图像源支持的格式字符串。 此选项给[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md)[OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [format](image.md#format) = nullptr | 图像源支持的格式字符串头地址 |
| [size](image.md#size-57) = 0 | 图像源支持的格式字符串大小 |
# OhosImageSourceSupportedFormatList
## 概述
定义图像源支持的格式字符串列表。 由[OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats)获取
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [supportedFormatList](image.md#supportedformatlist) = nullptr | 图像源支持的格式字符串列表头地址 |
| [size](image.md#size-67) = 0 | 图像源支持的格式字符串列表大小 |
# OhosImageSourceUpdateData
## 概述
定义图像源更新数据选项,由[OH_ImageSource_UpdateData](image.md#oh_imagesource_updatedata)获取。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 成员变量
| 名称 | 描述 |
| -------- | -------- |
| [buffer](image.md#buffer-22) = nullptr | 图像源更新数据缓冲区 |
| [bufferSize](image.md#buffersize-22) = 0 | 图像源更新数据缓冲区大小 |
| [offset](image.md#offset) = 0 | 图像源更新数据缓冲区的开端 |
| [updateLength](image.md#updatelength) = 0 | 图像源更新数据缓冲区的更新数据长度 |
| [isCompleted](image.md#iscompleted) = 0 | 图像源更新数据在此节中完成 |
...@@ -3,12 +3,13 @@ ...@@ -3,12 +3,13 @@
## 概述 ## 概述
用于定义创建 pixel map 设置选项的相关信息. 用于定义创建 pixel map 设置选项的相关信息
**起始版本:** **起始版本:**
10 10
**相关模块:** **相关模块**
[Image](image.md) [Image](image.md)
...@@ -20,12 +21,12 @@ ...@@ -20,12 +21,12 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [width](#width) | 图片的宽,用pixels表示。 | | [width](#width) | 图片的宽, 用pixels表示 |
| [height](#height) | 图片的高,用pixels表示。 | | [height](#height) | 图片的高, 用pixels表示 |
| [pixelFormat](#pixelformat) | 图片的格式 | | [pixelFormat](#pixelformat) | 图片的格式 |
| [editable](#editable) | 图片的编辑类型 | | [editable](#editable) | 图片的编辑类型 |
| [alphaType](#alphatype) | 图片的alpha类型 | | [alphaType](#alphatype) | 图片的alpha类型 |
| [scaleMode](#scalemode) | 图片的缩放类型 | | [scaleMode](#scalemode) | 图片的缩放类型 |
## 结构体成员变量说明 ## 结构体成员变量说明
...@@ -33,59 +34,65 @@ ...@@ -33,59 +34,65 @@
### alphaType ### alphaType
``` ```
uint32_t OhosPixelMapCreateOps::alphaType uint32_t OhosPixelMapCreateOps::alphaType
``` ```
**描述:**
图片的alpha类型。 **描述:**
图片的alpha类型
### editable ### editable
``` ```
uint32_t OhosPixelMapCreateOps::editable uint32_t OhosPixelMapCreateOps::editable
``` ```
**描述:**
图片的编辑类型。 **描述:**
图片的编辑类型
### height ### height
``` ```
uint32_t OhosPixelMapCreateOps::height uint32_t OhosPixelMapCreateOps::height
``` ```
**描述:**
图片的高,用pixels表示。 **描述:**
图片的高, 用pixels表示
### pixelFormat ### pixelFormat
``` ```
int32_t OhosPixelMapCreateOps::pixelFormat int32_t OhosPixelMapCreateOps::pixelFormat
``` ```
**描述:**
图片的格式。 **描述:**
图片的格式
### scaleMode ### scaleMode
``` ```
uint32_t OhosPixelMapCreateOps::scaleMode uint32_t OhosPixelMapCreateOps::scaleMode
``` ```
**描述:**
图片的缩放类型。 **描述:**
图片的缩放类型
### width ### width
``` ```
uint32_t OhosPixelMapCreateOps::width uint32_t OhosPixelMapCreateOps::width
``` ```
**描述:**
图片的宽,用pixels表示。 **描述:**
图片的宽, 用pixels表示
# OhosPixelMapInfo # OhosPixelMapInfos
## 概述 ## 概述
用于定义 pixel map 的相关信息。 用于定义 pixel map 的相关信息。
**起始版本:** **起始版本:**
8 10
**相关模块:** **相关模块:**
[Image](image.md) [Image](image.md)
## 汇总 ## 汇总
### 成员变量 ### 成员变量
| 成员变量名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [width](#width) | 图片的宽,用pixels表示。 | | [width](#width) | 图片的宽, 用pixels表示 |
| [height](#height) | 图片的高,用pixels表示。 | | [height](#height) | 图片的高, 用pixels表示 |
| [rowSize](#rowsize) | 每行的bytes数。 | | [rowSize](#rowsize) | 每行的bytes数 |
| [pixelFormat](#pixelformat) | Pixel的格式。 | | [pixelFormat](#pixelformat) | Pixel 的格式 |
## 结构体成员变量说明 ## 结构体成员变量说明
### height ### height
```
``` uint32_t OhosPixelMapInfos::height
uint32_t OhosPixelMapInfo::height ```
```
**描述:**
**描述:**
图片的高, 用pixels表示
图片的高,用pixels表示。
### pixelFormat
### pixelFormat
```
int32_t OhosPixelMapInfos::pixelFormat
``` ```
int32_t OhosPixelMapInfo::pixelFormat
``` **描述:**
**描述:** Pixel 的格式
Pixel的格式。
### rowSize
### rowSize ```
uint32_t OhosPixelMapInfos::rowSize
```
```
uint32_t OhosPixelMapInfo::rowSize **描述:**
```
每行的bytes数
**描述:**
每行的bytes数。 ### width
```
### width uint32_t OhosPixelMapInfos::width
```
``` **描述:**
uint32_t OhosPixelMapInfo::width
``` 图片的宽, 用pixels表示
**描述:**
图片的宽,用pixels表示。
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的 对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。 关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的 对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。
\@syscap SystemCapability.DistributedDataManager.RelationalStore.Core \@SystemCapability.DistributedDataManager.RelationalStore.Core
**起始版本:** **起始版本:**
...@@ -43,10 +43,13 @@ ...@@ -43,10 +43,13 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_ColumnType](#oh_columntype) | 数据库字段类型。 |
| [OH_Cursor](#oh_cursor) | 表示结果集。 | | [OH_Cursor](#oh_cursor) | 表示结果集。 |
| [OH_OrderType](#oh_ordertype) | 排序方式。 |
| [OH_Predicates](#oh_predicates) | 表示谓词。 | | [OH_Predicates](#oh_predicates) | 表示谓词。 |
| [OH_VObject](#oh_vobject) | 表示允许的数据字段类型。 | | [OH_VObject](#oh_vobject) | 表示允许的数据字段类型。 |
| [OH_VBucket](#oh_vbucket) | 用于存储键值对的类型。 | | [OH_VBucket](#oh_vbucket) | 用于存储键值对的类型。 |
| [OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) | 数据库的安全级别枚举。 |
| [OH_Rdb_ErrCode](#oh_rdb_errcode) | 表示错误码信息。 | | [OH_Rdb_ErrCode](#oh_rdb_errcode) | 表示错误码信息。 |
...@@ -69,7 +72,7 @@ ...@@ -69,7 +72,7 @@
| [OH_Rdb_CreatePredicates](#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 | | [OH_Rdb_CreatePredicates](#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 |
| [OH_Rdb_GetOrOpen](#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 | | [OH_Rdb_GetOrOpen](#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 |
| [OH_Rdb_CloseStore](#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 | | [OH_Rdb_CloseStore](#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 |
| [OH_Rdb_DeleteStore](#oh_rdb_deletestore) (const char \*path) | 使用指定的数据库文件配置删除数据库。 | | [OH_Rdb_DeleteStore](#oh_rdb_deletestore) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config) | 使用指定的数据库文件配置删除数据库。 |
| [OH_Rdb_Insert](#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 | | [OH_Rdb_Insert](#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 |
| [OH_Rdb_Update](#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 | | [OH_Rdb_Update](#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 |
| [OH_Rdb_Delete](#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 | | [OH_Rdb_Delete](#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 |
...@@ -102,7 +105,7 @@ ...@@ -102,7 +105,7 @@
| [OH_Cursor::getReal](#getreal) | 函数指针,以double形式获取当前行中指定列的值。 | | [OH_Cursor::getReal](#getreal) | 函数指针,以double形式获取当前行中指定列的值。 |
| [OH_Cursor::getBlob](#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 | | [OH_Cursor::getBlob](#getblob) | 函数指针,以字节数组的形式获取当前行中指定列的值。 |
| [OH_Cursor::isNull](#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 | | [OH_Cursor::isNull](#isnull-12) | 函数指针,检查当前行中指定列的值是否为null。 |
| [OH_Cursor::close](#close) | 函数指针,关闭结果集。 | | [OH_Cursor::destroy](#destroy-14) | 函数指针,关闭结果集。 |
| [OH_Predicates::id](#id-14) | OH_Predicates结构体的唯一标识符。 | | [OH_Predicates::id](#id-14) | OH_Predicates结构体的唯一标识符。 |
| [OH_Predicates::equalTo](#equalto) | 函数指针,配置谓词以匹配数据字段等于指定值的字段。 | | [OH_Predicates::equalTo](#equalto) | 函数指针,配置谓词以匹配数据字段等于指定值的字段。 |
| [OH_Predicates::notEqualTo](#notequalto) | 函数指针,配置谓词以匹配数据字段不等于指定值的字段。 | | [OH_Predicates::notEqualTo](#notequalto) | 函数指针,配置谓词以匹配数据字段不等于指定值的字段。 |
...@@ -127,13 +130,13 @@ ...@@ -127,13 +130,13 @@
| [OH_Predicates::in](#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 | | [OH_Predicates::in](#in) | 函数指针,配置谓词以匹配数据字段为field且值在给定范围内的指定字段。 |
| [OH_Predicates::notIn](#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 | | [OH_Predicates::notIn](#notin) | 函数指针,配置谓词以匹配数据字段为field且值超出给定范围内的指定字段。 |
| [OH_Predicates::clear](#clear-12) | 函数指针,清空谓词。 | | [OH_Predicates::clear](#clear-12) | 函数指针,清空谓词。 |
| [OH_Predicates::destroyPredicates](#destroypredicates) | 销毁[OH_Predicates](_o_h___predicates.md)对象,并回收该对象占用的内存。 | | [OH_Predicates::destroy](#destroy-24) | 销毁[OH_Predicates](_o_h___predicates.md)对象,并回收该对象占用的内存。 |
| [OH_VObject::id](#id-24) | OH_VObject结构体的唯一标识符。 | | [OH_VObject::id](#id-24) | OH_VObject结构体的唯一标识符。 |
| [OH_VObject::putInt64](#putint64-22) | 将int64类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putInt64](#putint64-22) | 将int64类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 |
| [OH_VObject::putDouble](#putdouble) | 将double类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putDouble](#putdouble) | 将double类型的单个参数或者数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 |
| [OH_VObject::putText](#puttext-22) | 将char \*类型的字符数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putText](#puttext-22) | 将char \*类型的字符数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 |
| [OH_VObject::putTexts](#puttexts) | 将char \*类型的字符串数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 | | [OH_VObject::putTexts](#puttexts) | 将char \*类型的字符串数组转换为[OH_VObject](_o_h___v_object.md)类型的值。 |
| [OH_VObject::destroyValueObject](#destroyvalueobject) | 销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 | | [OH_VObject::destroy](#destroy-44) | 销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 |
| [OH_VBucket::id](#id-34) | OH_VBucket结构体的唯一标识符。 | | [OH_VBucket::id](#id-34) | OH_VBucket结构体的唯一标识符。 |
| [OH_VBucket::capability](#capability) | 表示结构体的存储键值对的数量 | | [OH_VBucket::capability](#capability) | 表示结构体的存储键值对的数量 |
| [OH_VBucket::putText](#puttext-12) | 将char\*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | | [OH_VBucket::putText](#puttext-12) | 将char\*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 |
...@@ -142,8 +145,11 @@ ...@@ -142,8 +145,11 @@
| [OH_VBucket::putBlob](#putblob) | 将const uint8_t \*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | | [OH_VBucket::putBlob](#putblob) | 将const uint8_t \*值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 |
| [OH_VBucket::putNull](#putnull) | 将NULL值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 | | [OH_VBucket::putNull](#putnull) | 将NULL值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。 |
| [OH_VBucket::clear](#clear-22) | 清空[OH_VBucket](_o_h___v_bucket.md)对象。 | | [OH_VBucket::clear](#clear-22) | 清空[OH_VBucket](_o_h___v_bucket.md)对象。 |
| [OH_VBucket::destroyValuesBucket](#destroyvaluesbucket) | 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 | | [OH_VBucket::destroy](#destroy-34) | 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 |
| [OH_Rdb_Config::path](#path) | 数据库文件路径。 | | [OH_Rdb_Config::selfSize](#selfsize) | 该结构体的大小。 |
| [OH_Rdb_Config::dataBaseDir](#databasedir) | 数据库文件路径。 |
| [OH_Rdb_Config::bundleName](#bundlename) | 应用包名。 |
| [OH_Rdb_Config::moduleName](#modulename) | 应用模块名。 |
| [OH_Rdb_Config::isEncrypt](#isencrypt) | 指定数据库是否加密。 | | [OH_Rdb_Config::isEncrypt](#isencrypt) | 指定数据库是否加密。 |
| [OH_Rdb_Config::securityLevel](#securitylevel) | 设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)。 | | [OH_Rdb_Config::securityLevel](#securitylevel) | 设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)。 |
| [OH_Rdb_Store::id](#id-44) | OH_Rdb_Store结构体的唯一标识符。 | | [OH_Rdb_Store::id](#id-44) | OH_Rdb_Store结构体的唯一标识符。 |
...@@ -152,8 +158,18 @@ ...@@ -152,8 +158,18 @@
## 类型定义说明 ## 类型定义说明
### OH_Cursor ### OH_ColumnType
```
typedef enum OH_ColumnType OH_ColumnType
```
**描述:**
数据库字段类型.
### OH_Cursor
``` ```
typedef struct OH_Cursor OH_Cursor typedef struct OH_Cursor OH_Cursor
...@@ -166,9 +182,19 @@ typedef struct OH_Cursor OH_Cursor ...@@ -166,9 +182,19 @@ typedef struct OH_Cursor OH_Cursor
提供通过查询数据库生成的数据库结果集的访问方法。 提供通过查询数据库生成的数据库结果集的访问方法。
### OH_Predicates ### OH_OrderType
```
typedef enum OH_OrderType OH_OrderType
```
**描述:**
排序方式。
### OH_Predicates
``` ```
typedef struct OH_Predicates OH_Predicates typedef struct OH_Predicates OH_Predicates
``` ```
...@@ -180,7 +206,6 @@ typedef struct OH_Predicates OH_Predicates ...@@ -180,7 +206,6 @@ typedef struct OH_Predicates OH_Predicates
### OH_Rdb_ErrCode ### OH_Rdb_ErrCode
``` ```
typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode
``` ```
...@@ -190,8 +215,18 @@ typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode ...@@ -190,8 +215,18 @@ typedef enum OH_Rdb_ErrCode OH_Rdb_ErrCode
表示错误码信息。 表示错误码信息。
### OH_VBucket ### OH_Rdb_SecurityLevel
```
typedef enum OH_Rdb_SecurityLevel OH_Rdb_SecurityLevel
```
**描述:**
数据库的安全级别枚举。
### OH_VBucket
``` ```
typedef struct OH_VBucket OH_VBucket typedef struct OH_VBucket OH_VBucket
...@@ -204,7 +239,6 @@ typedef struct OH_VBucket OH_VBucket ...@@ -204,7 +239,6 @@ typedef struct OH_VBucket OH_VBucket
### OH_VObject ### OH_VObject
``` ```
typedef struct OH_VObject OH_VObject typedef struct OH_VObject OH_VObject
``` ```
...@@ -219,7 +253,6 @@ typedef struct OH_VObject OH_VObject ...@@ -219,7 +253,6 @@ typedef struct OH_VObject OH_VObject
### OH_ColumnType ### OH_ColumnType
``` ```
enum OH_ColumnType enum OH_ColumnType
``` ```
...@@ -239,7 +272,6 @@ enum OH_ColumnType ...@@ -239,7 +272,6 @@ enum OH_ColumnType
### OH_OrderType ### OH_OrderType
``` ```
enum OH_OrderType enum OH_OrderType
``` ```
...@@ -256,7 +288,6 @@ enum OH_OrderType ...@@ -256,7 +288,6 @@ enum OH_OrderType
### OH_Rdb_ErrCode ### OH_Rdb_ErrCode
``` ```
enum OH_Rdb_ErrCode enum OH_Rdb_ErrCode
``` ```
...@@ -323,7 +354,6 @@ enum OH_Rdb_ErrCode ...@@ -323,7 +354,6 @@ enum OH_Rdb_ErrCode
### OH_Rdb_SecurityLevel ### OH_Rdb_SecurityLevel
``` ```
enum OH_Rdb_SecurityLevel enum OH_Rdb_SecurityLevel
``` ```
...@@ -345,7 +375,6 @@ enum OH_Rdb_SecurityLevel ...@@ -345,7 +375,6 @@ enum OH_Rdb_SecurityLevel
### OH_Rdb_Backup() ### OH_Rdb_Backup()
``` ```
int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath ) int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath )
``` ```
...@@ -372,7 +401,6 @@ int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath ) ...@@ -372,7 +401,6 @@ int OH_Rdb_Backup (OH_Rdb_Store * store, const char * databasePath )
### OH_Rdb_BeginTransaction() ### OH_Rdb_BeginTransaction()
``` ```
int OH_Rdb_BeginTransaction (OH_Rdb_Store * store) int OH_Rdb_BeginTransaction (OH_Rdb_Store * store)
``` ```
...@@ -398,7 +426,6 @@ int OH_Rdb_BeginTransaction (OH_Rdb_Store * store) ...@@ -398,7 +426,6 @@ int OH_Rdb_BeginTransaction (OH_Rdb_Store * store)
### OH_Rdb_CloseStore() ### OH_Rdb_CloseStore()
``` ```
int OH_Rdb_CloseStore (OH_Rdb_Store * store) int OH_Rdb_CloseStore (OH_Rdb_Store * store)
``` ```
...@@ -424,7 +451,6 @@ int OH_Rdb_CloseStore (OH_Rdb_Store * store) ...@@ -424,7 +451,6 @@ int OH_Rdb_CloseStore (OH_Rdb_Store * store)
### OH_Rdb_Commit() ### OH_Rdb_Commit()
``` ```
int OH_Rdb_Commit (OH_Rdb_Store * store) int OH_Rdb_Commit (OH_Rdb_Store * store)
``` ```
...@@ -450,7 +476,6 @@ int OH_Rdb_Commit (OH_Rdb_Store * store) ...@@ -450,7 +476,6 @@ int OH_Rdb_Commit (OH_Rdb_Store * store)
### OH_Rdb_CreatePredicates() ### OH_Rdb_CreatePredicates()
``` ```
OH_Predicates* OH_Rdb_CreatePredicates (const char * table) OH_Predicates* OH_Rdb_CreatePredicates (const char * table)
``` ```
...@@ -476,9 +501,8 @@ OH_Predicates* OH_Rdb_CreatePredicates (const char * table) ...@@ -476,9 +501,8 @@ OH_Predicates* OH_Rdb_CreatePredicates (const char * table)
### OH_Rdb_CreateValueObject() ### OH_Rdb_CreateValueObject()
``` ```
OH_VObject* OH_Rdb_CreateValueObject (void ) OH_VObject* OH_Rdb_CreateValueObject (void)
``` ```
**描述:** **描述:**
...@@ -496,9 +520,8 @@ OH_VObject* OH_Rdb_CreateValueObject (void ) ...@@ -496,9 +520,8 @@ OH_VObject* OH_Rdb_CreateValueObject (void )
### OH_Rdb_CreateValuesBucket() ### OH_Rdb_CreateValuesBucket()
``` ```
OH_VBucket* OH_Rdb_CreateValuesBucket (void ) OH_VBucket* OH_Rdb_CreateValuesBucket (void)
``` ```
**描述:** **描述:**
...@@ -516,7 +539,6 @@ OH_VBucket* OH_Rdb_CreateValuesBucket (void ) ...@@ -516,7 +539,6 @@ OH_VBucket* OH_Rdb_CreateValuesBucket (void )
### OH_Rdb_Delete() ### OH_Rdb_Delete()
``` ```
int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates ) int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates )
``` ```
...@@ -543,9 +565,8 @@ int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates ) ...@@ -543,9 +565,8 @@ int OH_Rdb_Delete (OH_Rdb_Store * store, OH_Predicates * predicates )
### OH_Rdb_DeleteStore() ### OH_Rdb_DeleteStore()
``` ```
int OH_Rdb_DeleteStore (const char * path) int OH_Rdb_DeleteStore (const OH_Rdb_Config * config)
``` ```
**描述:** **描述:**
...@@ -565,7 +586,6 @@ int OH_Rdb_DeleteStore (const char * path) ...@@ -565,7 +586,6 @@ int OH_Rdb_DeleteStore (const char * path)
### OH_Rdb_Execute() ### OH_Rdb_Execute()
``` ```
int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql ) int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql )
``` ```
...@@ -592,7 +612,6 @@ int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql ) ...@@ -592,7 +612,6 @@ int OH_Rdb_Execute (OH_Rdb_Store * store, const char * sql )
### OH_Rdb_ExecuteQuery() ### OH_Rdb_ExecuteQuery()
``` ```
OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql ) OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql )
``` ```
...@@ -619,7 +638,6 @@ OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql ) ...@@ -619,7 +638,6 @@ OH_Cursor* OH_Rdb_ExecuteQuery (OH_Rdb_Store * store, const char * sql )
### OH_Rdb_GetOrOpen() ### OH_Rdb_GetOrOpen()
``` ```
OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode ) OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode )
``` ```
...@@ -646,7 +664,6 @@ OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode ) ...@@ -646,7 +664,6 @@ OH_Rdb_Store* OH_Rdb_GetOrOpen (const OH_Rdb_Config * config, int * errCode )
### OH_Rdb_GetVersion() ### OH_Rdb_GetVersion()
``` ```
int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version ) int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version )
``` ```
...@@ -673,7 +690,6 @@ int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version ) ...@@ -673,7 +690,6 @@ int OH_Rdb_GetVersion (OH_Rdb_Store * store, int * version )
### OH_Rdb_Insert() ### OH_Rdb_Insert()
``` ```
int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * valuesBucket ) int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * valuesBucket )
``` ```
...@@ -701,7 +717,6 @@ int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * values ...@@ -701,7 +717,6 @@ int OH_Rdb_Insert (OH_Rdb_Store * store, const char * table, OH_VBucket * values
### OH_Rdb_Query() ### OH_Rdb_Query()
``` ```
OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const char *const * columnNames, int length ) OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const char *const * columnNames, int length )
``` ```
...@@ -730,7 +745,6 @@ OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const ...@@ -730,7 +745,6 @@ OH_Cursor* OH_Rdb_Query (OH_Rdb_Store * store, OH_Predicates * predicates, const
### OH_Rdb_Restore() ### OH_Rdb_Restore()
``` ```
int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath ) int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath )
``` ```
...@@ -757,7 +771,6 @@ int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath ) ...@@ -757,7 +771,6 @@ int OH_Rdb_Restore (OH_Rdb_Store * store, const char * databasePath )
### OH_Rdb_RollBack() ### OH_Rdb_RollBack()
``` ```
int OH_Rdb_RollBack (OH_Rdb_Store * store) int OH_Rdb_RollBack (OH_Rdb_Store * store)
``` ```
...@@ -783,7 +796,6 @@ int OH_Rdb_RollBack (OH_Rdb_Store * store) ...@@ -783,7 +796,6 @@ int OH_Rdb_RollBack (OH_Rdb_Store * store)
### OH_Rdb_SetVersion() ### OH_Rdb_SetVersion()
``` ```
int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version ) int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version )
``` ```
...@@ -810,7 +822,6 @@ int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version ) ...@@ -810,7 +822,6 @@ int OH_Rdb_SetVersion (OH_Rdb_Store * store, int version )
### OH_Rdb_Update() ### OH_Rdb_Update()
``` ```
int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicates * predicates ) int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicates * predicates )
``` ```
...@@ -841,7 +852,6 @@ int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicate ...@@ -841,7 +852,6 @@ int OH_Rdb_Update (OH_Rdb_Store * store, OH_VBucket * valuesBucket, OH_Predicate
### andOperate ### andOperate
``` ```
OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates)
``` ```
...@@ -869,7 +879,6 @@ OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates) ...@@ -869,7 +879,6 @@ OH_Predicates*(* OH_Predicates::andOperate) (OH_Predicates *predicates)
### beginWrap ### beginWrap
``` ```
OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates)
``` ```
...@@ -897,7 +906,6 @@ OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates) ...@@ -897,7 +906,6 @@ OH_Predicates*(* OH_Predicates::beginWrap) (OH_Predicates *predicates)
### between ### between
``` ```
OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -925,8 +933,18 @@ OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char ...@@ -925,8 +933,18 @@ OH_Predicates*(* OH_Predicates::between) (OH_Predicates *predicates, const char
[OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md). [OH_Predicates](_o_h___predicates.md), [OH_VObject](_o_h___v_object.md).
### capability ### bundleName
```
const char* OH_Rdb_Config::bundleName
```
**描述:**
应用包名。
### capability
``` ```
uint16_t OH_VBucket::capability uint16_t OH_VBucket::capability
...@@ -939,7 +957,6 @@ uint16_t OH_VBucket::capability ...@@ -939,7 +957,6 @@ uint16_t OH_VBucket::capability
### clear [1/2] ### clear [1/2]
``` ```
OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates)
``` ```
...@@ -965,7 +982,6 @@ OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates) ...@@ -965,7 +982,6 @@ OH_Predicates*(* OH_Predicates::clear) (OH_Predicates *predicates)
### clear [2/2] ### clear [2/2]
``` ```
int(* OH_VBucket::clear) (OH_VBucket *bucket) int(* OH_VBucket::clear) (OH_VBucket *bucket)
``` ```
...@@ -989,11 +1005,21 @@ int(* OH_VBucket::clear) (OH_VBucket *bucket) ...@@ -989,11 +1005,21 @@ int(* OH_VBucket::clear) (OH_VBucket *bucket)
[OH_VBucket](_o_h___v_bucket.md). [OH_VBucket](_o_h___v_bucket.md).
### close ### dataBaseDir
```
const char* OH_Rdb_Config::dataBaseDir
```
**描述:**
数据库文件路径。
### destroy [1/4]
``` ```
int(* OH_Cursor::close) (OH_Cursor *cursor) int(* OH_Cursor::destroy) (OH_Cursor *cursor)
``` ```
**描述:** **描述:**
...@@ -1015,11 +1041,10 @@ int(* OH_Cursor::close) (OH_Cursor *cursor) ...@@ -1015,11 +1041,10 @@ int(* OH_Cursor::close) (OH_Cursor *cursor)
[OH_Cursor](_o_h___cursor.md). [OH_Cursor](_o_h___cursor.md).
### destroyPredicates ### destroy [2/4]
``` ```
int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates) int(* OH_Predicates::destroy) (OH_Predicates *predicates)
``` ```
**描述:** **描述:**
...@@ -1041,22 +1066,21 @@ int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates) ...@@ -1041,22 +1066,21 @@ int(* OH_Predicates::destroyPredicates) (OH_Predicates *predicates)
[OH_Predicates](_o_h___predicates.md). [OH_Predicates](_o_h___predicates.md).
### destroyValueObject ### destroy [3/4]
``` ```
int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject) int(* OH_VBucket::destroy) (OH_VBucket *bucket)
``` ```
**描述:** **描述:**
销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。 销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| valueObject | 表示指向[OH_VObject](_o_h___v_object.md)实例的指针。 | | bucket | 表示指向[OH_VBucket](_o_h___v_bucket.md)实例的指针。 |
**返回:** **返回:**
...@@ -1064,25 +1088,24 @@ int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject) ...@@ -1064,25 +1088,24 @@ int(* OH_VObject::destroyValueObject) (OH_VObject *valueObject)
**参见:** **参见:**
[OH_VObject](_o_h___v_object.md). [OH_VBucket](_o_h___v_bucket.md).
### destroyValuesBucket
### destroy [4/4]
``` ```
int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket) int(* OH_VObject::destroy) (OH_VObject *valueObject)
``` ```
**描述:** **描述:**
销毁[OH_VBucket](_o_h___v_bucket.md)对象,并回收该对象占用的内存。 销毁[OH_VObject](_o_h___v_object.md)对象,并回收该对象占用的内存。
**参数:** **参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| bucket | 表示指向[OH_VBucket](_o_h___v_bucket.md)实例的指针。 | | valueObject | 表示指向[OH_VObject](_o_h___v_object.md)实例的指针。 |
**返回:** **返回:**
...@@ -1090,12 +1113,11 @@ int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket) ...@@ -1090,12 +1113,11 @@ int(* OH_VBucket::destroyValuesBucket) (OH_VBucket *bucket)
**参见:** **参见:**
[OH_VBucket](_o_h___v_bucket.md). [OH_VObject](_o_h___v_object.md).
### distinct ### distinct
``` ```
OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates)
``` ```
...@@ -1123,7 +1145,6 @@ OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates) ...@@ -1123,7 +1145,6 @@ OH_Predicates*(* OH_Predicates::distinct) (OH_Predicates *predicates)
### endWrap ### endWrap
``` ```
OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates)
``` ```
...@@ -1151,7 +1172,6 @@ OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates) ...@@ -1151,7 +1172,6 @@ OH_Predicates*(* OH_Predicates::endWrap) (OH_Predicates *predicates)
### equalTo ### equalTo
``` ```
OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1181,7 +1201,6 @@ OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char ...@@ -1181,7 +1201,6 @@ OH_Predicates*(* OH_Predicates::equalTo) (OH_Predicates *predicates, const char
### getBlob ### getBlob
``` ```
int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char *value, int length) int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char *value, int length)
``` ```
...@@ -1210,7 +1229,6 @@ int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char ...@@ -1210,7 +1229,6 @@ int(* OH_Cursor::getBlob) (OH_Cursor *cursor, int32_t columnIndex, unsigned char
### getColumnCount ### getColumnCount
``` ```
int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count) int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count)
``` ```
...@@ -1237,7 +1255,6 @@ int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count) ...@@ -1237,7 +1255,6 @@ int(* OH_Cursor::getColumnCount) (OH_Cursor *cursor, int *count)
### getColumnIndex ### getColumnIndex
``` ```
int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *columnIndex) int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *columnIndex)
``` ```
...@@ -1265,7 +1282,6 @@ int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *colu ...@@ -1265,7 +1282,6 @@ int(* OH_Cursor::getColumnIndex) (OH_Cursor *cursor, const char *name, int *colu
### getColumnName ### getColumnName
``` ```
int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *name, int length) int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *name, int length)
``` ```
...@@ -1294,7 +1310,6 @@ int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *n ...@@ -1294,7 +1310,6 @@ int(* OH_Cursor::getColumnName) (OH_Cursor *cursor, int32_t columnIndex, char *n
### getColumnType ### getColumnType
``` ```
int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_ColumnType *columnType) int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_ColumnType *columnType)
``` ```
...@@ -1322,7 +1337,6 @@ int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_Colu ...@@ -1322,7 +1337,6 @@ int(* OH_Cursor::getColumnType) (OH_Cursor *cursor, int32_t columnIndex, OH_Colu
### getInt64 ### getInt64
``` ```
int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *value) int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *value)
``` ```
...@@ -1350,7 +1364,6 @@ int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *val ...@@ -1350,7 +1364,6 @@ int(* OH_Cursor::getInt64) (OH_Cursor *cursor, int32_t columnIndex, int64_t *val
### getReal ### getReal
``` ```
int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value) int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value)
``` ```
...@@ -1378,7 +1391,6 @@ int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value ...@@ -1378,7 +1391,6 @@ int(* OH_Cursor::getReal) (OH_Cursor *cursor, int32_t columnIndex, double *value
### getRowCount ### getRowCount
``` ```
int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count) int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count)
``` ```
...@@ -1405,7 +1417,6 @@ int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count) ...@@ -1405,7 +1417,6 @@ int(* OH_Cursor::getRowCount) (OH_Cursor *cursor, int *count)
### getSize ### getSize
``` ```
int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size) int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size)
``` ```
...@@ -1433,7 +1444,6 @@ int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size) ...@@ -1433,7 +1444,6 @@ int(* OH_Cursor::getSize) (OH_Cursor *cursor, int32_t columnIndex, size_t *size)
### getText ### getText
``` ```
int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, int length) int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, int length)
``` ```
...@@ -1462,7 +1472,6 @@ int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value, ...@@ -1462,7 +1472,6 @@ int(* OH_Cursor::getText) (OH_Cursor *cursor, int32_t columnIndex, char *value,
### goToNextRow ### goToNextRow
``` ```
int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor) int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor)
``` ```
...@@ -1488,7 +1497,6 @@ int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor) ...@@ -1488,7 +1497,6 @@ int(* OH_Cursor::goToNextRow) (OH_Cursor *cursor)
### greaterThan ### greaterThan
``` ```
OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1518,7 +1526,6 @@ OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const c ...@@ -1518,7 +1526,6 @@ OH_Predicates*(* OH_Predicates::greaterThan) (OH_Predicates *predicates, const c
### greaterThanOrEqualTo ### greaterThanOrEqualTo
``` ```
OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1548,7 +1555,6 @@ OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates ...@@ -1548,7 +1555,6 @@ OH_Predicates*(* OH_Predicates::greaterThanOrEqualTo) (OH_Predicates *predicates
### groupBy ### groupBy
``` ```
OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const *const *fields, int length) OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const *const *fields, int length)
``` ```
...@@ -1578,7 +1584,6 @@ OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const ...@@ -1578,7 +1584,6 @@ OH_Predicates*(* OH_Predicates::groupBy) (OH_Predicates *predicates, char const
### id [1/4] ### id [1/4]
``` ```
int64_t OH_Predicates::id int64_t OH_Predicates::id
``` ```
...@@ -1590,7 +1595,6 @@ OH_Predicates结构体的唯一标识符。 ...@@ -1590,7 +1595,6 @@ OH_Predicates结构体的唯一标识符。
### id [2/4] ### id [2/4]
``` ```
int64_t OH_VObject::id int64_t OH_VObject::id
``` ```
...@@ -1602,7 +1606,6 @@ OH_VObject结构体的唯一标识符。 ...@@ -1602,7 +1606,6 @@ OH_VObject结构体的唯一标识符。
### id [3/4] ### id [3/4]
``` ```
int64_t OH_VBucket::id int64_t OH_VBucket::id
``` ```
...@@ -1614,7 +1617,6 @@ OH_VBucket结构体的唯一标识符。 ...@@ -1614,7 +1617,6 @@ OH_VBucket结构体的唯一标识符。
### id [4/4] ### id [4/4]
``` ```
int64_t OH_Rdb_Store::id int64_t OH_Rdb_Store::id
``` ```
...@@ -1626,7 +1628,6 @@ OH_Rdb_Store结构体的唯一标识符。 ...@@ -1626,7 +1628,6 @@ OH_Rdb_Store结构体的唯一标识符。
### in ### in
``` ```
OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1656,7 +1657,6 @@ OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *fiel ...@@ -1656,7 +1657,6 @@ OH_Predicates*(* OH_Predicates::in) (OH_Predicates *predicates, const char *fiel
### isEncrypt ### isEncrypt
``` ```
bool OH_Rdb_Config::isEncrypt bool OH_Rdb_Config::isEncrypt
``` ```
...@@ -1668,7 +1668,6 @@ bool OH_Rdb_Config::isEncrypt ...@@ -1668,7 +1668,6 @@ bool OH_Rdb_Config::isEncrypt
### isNotNull ### isNotNull
``` ```
OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const char *field) OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const char *field)
``` ```
...@@ -1697,7 +1696,6 @@ OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const cha ...@@ -1697,7 +1696,6 @@ OH_Predicates*(* OH_Predicates::isNotNull) (OH_Predicates *predicates, const cha
### isNull [1/2] ### isNull [1/2]
``` ```
int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull) int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull)
``` ```
...@@ -1725,7 +1723,6 @@ int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull) ...@@ -1725,7 +1723,6 @@ int(* OH_Cursor::isNull) (OH_Cursor *cursor, int32_t columnIndex, bool *isNull)
### isNull [2/2] ### isNull [2/2]
``` ```
OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char *field) OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char *field)
``` ```
...@@ -1754,7 +1751,6 @@ OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char * ...@@ -1754,7 +1751,6 @@ OH_Predicates*(* OH_Predicates::isNull) (OH_Predicates *predicates, const char *
### lessThan ### lessThan
``` ```
OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1784,7 +1780,6 @@ OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char ...@@ -1784,7 +1780,6 @@ OH_Predicates*(* OH_Predicates::lessThan) (OH_Predicates *predicates, const char
### lessThanOrEqualTo ### lessThanOrEqualTo
``` ```
OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1814,7 +1809,6 @@ OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, c ...@@ -1814,7 +1809,6 @@ OH_Predicates*(* OH_Predicates::lessThanOrEqualTo) (OH_Predicates *predicates, c
### like ### like
``` ```
OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1844,7 +1838,6 @@ OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *fi ...@@ -1844,7 +1838,6 @@ OH_Predicates*(* OH_Predicates::like) (OH_Predicates *predicates, const char *fi
### limit ### limit
``` ```
OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int value) OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int value)
``` ```
...@@ -1871,9 +1864,19 @@ OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int ...@@ -1871,9 +1864,19 @@ OH_Predicates*(* OH_Predicates::limit) (OH_Predicates *predicates, unsigned int
[OH_Predicates](_o_h___predicates.md). [OH_Predicates](_o_h___predicates.md).
### notBetween ### moduleName
```
const char* OH_Rdb_Config::moduleName
```
**描述:**
应用模块名。
### notBetween
``` ```
OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1903,7 +1906,6 @@ OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const ch ...@@ -1903,7 +1906,6 @@ OH_Predicates*(* OH_Predicates::notBetween) (OH_Predicates *predicates, const ch
### notEqualTo ### notEqualTo
``` ```
OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1933,7 +1935,6 @@ OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const ch ...@@ -1933,7 +1935,6 @@ OH_Predicates*(* OH_Predicates::notEqualTo) (OH_Predicates *predicates, const ch
### notIn ### notIn
``` ```
OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject) OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *field, OH_VObject *valueObject)
``` ```
...@@ -1963,7 +1964,6 @@ OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *f ...@@ -1963,7 +1964,6 @@ OH_Predicates*(* OH_Predicates::notIn) (OH_Predicates *predicates, const char *f
### offset ### offset
``` ```
OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int rowOffset) OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int rowOffset)
``` ```
...@@ -1992,7 +1992,6 @@ OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int ...@@ -1992,7 +1992,6 @@ OH_Predicates*(* OH_Predicates::offset) (OH_Predicates *predicates, unsigned int
### orderBy ### orderBy
``` ```
OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char *field, OH_OrderType type) OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char *field, OH_OrderType type)
``` ```
...@@ -2022,7 +2021,6 @@ OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char ...@@ -2022,7 +2021,6 @@ OH_Predicates*(* OH_Predicates::orderBy) (OH_Predicates *predicates, const char
### orOperate ### orOperate
``` ```
OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates) OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates)
``` ```
...@@ -2048,21 +2046,8 @@ OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates) ...@@ -2048,21 +2046,8 @@ OH_Predicates*(* OH_Predicates::orOperate) (OH_Predicates *predicates)
[OH_Predicates](_o_h___predicates.md). [OH_Predicates](_o_h___predicates.md).
### path
```
const char* OH_Rdb_Config::path
```
**描述:**
数据库文件路径。
### putBlob ### putBlob
``` ```
int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t *value, uint32_t size) int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t *value, uint32_t size)
``` ```
...@@ -2091,7 +2076,6 @@ int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t ...@@ -2091,7 +2076,6 @@ int(* OH_VBucket::putBlob) (OH_VBucket *bucket, const char *field, const uint8_t
### putDouble ### putDouble
``` ```
int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t count) int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t count)
``` ```
...@@ -2119,7 +2103,6 @@ int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t c ...@@ -2119,7 +2103,6 @@ int(* OH_VObject::putDouble) (OH_VObject *valueObject, double *value, uint32_t c
### putInt64 [1/2] ### putInt64 [1/2]
``` ```
int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t value) int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t value)
``` ```
...@@ -2147,7 +2130,6 @@ int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t valu ...@@ -2147,7 +2130,6 @@ int(* OH_VBucket::putInt64) (OH_VBucket *bucket, const char *field, int64_t valu
### putInt64 [2/2] ### putInt64 [2/2]
``` ```
int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t count) int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t count)
``` ```
...@@ -2175,7 +2157,6 @@ int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t c ...@@ -2175,7 +2157,6 @@ int(* OH_VObject::putInt64) (OH_VObject *valueObject, int64_t *value, uint32_t c
### putNull ### putNull
``` ```
int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field) int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field)
``` ```
...@@ -2202,14 +2183,13 @@ int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field) ...@@ -2202,14 +2183,13 @@ int(* OH_VBucket::putNull) (OH_VBucket *bucket, const char *field)
### putReal ### putReal
``` ```
int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value) int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value)
``` ```
**描述:** **描述:**
将double值放入给定列名的**OH_VBucket}对象中。** 将double值放入给定列名的[OH_VBucket](_o_h___v_bucket.md)对象中。
**参数:** **参数:**
...@@ -2230,7 +2210,6 @@ int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value) ...@@ -2230,7 +2210,6 @@ int(* OH_VBucket::putReal) (OH_VBucket *bucket, const char *field, double value)
### putText [1/2] ### putText [1/2]
``` ```
int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *value) int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *value)
``` ```
...@@ -2258,7 +2237,6 @@ int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *v ...@@ -2258,7 +2237,6 @@ int(* OH_VBucket::putText) (OH_VBucket *bucket, const char *field, const char *v
### putText [2/2] ### putText [2/2]
``` ```
int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value) int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value)
``` ```
...@@ -2285,7 +2263,6 @@ int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value) ...@@ -2285,7 +2263,6 @@ int(* OH_VObject::putText) (OH_VObject *valueObject, const char *value)
### putTexts ### putTexts
``` ```
int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32_t count) int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32_t count)
``` ```
...@@ -2313,11 +2290,21 @@ int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32 ...@@ -2313,11 +2290,21 @@ int(* OH_VObject::putTexts) (OH_VObject *valueObject, const char **value, uint32
### securityLevel ### securityLevel
``` ```
enum OH_Rdb_SecurityLevel OH_Rdb_Config::securityLevel int OH_Rdb_Config::securityLevel
``` ```
**描述:** **描述:**
设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel) 设置数据库安全级别[OH_Rdb_SecurityLevel](#oh_rdb_securitylevel)
### selfSize
```
int OH_Rdb_Config::selfSize
```
**描述:**
该结构体的大小。
# Image # Image
提供获取pixelmap的数据和信息的接口方法。 ## 概述
@Syscap SystemCapability.Multimedia.Image 提供访问Image接口的方法,包括如何获取图片数据、获取PixelMap的数据和信息。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:** **起始版本:**
8 8
...@@ -17,686 +17,4092 @@ ...@@ -17,686 +17,4092 @@
### 文件 ### 文件
| 文件名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。 <br>**引用文件**<multimedia/image_framework/image_pixel_map_napi.h> <br>**库**:libpixelmap_ndk.z.so| | [image_mdk.h](image__mdk_8h.md) | 声明访问图像剪辑矩形、大小、格式和组件数据的函数。<br/>**引用文件**&lt;multimedia/image_framework/image_mdk.h&gt;<br/>**库**:libimage_ndk.z.so |
| [image_mdk_common.h](image__mdk__common_8h.md) | 声明图像常用的枚举值和结构体。<br/>**引用文件**&lt;multimedia/image_framework/image_mdk_common.h&gt;<br/>**库**:libimage_ndk.z.so |
| [image_pixel_map_mdk.h](image__pixel__map__mdk_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。<br/>**引用文件**&lt;multimedia/image_framework/image_pixel_map_mdk.h&gt;<br/>**库**:libpixelmap_ndk.z.so |
| [image_pixel_map_napi.h](image__pixel__map__napi_8h.md) | 声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。<br/>**引用文件**&lt;multimedia/image_framework/image_pixel_map_napi.h&gt;<br/>**库**:libpixelmap_ndk.z.so |
| [image_receiver_mdk.h](image__receiver__mdk_8h.md) | 声明从native层获取图片数据的方法。<br/>**引用文件**&lt;multimedia/image_framework/image_receiver_mdk.h&gt;<br/>**库**:libimage_receiver_ndk.z.so |
| [image_source_mdk.h](image__source__mdk_8h.md) | 声明将图片源解码成像素位图的方法。<br/>**引用文件**&lt;multimedia/image_framework/image_source_mdk.h&gt;<br/>**库**:libimage_source_ndk.z.so |
### 结构体 ### 结构体
| 结构体名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 | | [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) | 定义图像矩形信息。 |
| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。| | [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) | 定义图像组成信息。 |
| [OhosImageSize](_ohos_image_size.md) | 定义图像大小。 |
| [OhosPixelMapInfos](_ohos_pixel_map_infos.md) | 用于定义 pixel map 的相关信息。 |
| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 |
| [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 |
| [OhosImageReceiverInfo](_ohos_image_receiver_info.md) | 定义**ImageReceiver**的相关信息。 |
| [OhosImageRegion](_ohos_image_region.md) | 定义图像源解码的范围选项。 |
| [OhosImageSourceOps](_ohos_image_source_ops.md) | 定义图像源选项信息。 |
| [OhosImageDecodingOps](_ohos_image_decoding_ops.md) | 定义图像源解码选项。 |
| [OhosImageSourceInfo](_ohos_image_source_info.md) | 定义图像源信息。 |
| [OhosImageSource](_ohos_image_source.md) | 定义图像源输入资源,每次仅接收一种类型。 |
| [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) | 定义图像源延迟时间列表。 |
| [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) | 定义图像源支持的格式字符串。 |
| [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) | 定义图像源支持的格式字符串列表。 |
| [OhosImageSourceProperty](_ohos_image_source_property.md) | 定义图像源属性键值字符串。 |
| [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) | 定义图像源更新数据选项。 |
### 类型定义 ### 类型定义
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [NativePixelMap](#nativepixelmap) | 用于定义NativePixelMap数据类型名称。| | [OHOS::Media::ImageNative](#imagenative) | 为图像接口定义native层图像对象。 |
| [NativePixelMap](#nativepixelmap) | 定义native层pixelmap数据类型名称。 |
| [OhosPixelMapInfos](#ohospixelmapinfos) | 用于定义 pixel map 的相关信息。 |
| [ImageReceiverNative](#imagereceivernative) | 用于定义ImageReceiverNative数据类型名称。 |
| (\*[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)) () | 定义native层图片的回调方法。 |
| [ImageSourceNative](#imagesourcenative) | 为图像源方法定义native层图像源对象。 |
### 宏定义
| 名称 | 描述 |
| -------- | -------- |
| **IMAGE_RESULT_BASE** 62980096 | 接口返回值的基础值 |
### 枚举 ### 枚举
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。| | { OHOS::Media::OHOS_IMAGE_FORMAT_YCBCR_422_SP = 1000,<br/>OHOS::Media::OHOS_IMAGE_FORMAT_JPEG = 2000, } | 图像格式枚举值。 |
| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。| | { OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y = 1,<br/>OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_U = 2,<br/>OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_V = 3,<br/>OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_JPEG = 4, } | 图像组成类型枚举值。 |
| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap alpha 类型的枚举。| | [IRNdkErrCode](#irndkerrcode) {<br/>IMAGE_RESULT_SUCCESS = 0,<br/>IMAGE_RESULT_BAD_PARAMETER = -1,<br/>IMAGE_RESULT_IMAGE_RESULT_BASE = IMAGE_RESULT_BASE,<br/>IMAGE_RESULT_ERR_IPC = IMAGE_RESULT_BASE + 1,<br/>IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST = IMAGE_RESULT_BASE + 2,<br/>IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL = IMAGE_RESULT_BASE + 3,<br/>IMAGE_RESULT_DECODE_ABNORMAL = IMAGE_RESULT_BASE + 4,<br/>IMAGE_RESULT_DATA_ABNORMAL = IMAGE_RESULT_BASE + 5,<br/>IMAGE_RESULT_MALLOC_ABNORMAL = IMAGE_RESULT_BASE + 6,<br/>IMAGE_RESULT_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 7,<br/>IMAGE_RESULT_INIT_ABNORMAL = IMAGE_RESULT_BASE + 8,<br/>IMAGE_RESULT_GET_DATA_ABNORMAL = IMAGE_RESULT_BASE + 9,<br/>IMAGE_RESULT_TOO_LARGE = IMAGE_RESULT_BASE + 10,<br/>IMAGE_RESULT_TRANSFORM = IMAGE_RESULT_BASE + 11,<br/>IMAGE_RESULT_COLOR_CONVERT = IMAGE_RESULT_BASE + 12,<br/>IMAGE_RESULT_CROP = IMAGE_RESULT_BASE + 13,<br/>IMAGE_RESULT_SOURCE_DATA = IMAGE_RESULT_BASE + 14,<br/>IMAGE_RESULT_SOURCE_DATA_INCOMPLETE = IMAGE_RESULT_BASE + 15,<br/>IMAGE_RESULT_MISMATCHED_FORMAT = IMAGE_RESULT_BASE + 16,<br/>IMAGE_RESULT_UNKNOWN_FORMAT = IMAGE_RESULT_BASE + 17,<br/>IMAGE_RESULT_SOURCE_UNRESOLVED = IMAGE_RESULT_BASE + 18,<br/>IMAGE_RESULT_INVALID_PARAMETER = IMAGE_RESULT_BASE + 19,<br/>IMAGE_RESULT_DECODE_FAILED = IMAGE_RESULT_BASE + 20,<br/>IMAGE_RESULT_PLUGIN_REGISTER_FAILED = IMAGE_RESULT_BASE + 21,<br/>IMAGE_RESULT_PLUGIN_CREATE_FAILED = IMAGE_RESULT_BASE + 22,<br/>IMAGE_RESULT_ENCODE_FAILED = IMAGE_RESULT_BASE + 23,<br/>IMAGE_RESULT_ADD_PIXEL_MAP_FAILED = IMAGE_RESULT_BASE + 24,<br/>IMAGE_RESULT_HW_DECODE_UNSUPPORT = IMAGE_RESULT_BASE + 25,<br/>IMAGE_RESULT_DECODE_HEAD_ABNORMAL = IMAGE_RESULT_BASE + 26,<br/>IMAGE_RESULT_DECODE_EXIF_UNSUPPORT = IMAGE_RESULT_BASE + 27,<br/>IMAGE_RESULT_PROPERTY_NOT_EXIST = IMAGE_RESULT_BASE + 28,<br/>IMAGE_RESULT_MEDIA_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 30,<br/>IMAGE_RESULT_MEDIA_TOO_LARGE = IMAGE_RESULT_BASE + 31,<br/>IMAGE_RESULT_MEDIA_MALLOC_FAILED = IMAGE_RESULT_BASE + 32,<br/>IMAGE_RESULT_MEDIA_END_OF_STREAM = IMAGE_RESULT_BASE + 33,<br/>IMAGE_RESULT_MEDIA_IO_ABNORMAL = IMAGE_RESULT_BASE + 34,<br/>IMAGE_RESULT_MEDIA_MALFORMED = IMAGE_RESULT_BASE + 35,<br/>IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL = IMAGE_RESULT_BASE + 36,<br/>IMAGE_RESULT_MEDIA_OUT_OF_RANGE = IMAGE_RESULT_BASE + 37,<br/>IMAGE_RESULT_MEDIA_STATUS_ABNORMAL = IMAGE_RESULT_BASE + 38,<br/>IMAGE_RESULT_MEDIA_VALUE_INVALID = IMAGE_RESULT_BASE + 39,<br/>IMAGE_RESULT_MEDIA_NULL_POINTER = IMAGE_RESULT_BASE + 40,<br/>IMAGE_RESULT_MEDIA_INVALID_OPERATION = IMAGE_RESULT_BASE + 41,<br/>IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT = IMAGE_RESULT_BASE + 42,<br/>IMAGE_RESULT_MEDIA_EARLY_PREPARE = IMAGE_RESULT_BASE + 43,<br/>IMAGE_RESULT_MEDIA_SEEK_ERR = IMAGE_RESULT_BASE + 44,<br/>IMAGE_RESULT_MEDIA_PERMISSION_DENIED = IMAGE_RESULT_BASE + 45,<br/>IMAGE_RESULT_MEDIA_DEAD_OBJECT = IMAGE_RESULT_BASE + 46,<br/>IMAGE_RESULT_MEDIA_TIMED_OUT = IMAGE_RESULT_BASE + 47,<br/>IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED = IMAGE_RESULT_BASE + 48,<br/>IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED = IMAGE_RESULT_BASE + 49,<br/>IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL = IMAGE_RESULT_BASE + 50,<br/>IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL = IMAGE_RESULT_BASE + 51,<br/>IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER = IMAGE_RESULT_BASE + 52,<br/>IMAGE_RESULT_MEDIA_INVALID_PARAM = IMAGE_RESULT_BASE + 53, IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 54,<br/>IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED = IMAGE_RESULT_BASE + 55,<br/>IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 56,<br/>IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED = IMAGE_RESULT_BASE + 57,<br/>IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST = IMAGE_RESULT_BASE + 58,<br/>IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST = IMAGE_RESULT_BASE + 59,<br/>IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST = IMAGE_RESULT_BASE + 60,<br/>IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED = IMAGE_RESULT_BASE + 61,<br/>IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR = IMAGE_RESULT_BASE + 62,<br/>IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT = IMAGE_RESULT_BASE + 63,<br/>IMAGE_RESULT_MEDIA_SOURCE_NOT_SET = IMAGE_RESULT_BASE + 64,<br/>IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 65,<br/>IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 66,<br/>IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT = IMAGE_RESULT_BASE + 67,<br/>IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT = IMAGE_RESULT_BASE + 68,<br/>IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID = IMAGE_RESULT_BASE + 69,<br/>IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND = IMAGE_RESULT_BASE + 70,<br/>IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX = IMAGE_RESULT_BASE + 71,<br/>IMAGE_RESULT_MEDIA_SET_VOLUME = IMAGE_RESULT_BASE + 72,<br/>IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW = IMAGE_RESULT_BASE + 73,<br/>IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED = IMAGE_RESULT_BASE + 74,<br/>IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 75,<br/>IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 76,<br/>IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 150,<br/>IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 151,<br/>IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY = IMAGE_RESULT_BASE + 152,<br/>IMAGE_RESULT_MEDIA_CONFIG_FAILED = IMAGE_RESULT_BASE + 153,<br/>IMAGE_RESULT_JNI_ENV_ABNORMAL = IMAGE_RESULT_BASE + 154,<br/>IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED = IMAGE_RESULT_BASE + 155,<br/>IMAGE_RESULT_CREATE_SURFACE_FAILED = IMAGE_RESULT_BASE + 156,<br/>IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED = IMAGE_RESULT_BASE + 157,<br/>IMAGE_RESULT_GET_SURFACE_FAILED = IMAGE_RESULT_BASE + 158,<br/>IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED = IMAGE_RESULT_BASE + 159,<br/>IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED = IMAGE_RESULT_BASE + 160,<br/>IMAGE_RESULT_REGISTER_LISTENER_FAILED = IMAGE_RESULT_BASE + 161,<br/>IMAGE_RESULT_REGISTER_BUFFER_FAILED = IMAGE_RESULT_BASE + 162,<br/>IMAGE_RESULT_FREAD_FAILED = IMAGE_RESULT_BASE + 163,<br/>IMAGE_RESULT_PEEK_FAILED = IMAGE_RESULT_BASE + 164,<br/>IMAGE_RESULT_SEEK_FAILED = IMAGE_RESULT_BASE + 165,<br/>IMAGE_RESULT_STREAM_SIZE_ERROR = IMAGE_RESULT_BASE + 166,<br/>IMAGE_RESULT_FILE_FD_ERROR = IMAGE_RESULT_BASE + 167,<br/>IMAGE_RESULT_FILE_DAMAGED = IMAGE_RESULT_BASE + 168,<br/>IMAGE_RESULT_CREATE_DECODER_FAILED = IMAGE_RESULT_BASE + 169,<br/>IMAGE_RESULT_CREATE_ENCODER_FAILED = IMAGE_RESULT_BASE + 170,<br/>IMAGE_RESULT_CHECK_FORMAT_ERROR = IMAGE_RESULT_BASE + 171,<br/>IMAGE_RESULT_THIRDPART_SKIA_ERROR = IMAGE_RESULT_BASE + 172,<br/>IMAGE_RESULT_HW_DECODE_FAILED = IMAGE_RESULT_BASE + 173,<br/>IMAGE_RESULT_ALLOCATER_TYPE_ERROR = IMAGE_RESULT_BASE + 174,<br/>IMAGE_RESULT_ALPHA_TYPE_ERROR = IMAGE_RESULT_BASE + 175,<br/>IMAGE_RESULT_INDEX_INVALID = IMAGE_RESULT_BASE + 176,<br/>IMAGE_RESULT_MEDIA_UNKNOWN = IMAGE_RESULT_BASE + 200<br/>} | 可能出现的返回值的枚举。 |
| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。| | { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0,<br/>OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1,<br/>OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2,<br/>OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap 透明度类型的枚举。 |
| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。| | { OHOS_PIXEL_MAP_READ_ONLY = 0,<br/>OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。 |
| { OHOS::Media::OHOS_IMAGE_RESULT_SUCCESS = 0,<br/>OHOS::Media::OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。 |
| { OHOS::Media::OHOS_PIXEL_MAP_FORMAT_NONE = 0,<br/>OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3,<br/>OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。 |
| { OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0,<br/>OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。 |
### 函数 ### 函数
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。| | [OHOS::Media::OH_Image_InitImageNative](#oh_image_initimagenative) (napi_env env, napi_value source) | 从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。 |
| [OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。| | [OHOS::Media::OH_Image_ClipRect](#oh_image_cliprect) (const [ImageNative](#imagenative) \*native, struct [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) \*rect) | 获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。 |
| [OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](#oh_accesspixels)。| | [OHOS::Media::OH_Image_Size](#oh_image_size) (const [ImageNative](#imagenative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。 |
| [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。| | [OHOS::Media::OH_Image_Format](#oh_image_format) (const [ImageNative](#imagenative) \*native, int32_t \*format) | 获取native **ImageNative** 对象的图像格式。 |
| [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。| | [OHOS::Media::OH_Image_GetComponent](#oh_image_getcomponent) (const [ImageNative](#imagenative) \*native, int32_t componentType, struct [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) \*componentNative) | 从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)。 |
| [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。| | [OHOS::Media::OH_Image_Release](#oh_image_release) ([ImageNative](#imagenative) \*native) | 释放 **ImageNative** native对象。 |
| [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。| | [OH_PixelMap_CreatePixelMap](#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 |
| [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*[editable](image__pixel__map__napi_8h.md#editable)) | 获取**PixelMap**对象是否可编辑的状态。| | [OH_PixelMap_CreateAlphaPixelMap](#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 |
| [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。| | [OH_PixelMap_InitNativePixelMap](#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 |
| [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。| | [OH_PixelMap_GetBytesNumberPerRow](#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 |
| [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。| | [OH_PixelMap_GetIsEditable](#oh_pixelmap_getiseditable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*editable) | 获取**PixelMap**对象是否可编辑的状态。 |
| [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。| | [OH_PixelMap_IsSupportAlpha](#oh_pixelmap_issupportalpha) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 |
| [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。| | [OH_PixelMap_SetAlphaAble](#oh_pixelmap_setalphaable) (const [NativePixelMap](#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 |
| [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。| | [OH_PixelMap_GetDensity](#oh_pixelmap_getdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 |
| [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。| | [OH_PixelMap_SetDensity](#oh_pixelmap_setdensity) (const [NativePixelMap](#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 |
| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。| | [OH_PixelMap_SetOpacity](#oh_pixelmap_setopacity) (const [NativePixelMap](#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 |
| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。| | [OH_PixelMap_Scale](#oh_pixelmap_scale) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 |
| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](image__pixel__map__napi_8h.md#width), int32_t [height](image__pixel__map__napi_8h.md#height)) | 设置**PixelMap**对象的裁剪。| | [OH_PixelMap_Translate](#oh_pixelmap_translate) (const [NativePixelMap](#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 |
| [OH_PixelMap_Rotate](#oh_pixelmap_rotate) (const [NativePixelMap](#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 |
| [OH_PixelMap_Flip](#oh_pixelmap_flip) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 |
| [OH_PixelMap_Crop](#oh_pixelmap_crop) (const [NativePixelMap](#nativepixelmap) \*native, int32_t x, int32_t y, int32_t width, int32_t height) | 设置**PixelMap**对象的裁剪。 |
| [OH_PixelMap_GetImageInfo](#oh_pixelmap_getimageinfo) (const [NativePixelMap](#nativepixelmap) \*native, [OhosPixelMapInfos](_ohos_pixel_map_infos.md) \*info) | 获取**PixelMap**对象图像信息。 |
| [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels) (const [NativePixelMap](#nativepixelmap) \*native, void \*\*addr) | 获取native **PixelMap** 对象数据的内存地址,并锁定该内存。 |
| [OH_PixelMap_UnAccessPixels](#oh_pixelmap_unaccesspixels) (const [NativePixelMap](#nativepixelmap) \*native) | 释放native **PixelMap**对象数据的内存锁,用于匹配方法 [OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels)。 |
| [OHOS::Media::OH_GetImageInfo](#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。 |
| [OHOS::Media::OH_AccessPixels](#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 |
| [OHOS::Media::OH_UnAccessPixels](#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**。 |
| [OH_Image_Receiver_CreateImageReceiver](#oh_image_receiver_createimagereceiver) (napi_env env, struct [OhosImageReceiverInfo](_ohos_image_receiver_info.md) info, napi_value \*res) | 创建应用层 **ImageReceiver** 对象。 |
| [OH_Image_Receiver_InitImageReceiverNative](#oh_image_receiver_initimagereceivernative) (napi_env env, napi_value source) | 通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](#imagereceivernative)对象。 |
| [OH_Image_Receiver_GetReceivingSurfaceId](#oh_image_receiver_getreceivingsurfaceid) (const [ImageReceiverNative](#imagereceivernative) \*native, char \*id, size_t len) | 通过[ImageReceiverNative](#imagereceivernative)获取receiver的id。 |
| [OH_Image_Receiver_ReadLatestImage](#oh_image_receiver_readlatestimage) (const [ImageReceiverNative](#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](#imagereceivernative)获取最新的一张图片。 |
| [OH_Image_Receiver_ReadNextImage](#oh_image_receiver_readnextimage) (const [ImageReceiverNative](#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](#imagereceivernative)获取下一张图片。 |
| [OH_Image_Receiver_On](#oh_image_receiver_on) (const [ImageReceiverNative](#imagereceivernative) \*native, [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback) callback) | 注册一个[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。 |
| [OH_Image_Receiver_GetSize](#oh_image_receiver_getsize) (const [ImageReceiverNative](#imagereceivernative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的大小。 |
| [OH_Image_Receiver_GetCapacity](#oh_image_receiver_getcapacity) (const [ImageReceiverNative](#imagereceivernative) \*native, int32_t \*capacity) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的容量。 |
| [OH_Image_Receiver_GetFormat](#oh_image_receiver_getformat) (const [ImageReceiverNative](#imagereceivernative) \*native, int32_t \*format) | 通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的格式。 |
| [OH_Image_Receiver_Release](#oh_image_receiver_release) ([ImageReceiverNative](#imagereceivernative) \*native) | 释放native层 [ImageReceiverNative](#imagereceivernative) 对象。注意: 此方法不能释放应用层**ImageReceiver**对象。 |
| [OH_ImageSource_Create](#oh_imagesource_create) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*src, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的信息[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API**ImageSource**对象。 |
| [OH_ImageSource_CreateIncremental](#oh_imagesource_createincremental) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*source, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的infomations[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过OH_ImageSource_UpdateData更新。 |
| [OH_ImageSource_GetSupportedFormats](#oh_imagesource_getsupportedformats) (struct [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) \*res) | 获取所有支持的解码格式元标记。 |
| [OH_ImageSource_InitNative](#oh_imagesource_initnative) (napi_env env, napi_value source) | 从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](#imagesourcenative)值。 |
| [OH_ImageSource_CreatePixelMap](#oh_imagesource_createpixelmap) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象 |
| [OH_ImageSource_CreatePixelMapList](#oh_imagesource_createpixelmaplist) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表 |
| [OH_ImageSource_GetDelayTime](#oh_imagesource_getdelaytime) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) \*res) | 从一些**ImageSource**(如GIF图像源)获取延迟时间列表。 |
| [OH_ImageSource_GetFrameCount](#oh_imagesource_getframecount) (const [ImageSourceNative](#imagesourcenative) \*native, uint32_t \*res) | 从**ImageSource**中获取帧计数。 |
| [OH_ImageSource_GetImageInfo](#oh_imagesource_getimageinfo) (const [ImageSourceNative](#imagesourcenative) \*native, int32_t index, struct [OhosImageSourceInfo](_ohos_image_source_info.md) \*info) | 通过索引从**ImageSource**获取图像源信息。 |
| [OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字从**ImageSource**中获取图像源属性。 |
| [OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字为**ImageSource**修改图像源属性。 |
| [OH_ImageSource_UpdateData](#oh_imagesource_updatedata) (const [ImageSourceNative](#imagesourcenative) \*native, struct [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) \*data) | 为了增量类型的**ImageSource**更新源数据。 |
| [OH_ImageSource_Release](#oh_imagesource_release) ([ImageSourceNative](#imagesourcenative) \*native) | 释放native层图像源 **ImageSourceNative**。 |
### 变量
| 名称 | 描述 |
| -------- | -------- |
| [OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE](#ohos_image_property_bits_per_sample) = "BitsPerSample" | 定义每个样本比特的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_ORIENTATION](#ohos_image_property_orientation) = "Orientation" | 定义方向的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_IMAGE_LENGTH](#ohos_image_property_image_length) = "ImageLength" | 定义图像长度的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_IMAGE_WIDTH](#ohos_image_property_image_width) = "ImageWidth" | 定义图像宽度的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_GPS_LATITUDE](#ohos_image_property_gps_latitude) = "GPSLatitude" | 定义GPS纬度的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_GPS_LONGITUDE](#ohos_image_property_gps_longitude) = "GPSLongitude" | 定义GPS经度的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF](#ohos_image_property_gps_latitude_ref) = "GPSLatitudeRef" | 定义GPS纬度参考的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF](#ohos_image_property_gps_longitude_ref) = "GPSLongitudeRef" | 定义GPS经度参考的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL](#ohos_image_property_date_time_original) = "DateTimeOriginal" | 定义初始日期时间的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_EXPOSURE_TIME](#ohos_image_property_exposure_time) = "ExposureTime" | 定义曝光时间的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_SCENE_TYPE](#ohos_image_property_scene_type) = "SceneType" | 定义场景类型的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS](#ohos_image_property_iso_speed_ratings) = "ISOSpeedRatings" | 定义ISO速度等级的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_F_NUMBER](#ohos_image_property_f_number) = "FNumber" | 定义FNumber的图像属性关键字。 |
| [OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL](#ohos_image_property_compressed_bits_per_pixel) = "CompressedBitsPerPixel" | 定义每个像素的压缩比特的图像属性关键字。 |
| [OhosImageRegion::x](#x) | 起始x坐标,用pixels表示 |
| [OhosImageRegion::y](#y) | 起始y坐标,用pixels表示 |
| [OhosImageRegion::width](#width) | 宽度范围,用pixels表示 |
| [OhosImageRegion::height](#height) | 高度范围,用pixels表示 |
| [OhosImageSourceOps::density](#density-12) | 图像源像素密度 |
| [OhosImageSourceOps::pixelFormat](#pixelformat-13) | 图像源像素格式,通常用于描述YUV缓冲区 |
| [OhosImageSourceOps::size](#size-17) | 图像源像素宽高的大小 |
| [OhosImageDecodingOps::editable](#editable) | 定义输出的像素位图是否可编辑 |
| [OhosImageDecodingOps::pixelFormat](#pixelformat-23) | 定义输出的像素格式 |
| [OhosImageDecodingOps::fitDensity](#fitdensity) | 定义解码目标的像素密度 |
| [OhosImageDecodingOps::index](#index) | 定义图像源解码指数 |
| [OhosImageDecodingOps::sampleSize](#samplesize) | 定义解码样本大小选项 |
| [OhosImageDecodingOps::rotate](#rotate) | 定义解码旋转选项 |
| [OhosImageDecodingOps::size](#size-27) | 定义解码目标像素宽高的大小 |
| [OhosImageDecodingOps::region](#region) | 定义图像源解码的像素范围 |
| [OhosImageSourceInfo::pixelFormat](#pixelformat-33) | 图像源像素格式, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 |
| [OhosImageSourceInfo::colorSpace](#colorspace) | 图像源色彩空间 |
| [OhosImageSourceInfo::alphaType](#alphatype) | 图像源透明度类型 |
| [OhosImageSourceInfo::density](#density-22) | 图像源密度, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置 |
| [OhosImageSourceInfo::size](#size-37) | 图像源像素宽高的大小 |
| [OhosImageSource::uri](#uri) = nullptr | 图像源资源标识符,接受文件资源或者base64资源 |
| [OhosImageSource::uriSize](#urisize) = 0 | 图像源资源长度 |
| [OhosImageSource::fd](#fd) = -1 | 图像源文件资源描述符 |
| [OhosImageSource::buffer](#buffer-12) = nullptr | 图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区 |
| [OhosImageSource::bufferSize](#buffersize-12) = 0 | 图像源缓冲区资源大小 |
| [OhosImageSourceDelayTimeList::delayTimeList](#delaytimelist) | 图像源延迟时间列表头地址 |
| [OhosImageSourceDelayTimeList::size](#size-47) = 0 | 图像源延迟时间列表大小 |
| [OhosImageSourceSupportedFormat::format](#format) = nullptr | 图像源支持的格式字符串头地址 |
| [OhosImageSourceSupportedFormat::size](#size-57) = 0 | 图像源支持的格式字符串大小 |
| [OhosImageSourceSupportedFormatList::supportedFormatList](#supportedformatlist) = nullptr | 图像源支持的格式字符串列表头地址 |
| [OhosImageSourceSupportedFormatList::size](#size-67) = 0 | 图像源支持的格式字符串列表大小 |
| [OhosImageSourceProperty::value](#value) = nullptr | 定义图像源属性键值字符串头地址 |
| [OhosImageSourceProperty::size](#size-77) = 0 | 定义图像源属性键值字符串大小 |
| [OhosImageSourceUpdateData::buffer](#buffer-22) = nullptr | 图像源更新数据缓冲区 |
| [OhosImageSourceUpdateData::bufferSize](#buffersize-22) = 0 | 图像源更新数据缓冲区大小 |
| [OhosImageSourceUpdateData::offset](#offset) = 0 | 图像源更新数据缓冲区的开端 |
| [OhosImageSourceUpdateData::updateLength](#updatelength) = 0 | 图像源更新数据缓冲区的更新数据长度 |
| [OhosImageSourceUpdateData::isCompleted](#iscompleted) = 0 | 图像源更新数据在此节中完成 |
## 类型定义说明 ## 类型定义说明
### NativePixelMap ### ImageNative
``` ```
typedef struct NativePixelMap typedef struct ImageNative_ OHOS::Media::ImageNative
``` ```
**描述:**
用于定义NativePixelMap数据类型名称。
**起始版本:** **描述:**
10
为图像接口定义native层图像对象。
## 枚举类型说明 **起始版本:**
10
### anonymous enum ### ImageReceiverNative
``` ```
anonymous enum typedef struct ImageReceiverNative_ ImageReceiverNative
``` ```
**描述:**
函数方法返回值的错误码的枚举。
| 枚举值 | 描述 | **描述:**
| -------- | -------- |
| OHOS_IMAGE_RESULT_SUCCESS| 成功的结果 | 用于定义ImageReceiverNative数据类型名称。
| OHOS_IMAGE_RESULT_BAD_PARAMETER| 无效值 |
**起始版本:** **起始版本:**
8
### anonymous enum 10
### ImageSourceNative
``` ```
anonymous enum typedef struct ImageSourceNative_ ImageSourceNative
``` ```
**描述:**
pixel 格式的枚举。
| 枚举值 | 描述 | **描述:**
| -------- | -------- |
| OHOS_PIXEL_MAP_FORMAT_NONE| 未知的格式 | 为图像源方法定义native层图像源对象。
| OHOS_PIXEL_MAP_FORMAT_RGBA_8888| 32-bit RGBA。 由 R, G, B组成,包括 A 都需要占用 8 bits。存储顺序是从高位到低位。 |
| OHOS_PIXEL_MAP_FORMAT_RGB_565| 16-bit RGB。 仅由 R, G, B 组成. 存储顺序是从高位到低位: 红色占用5 bits,绿色占用6 bits,蓝色占用5 bits。 | \@Syscap SystemCapability.Multimedia.Image
**起始版本:** **起始版本:**
8
### anonymous enum 10
### NativePixelMap
``` ```
anonymous enum typedef struct NativePixelMap_ NativePixelMap
``` ```
**描述:**
PixelMap alpha 类型的枚举。
| 枚举值 | 描述 | **描述:**
| -------- | -------- |
| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN| 未知的格式 | 定义native层pixelmap数据类型名称。
| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE| 不透明的格式 |
| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL| 预乘的格式 | **起始版本:**
| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL| 预除的格式 |
**起始版本:**
10 10
### anonymous enum
### OH_Image_Receiver_On_Callback
``` ```
anonymous enum typedef void(* OH_Image_Receiver_On_Callback) ()
``` ```
**描述:**
PixelMap 缩放类型的枚举。
| 枚举值 | 描述 | **描述:**
| -------- | -------- |
| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE| 适应目标图片大小的格式 | 定义native层图片的回调方法。
| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP| 以中心进行缩放的格式 |
**起始版本:**
**起始版本:**
10 10
### anonymous enum ### OhosPixelMapInfos
``` ```
anonymous enum typedef struct OhosPixelMapInfosOhosPixelMapInfos
``` ```
**描述:**
PixelMap 编辑类型的枚举。
| 枚举值 | 描述 | **描述:**
| -------- | -------- |
| OHOS_PIXEL_MAP_READ_ONLY| 只读的格式 | 用于定义 pixel map 的相关信息。
| OHOS_PIXEL_MAP_EDITABLE| 可编辑的格式 |
**起始版本:**
**起始版本:**
10 10
## 函数说明 ## 枚举类型说明
### OH_AccessPixels() ### anonymous enum [1/3]
``` ```
int32_t OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr ) anonymous enum
``` ```
**描述:**
获取**PixelMap**对象数据的内存地址,并锁定该内存。
函数执行成功后,**\*addrPtr**就是获取的待访问的内存地址. 访问操作完成后,必须要使用[OH_UnAccessPixels](#oh_unaccesspixels)来释放锁, 否则的话资源无法被释放. 待解锁后,内存地址就不可以再被访问和操作。 **描述:**
**参数:** 图像格式枚举值。
| 名称 | 描述 | **起始版本:**
10
| 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| env | napi的环境指针。| | OHOS_IMAGE_FORMAT_YCBCR_422_SP | YCBCR422 semi-planar 格式 |
| value | 应用层的 **PixelMap** 对象。| | OHOS_IMAGE_FORMAT_JPEG | JPEG 编码格式 |
| addrPtr | 用于指向的内存地址的双指针对象。|
**参见:**
UnAccessPixels ### anonymous enum [2/3]
**返回:** ```
anonymous enum
```
**描述:**
操作成功则返回 OHOS_IMAGE_RESULT_SUCCESS; 如果操作失败,则返回错误码 PixelMap 透明度类型的枚举
**起始版本:** **起始版本:**
8
10
| 枚举值 | 描述 |
| -------- | -------- |
| OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN | 未知的格式 |
| OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE | 不透明的格式 |
| OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL | 预乘的格式 |
| OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL | 预除的格式 |
### OH_GetImageInfo()
### anonymous enum [3/3]
``` ```
struct OhosPixelMapCreateOps OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info ) anonymous enum
``` ```
**描述:**
获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。
**参数:** **描述:**
| 名称 | 描述 | 函数方法返回值的错误码的枚举。
| -------- | -------- |
| env | napi的环境指针。|
| value | 应用层的 **PixelMap** 对象。|
| info | 用于保存信息的指针对象. 更多细节, 参看 [OhosPixelMapInfo](_ohos_pixel_map_info.md)。|
**返回:** **起始版本:**
如果获取并保存信息成功,则返回**0**; 如果操作失败,则返回错误码。 8
**参见:** **废弃起始版本:**
[OhosPixelMapInfo](_ohos_pixel_map_info.md) 10
**起始版本:** | 枚举值 | 描述 |
8 | -------- | -------- |
| OHOS_IMAGE_RESULT_SUCCESS | 成功的结果 |
| OHOS_IMAGE_RESULT_BAD_PARAMETER | 无效值 |
### OH_PixelMap_CreateAlphaPixelMap() ### anonymous enum [1/3]
``` ```
int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha ) anonymous enum
``` ```
**描述:**
根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。
**参数:** **描述:**
| 名称 | 描述 | 图像组成类型枚举值。
**起始版本:**
10
| 枚举值 | 描述 |
| -------- | -------- | | -------- | -------- |
| env | napi的环境指针。| | OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y | 亮度信息 |
| source | **PixelMap**数据设置项。| | OHOS_IMAGE_COMPONENT_FORMAT_YUV_U | 色度信息 |
| alpha | alpha通道的指针。| | OHOS_IMAGE_COMPONENT_FORMAT_YUV_V | 色差值信息 |
| OHOS_IMAGE_COMPONENT_FORMAT_JPEG | Jpeg 格式 |
**返回:**
操作成功则返回 **PixelMap** 对象; 如果操作失败,则返回错误码。 ### anonymous enum [2/3]
**参见:** ```
anonymous enum
```
CreateAlphaPixelMap **描述:**
PixelMap 编辑类型的枚举。
**起始版本:**
**起始版本:**
10 10
| 枚举值 | 描述 |
| -------- | -------- |
| OHOS_PIXEL_MAP_READ_ONLY | 只读的格式 |
| OHOS_PIXEL_MAP_EDITABLE | 可编辑的格式 |
### OH_PixelMap_CreatePixelMap() ### anonymous enum [3/3]
``` ```
int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res ) anonymous enum
``` ```
**描述:**
创建**PixelMap**对象.
**参数:**
| 名称 | 描述 | **描述:**
| -------- | -------- |
| env | napi的环境指针。|
| info | pixel map 数据设置项。|
| buf | 图片的buffer数据。|
| len | 图片大小信息。|
| res | 应用层的 **PixelMap** 对象的指针。|
**返回:** pixel 格式的枚举。
操作成功则返回 **PixelMap** 对象; 如果操作失败,则返回错误码。 **起始版本:**
**参见:** 8
CreatePixelMap **废弃起始版本:**
**起始版本:**
10 10
| 枚举值 | 描述 |
| -------- | -------- |
| OHOS_PIXEL_MAP_FORMAT_NONE | 未知的格式 |
| OHOS_PIXEL_MAP_FORMAT_RGBA_8888 | 32-bit RGBA. 由 R, G, B组成,包括 A 都需要占用 8 bits。存储顺序是从高位到低位。 |
| OHOS_PIXEL_MAP_FORMAT_RGB_565 | 16-bit RGB. 仅由 R, G, B 组成。 存储顺序是从高位到低位: 红色占用5 bits,绿色占用6 bits,蓝色占用5 bits。 |
### OH_PixelMap_Crop() ### anonymous enum
``` ```
int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height ) anonymous enum
``` ```
**描述:**
设置**PixelMap**对象的裁剪.
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。|
| x | 目标图片左上角的x坐标。|
| y | 目标图片左上角的y坐标。|
| width | 裁剪区域的宽度。|
| height | 裁剪区域的高度。|
**返回:** **描述:**
操作成功则返回**0**; 如果操作失败,则返回错误码。
**参见:** PixelMap 缩放类型的枚举。
Crop **起始版本:**
**起始版本:**
10 10
| 枚举值 | 描述 |
| -------- | -------- |
| OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE | 适应目标图片大小的格式 |
| OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP | 以中心进行缩放的格式 |
### OH_PixelMap_Flip() ### IRNdkErrCode
``` ```
int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y ) enum IRNdkErrCode
``` ```
**描述:**
设置**PixelMap**对象的翻转.
**参数:** **描述:**
| 名称 | 描述 | 可能被使用的接口返回值的枚举。
| -------- | -------- |
| native | NativePixelMap的指针。|
| x | 根据水平方向x轴进行图片翻转。|
| y | 根据垂直方向y轴进行图片翻转。|
**返回:** **起始版本:**
操作成功则返回**0**; 如果操作失败,则返回错误码。 10
**参见:** | 枚举值 | 描述 |
| -------- | -------- |
| IMAGE_RESULT_SUCCESS | 操作成功 |
| IMAGE_RESULT_BAD_PARAMETER | 无效参数 |
| IMAGE_RESULT_IMAGE_RESULT_BASE | 操作失败 |
| IMAGE_RESULT_ERR_IPC | ipc 错误 |
| IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST | 共享内存失败 |
| IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL | 共享内存数据异常 |
| IMAGE_RESULT_DECODE_ABNORMAL | 图像解码失败 |
| IMAGE_RESULT_DATA_ABNORMAL | 图像输入数据异常 |
| IMAGE_RESULT_MALLOC_ABNORMAL | 图像内存分配异常 |
| IMAGE_RESULT_DATA_UNSUPPORT | 图像类型不支持 |
| IMAGE_RESULT_INIT_ABNORMAL | 图像初始化失败 |
| IMAGE_RESULT_GET_DATA_ABNORMAL | 图像获取数据错误 |
| IMAGE_RESULT_TOO_LARGE | 图像数据过大 |
| IMAGE_RESULT_TRANSFORM | 图像转换错误 |
| IMAGE_RESULT_COLOR_CONVERT | 图像颜色转换错误 |
| IMAGE_RESULT_CROP | 裁剪错误 |
| IMAGE_RESULT_SOURCE_DATA | 图像源数据错误 |
| IMAGE_RESULT_SOURCE_DATA_INCOMPLETE | 图像源数据不完整 |
| IMAGE_RESULT_MISMATCHED_FORMAT | 图像格式不匹配 |
| IMAGE_RESULT_UNKNOWN_FORMAT | 图像未知格式 |
| IMAGE_RESULT_SOURCE_UNRESOLVED | 图像源未解析 |
| IMAGE_RESULT_INVALID_PARAMETER | 图像无效参数 |
| IMAGE_RESULT_DECODE_FAILED | 解码失败 |
| IMAGE_RESULT_PLUGIN_REGISTER_FAILED | 注册插件失败 |
| IMAGE_RESULT_PLUGIN_CREATE_FAILED | 创建插件失败 |
| IMAGE_RESULT_ENCODE_FAILED | 图像编码失败 |
| IMAGE_RESULT_ADD_PIXEL_MAP_FAILED | 图像添加像素位图失败 |
| IMAGE_RESULT_HW_DECODE_UNSUPPORT | 图像硬解码不支持 |
| IMAGE_RESULT_DECODE_HEAD_ABNORMAL | 图像头解码失败 |
| IMAGE_RESULT_DECODE_EXIF_UNSUPPORT | 图像解码EXIF不支持 |
| IMAGE_RESULT_PROPERTY_NOT_EXIST | 图像属性不存在 |
| IMAGE_RESULT_MEDIA_DATA_UNSUPPORT | 媒体类型不支持 |
| IMAGE_RESULT_MEDIA_TOO_LARGE | 媒体数据过大 |
| IMAGE_RESULT_MEDIA_MALLOC_FAILED | 媒体分配内存失败 |
| IMAGE_RESULT_MEDIA_END_OF_STREAM | 媒体数据流结束失败 |
| IMAGE_RESULT_MEDIA_IO_ABNORMAL | 媒体输入输出流异常 |
| IMAGE_RESULT_MEDIA_MALFORMED | 媒体功能异常 |
| IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL | 媒体数据过小错误 |
| IMAGE_RESULT_MEDIA_OUT_OF_RANGE | 媒体超出范围错误 |
| IMAGE_RESULT_MEDIA_STATUS_ABNORMAL | 媒体状态异常错误 |
| IMAGE_RESULT_MEDIA_VALUE_INVALID | 媒体值无效 |
| IMAGE_RESULT_MEDIA_NULL_POINTER | 媒体操作失败 |
| IMAGE_RESULT_MEDIA_INVALID_OPERATION | 媒体操作无效 |
| IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT | 媒体初始化异常 |
| IMAGE_RESULT_MEDIA_EARLY_PREPARE | 媒体过早预处理 |
| IMAGE_RESULT_MEDIA_SEEK_ERR | 媒体查找失败 |
| IMAGE_RESULT_MEDIA_PERMISSION_DENIED | 媒体权限拒绝 |
| IMAGE_RESULT_MEDIA_DEAD_OBJECT | 媒体对象注销 |
| IMAGE_RESULT_MEDIA_TIMED_OUT | 媒体超时 |
| IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED | 媒体能力不支持 |
| IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED | 媒体适配器初始化失败 |
| IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL | 写入parcel失败 |
| IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL | 读取parcel失败 |
| IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER | 无效数据 |
| IMAGE_RESULT_MEDIA_INVALID_PARAM | 媒体接口发现无效参数 |
| IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST | 媒体代码适配器不存在 |
| IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED | 媒体创建代码适配器失败 |
| IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT | 媒体代码适配器未初始化 |
| IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED | 媒体代码创建失败 |
| IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST | 媒体代码不存在 |
| IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST | 媒体JNI层类不存在 |
| IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST | 媒体JNI层方法不存在 |
| IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED | 媒体JNI层创建对象失败 |
| IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR | 媒体JNI层异常 |
| IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT | 媒体不支持分布 |
| IMAGE_RESULT_MEDIA_SOURCE_NOT_SET | 媒体源未设置 |
| IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT | 媒体rtsp适配器未初始化 |
| IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST | 媒体rtsp适配器不存在 |
| IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT | 媒体不支持rtsp surface |
| IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT | 媒体rtsp capture初始化失败 |
| IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID | 媒体rtsp源路径无效 |
| IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND | 媒体rtsp未发现视频能力 |
| IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX | rtsp相机数量达到最大数量 |
| IMAGE_RESULT_MEDIA_SET_VOLUME | 媒体设置卷失败 |
| IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW | 媒体操作次数溢出 |
| IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED | 媒体分布式播放器不支持 |
| IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED | 图像解码ICC失败 |
| IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED | 图像编码CC失败 |
| IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED | 读取像素位图失败 |
| IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED | 写入像素位图失败 |
| IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY | 像素位图不允许修改 |
| IMAGE_RESULT_MEDIA_CONFIG_FAILED | 配置失败 |
| IMAGE_RESULT_JNI_ENV_ABNORMAL | JNI环境异常 |
| IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED | surface申请内存失败 |
| IMAGE_RESULT_CREATE_SURFACE_FAILED | 创建surface失败 |
| IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED | 从surface获取参数失败 |
| IMAGE_RESULT_GET_SURFACE_FAILED | 获取sufrace失败 |
| IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED | 申请内存失败 |
| IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED | 申请内存失败 |
| IMAGE_RESULT_REGISTER_LISTENER_FAILED | 注册监听失败 |
| IMAGE_RESULT_REGISTER_BUFFER_FAILED | 注册内存失败 |
| IMAGE_RESULT_FREAD_FAILED | 读取文件失败 |
| IMAGE_RESULT_PEEK_FAILED | 检测文件失败 |
| IMAGE_RESULT_SEEK_FAILED | 查找文件失败 |
| IMAGE_RESULT_STREAM_SIZE_ERROR | 数据流损坏 |
| IMAGE_RESULT_FILE_FD_ERROR | 文件描述符损坏 |
| IMAGE_RESULT_FILE_DAMAGED | 文件损坏 |
| IMAGE_RESULT_CREATE_DECODER_FAILED | 创建解码失败 |
| IMAGE_RESULT_CREATE_ENCODER_FAILED | 创建编码失败 |
| IMAGE_RESULT_CHECK_FORMAT_ERROR | 检查格式失败 |
| IMAGE_RESULT_THIRDPART_SKIA_ERROR | skia解码失败 |
| IMAGE_RESULT_HW_DECODE_FAILED | 硬解码失败 |
| IMAGE_RESULT_ALLOCATER_TYPE_ERROR | 内存类型校验失败 |
| IMAGE_RESULT_ALPHA_TYPE_ERROR | 透明度类型失败 |
| IMAGE_RESULT_INDEX_INVALID | 参数无效 |
| IMAGE_RESULT_MEDIA_UNKNOWN | 媒体未知错误 |
Flip
**起始版本:** ## 函数说明
10
### OH_PixelMap_GetBytesNumberPerRow() ### OH_AccessPixels()
``` ```
int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num ) int32_t OHOS::Media::OH_AccessPixels (napi_env env, napi_value value, void ** addrPtr )
``` ```
**描述:**
获取**PixelMap**对象每行字节数.
**参数:** **描述:**
获取**PixelMap**对象数据的内存地址,并锁定该内存。
函数执行成功后,**\*addrPtr**就是获取的待访问的内存地址。访问操作完成后,必须要使用**OH_UnAccessPixels**来释放锁,否则的话资源无法被释放。 待解锁后,内存地址就不可以再被访问和操作。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | env | napi的环境指针。 |
| num | **PixelMap**对象的每行字节数指针。| | value | 应用层的 **PixelMap** 对象。 |
| addrPtr | 用于指向的内存地址的双指针对象。 |
**返回:** **返回**
操作成功则返回 **PixelMap** 对象每行字节数; 如果操作失败,则返回错误码。 操作成功则返回 **OHOS_IMAGE_RESULT_SUCCESS**如果操作失败,则返回错误码。
**参见:** **起始版本:**
GetBytesNumberPerRow 8
**废弃起始版本:**
**起始版本:**
10 10
### OH_PixelMap_GetDensity() **参见:**
UnAccessPixels
### OH_GetImageInfo()
``` ```
int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density ) int32_t OHOS::Media::OH_GetImageInfo (napi_env env, napi_value value, OhosPixelMapInfo * info )
``` ```
**描述:**
获取**PixelMap**对象像素密度.
**参数:** **描述:**
获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | env | napi的环境指针。 |
| density | 像素密度指针。| | value | 应用层的 **PixelMap** 对象。 |
| info | 用于保存信息的指针对象。 更多细节, 参看 [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)。 |
**返回:** **返回:**
如果获取并保存信息成功,则返回**0**; 如果操作失败,则返回错误码。
操作成功则返回像素密度; 如果操作失败,则返回错误码。 **起始版本:**
**参见:** 8
GetDensity **废弃起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_GetIsEditable() [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)
### OH_Image_ClipRect()
``` ```
int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable ) int32_t OHOS::Media::OH_Image_ClipRect (const ImageNative * native, struct OhosImageRect * rect )
``` ```
**描述:**
获取**PixelMap**对象是否可编辑的状态.
**参数:** **描述:**
获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | 表示指向 **ImageNative** native层对象的指针。 |
| editable | **PixelMap** 对象是否可编辑的指针。| | rect | 表示作为转换结果的 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 对象指针。 |
**返回:** **返回**
操作成功则返回编辑类型的枚举值; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功返回 IMAGE_RESULT_SUCCESS ;
GetIsEditable 如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED;
如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。
**起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_InitNativePixelMap() ImageNative, [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md)
### OH_Image_Format()
``` ```
NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source ) int32_t OHOS::Media::OH_Image_Format (const ImageNative * native, int32_t * format )
``` ```
**描述:**
初始化**PixelMap**对象数据.
**参数:** **描述:**
获取native **ImageNative** 对象的图像格式。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| env | napi的环境指针。| | native | 表示 **ImageNative** native对象的指针。 |
| source | **PixelMap** 数据设置项。| | format | 表示作为转换结果的图像格式对象的指针。 |
**返回:** **返回**
操作成功则返回NativePixelMap的指针; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功返回 IMAGE_RESULT_SUCCESS ;
InitNativePixelMap 如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED;
如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。
**起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_IsSupportAlpha() ImageNative
### OH_Image_GetComponent()
``` ```
int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha ) int32_t OHOS::Media::OH_Image_GetComponent (const ImageNative * native, int32_t componentType, struct OhosImageComponent * componentNative )
``` ```
**描述:**
获取**PixelMap**对象是否支持Alpha通道.
**参数:** **描述:**
从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | 表示 **ImageNative** native对象的指针。 |
| alpha | 是否支持Alpha的指针。| | componentType | 表示所需组件的组件类型。 |
| componentNative | 表示转换结果的 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) 对象的指针。 |
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功返回 IMAGE_RESULT_SUCCESS ;
IsSupportAlpha 如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED;
如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。
**起始版本:**
**起始版本:**
10 10
**参见:**
ImageNative, [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)
### OH_PixelMap_Rotate()
### OH_Image_InitImageNative()
``` ```
int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle ) ImageNative* OHOS::Media::OH_Image_InitImageNative (napi_env env, napi_value source )
``` ```
**描述:**
设置**PixelMap**对象的旋转.
**参数:** **描述:**
从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | env | 表示指向 JNI 环境的指针。 |
| angle | 旋转角度。| | source | 表示 JavaScript Native API **图像** 对象。 |
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 如果操作成果返回 **ImageNative** 指针对象,如果操作失败返回空指针
**参见:** **起始版本:**
Rotate 10
**参见:**
ImageNative, OH_Image_Release
### OH_Image_Receiver_CreateImageReceiver()
```
int32_t OH_Image_Receiver_CreateImageReceiver (napi_env env, struct OhosImageReceiverInfo info, napi_value * res )
```
**描述:**
创建应用层 **ImageReceiver** 对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | napi的环境指针。 |
| info | **ImageReceiver** 数据设置项。 |
| res | 应用层的 **ImageReceiver** 对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ;
如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ;
如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ;
如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_Scale() [OhosImageReceiverInfo](_ohos_image_receiver_info.md)
### OH_Image_Receiver_GetCapacity()
``` ```
int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y ) int32_t OH_Image_Receiver_GetCapacity (const ImageReceiverNative * native, int32_t * capacity )
``` ```
**描述:**
设置**PixelMap**对象的缩放.
**参数:** **描述:**
通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的容量。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| x | 缩放宽度。| | capacity | 作为结果的指向容量的指针。 |
| y | 缩放高度。|
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
Scale 如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_SetAlphaAble() [ImageReceiverNative](#imagereceivernative), [OhosImageSize](_ohos_image_size.md)
### OH_Image_Receiver_GetFormat()
``` ```
int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha ) int32_t OH_Image_Receiver_GetFormat (const ImageReceiverNative * native, int32_t * format )
``` ```
**描述:**
设置**PixelMap**对象的Alpha通道.
**参数:** **描述:**
通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的格式。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| alpha | Alpha通道。| | format | 作为结果的指向格式的指针。 |
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
SetAlphaAble 如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
### OH_PixelMap_SetDensity() [ImageReceiverNative](#imagereceivernative)
### OH_Image_Receiver_GetReceivingSurfaceId()
``` ```
int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density ) int32_t OH_Image_Receiver_GetReceivingSurfaceId (const ImageReceiverNative * native, char * id, size_t len )
``` ```
**描述:**
设置**PixelMap**对象像素密度.
**参数:** **描述:**
通过[ImageReceiverNative](#imagereceivernative)获取receiver的id。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| density | 像素密度。| | id | 指向字符缓冲区的指针,用于获取字符串的id。 |
| len | **id**所对应的字符缓冲区的大小。 |
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
GetDensity 如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
[ImageReceiverNative](#imagereceivernative)
### OH_PixelMap_SetOpacity()
### OH_Image_Receiver_GetSize()
``` ```
int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity ) int32_t OH_Image_Receiver_GetSize (const ImageReceiverNative * native, struct OhosImageSize * size )
``` ```
**描述:**
设置**PixelMap**对象的透明度.
**参数:** **描述:**
通过[ImageReceiverNative](#imagereceivernative)获取**ImageReceiver**的大小。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| opacity | 透明度。| | size | 作为结果的[OhosImageSize](_ohos_image_size.md)指针。 |
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
SetOpacity 如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
[ImageReceiverNative](#imagereceivernative), [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)
### OH_PixelMap_Translate()
### OH_Image_Receiver_InitImageReceiverNative()
``` ```
int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y ) ImageReceiverNative* OH_Image_Receiver_InitImageReceiverNative (napi_env env, napi_value source )
``` ```
**描述:**
设置**PixelMap**对象的偏移.
**参数:** **描述:**
通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](#imagereceivernative)对象。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| native | NativePixelMap的指针。| | env | napi的环境指针。 |
| x | 水平偏移量。| | source | napi的 **ImageReceiver** 对象。 |
| y | 垂直偏移量。|
**返回:** **返回**
操作成功则返回**0**; 如果操作失败,则返回错误码 操作成功则返回 [ImageReceiverNative](#imagereceivernative) 指针;如果操作失败,则返回nullptr
**参见:** **起始版本:**
Translate 10
**参见:**
[ImageReceiverNative](#imagereceivernative), [OH_Image_Receiver_Release](#oh_image_receiver_release)
### OH_Image_Receiver_On()
```
int32_t OH_Image_Receiver_On (const ImageReceiverNative * native, OH_Image_Receiver_On_Callback callback )
```
**描述:**
注册一个[OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| callback | [OH_Image_Receiver_On_Callback](#oh_image_receiver_on_callback)事件的回调函数。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。
**起始版本:**
**起始版本:**
10 10
**参见:**
[ImageReceiverNative](#imagereceivernative)
### OH_UnAccessPixels()
### OH_Image_Receiver_ReadLatestImage()
``` ```
int32_t OH_UnAccessPixels (napi_env env, napi_value value ) int32_t OH_Image_Receiver_ReadLatestImage (const ImageReceiverNative * native, napi_value * image )
``` ```
**描述:**
释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](#oh_accesspixels).
**参数:** **描述:**
通过[ImageReceiverNative](#imagereceivernative)获取最新的一张图片。
**参数:**
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| env | napi的环境指针。| | native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| value | 应用层的 **PixelMap** 对象。| | image | 获取到的应用层的 **Image** 指针对象。 |
**返回:** **返回**
操作成功则返回 OHOS_IMAGE_RESULT_SUCCESS; 如果操作失败,则返回错误码 参考[IRNdkErrCode](#irndkerrcode)
**参见:** 如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
AccessPixels 如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ;
如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ;
如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ;
如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
[ImageReceiverNative](#imagereceivernative)
### OH_Image_Receiver_ReadNextImage()
```
int32_t OH_Image_Receiver_ReadNextImage (const ImageReceiverNative * native, napi_value * image )
```
**描述:**
通过[ImageReceiverNative](#imagereceivernative)获取下一张图片。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
| image | 读取到的应用层的 **Image** 指针对象。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果创建surface失败则返回 IMAGE_RESULT_CREATE_SURFACE_FAILED ;
如果surface分配内存失败则返回 IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED ;
如果获取surface失败则返回 IMAGE_RESULT_GET_SURFACE_FAILED ;
如果媒体rtsp surface不支持则返回 IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果媒体类型不支持失败则返回 IMAGE_RESULT_MEDIA_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
[ImageReceiverNative](#imagereceivernative)
### OH_Image_Receiver_Release()
```
int32_t OH_Image_Receiver_Release (ImageReceiverNative * native)
```
**描述:**
释放native层 [ImageReceiverNative](#imagereceivernative) 对象。注意: 此方法不能释放应用层**ImageReceiver**对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | native层的[ImageReceiverNative](#imagereceivernative)指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像类型不支持失败则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
[ImageReceiverNative](#imagereceivernative)
### OH_Image_Release()
```
int32_t OHOS::Media::OH_Image_Release (ImageNative * native)
```
**描述:**
释放 **ImageNative** native对象。 Note: 这个方法无法释放 JavaScript Native API **Image** 对象, 而是释放被 **OH_Image_InitImageNative** 解析的 **ImageNative** native 对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表示 **ImageNative** native对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回 IMAGE_RESULT_SUCCESS ;
如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。
**起始版本:**
10
**参见:**
ImageNative, OH_Image_InitImageNative
### OH_Image_Size()
```
int32_t OHOS::Media::OH_Image_Size (const ImageNative * native, struct OhosImageSize * size )
```
**描述:**
获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表示 **ImageNative** native对象的指针。 |
| size | 表示作为转换结果的 [OhosImageSize](_ohos_image_size.md) 对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回 IMAGE_RESULT_SUCCESS ;
如果JNI环境异常返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果从surface获取参数失败返回 IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED;
如果参数错误返回 IMAGE_RESULT_BAD_PARAMETER 。
**起始版本:**
10
**参见:**
ImageNative, [OhosImageSize](_ohos_image_size.md)
### OH_ImageSource_Create()
```
int32_t OH_ImageSource_Create (napi_env env, struct OhosImageSource * src, struct OhosImageSourceOps * ops, napi_value * res )
```
**描述:**
通过给定的信息[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API** ImageSource**对象。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | 表明JNI环境的指针。 |
| src | 表明创建一个图像源的信息。查看[OhosImageSource](_ohos_image_source.md)获取更多细节。 |
| ops | 表明创建一个图像源的选项。查看[OhosImageSourceOps](_ohos_image_source_ops.md)。 |
| res | 表明JavaScript native层API**ImageSource**对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果图像源数据不完整,返回IMAGE_RESULT_SOURCE_DATA_INCOMPLETE;
如果图像源数据错误,返回IMAGE_RESULT_SOURCE_DATA;
如果图像获取数据错误,返回IMAGE_RESULT_GET_DATA_ABNORMAL;
如果图像数据太大,返回IMAGE_RESULT_TOO_LARGE;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果图像解码 EXIF 不支持,返回IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图像属性不存在,返回IMAGE_RESULT_PROPERTY_NOT_EXIST;
如果文件损坏,返回IMAGE_RESULT_FILE_DAMAGED;
如果文件 FD 错误,返回IMAGE_RESULT_FILE_FD_ERROR;
如果数据流错误,返回IMAGE_RESULT_STREAM_SIZE_ERROR;
如果查找文件失败,返回IMAGE_RESULT_SEEK_FAILED;
如果速览文件失败,返回IMAGE_RESULT_PEEK_FAILED;
如果读取文件失败,返回IMAGE_RESULT_FREAD_FAILED。
**起始版本:**
10
**参见:**
[OhosImageSource](_ohos_image_source.md), [OhosImageSourceOps](_ohos_image_source_ops.md)
### OH_ImageSource_CreateIncremental()
```
int32_t OH_ImageSource_CreateIncremental (napi_env env, struct OhosImageSource * source, struct OhosImageSourceOps * ops, napi_value * res )
```
**描述:**
通过给定的infomations[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过**OH_ImageSource_UpdateData**更新。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | 表明JNI环境的指针。 |
| src | 表明创建一个图像源的信息。这里只接收缓冲区类型。查看[OhosImageSource](_ohos_image_source.md)获取更多细节 |
| ops | 表明创建一个图像源的选项。查看[OhosImageSourceOps](_ohos_image_source_ops.md)。 |
| res | 表明JavaScript native层API**ImageSource**对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果图像源数据不完整,返回IMAGE_RESULT_SOURCE_DATA_INCOMPLETE;
如果图像源数据错误,返回IMAGE_RESULT_SOURCE_DATA;
如果图像获取数据错误,返回IMAGE_RESULT_GET_DATA_ABNORMAL;
如果图像数据太大,返回IMAGE_RESULT_TOO_LARGE;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果图像解码 EXIF 不支持,返回IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图像属性不存在,返回IMAGE_RESULT_PROPERTY_NOT_EXIST;
如果文件损坏,返回IMAGE_RESULT_FILE_DAMAGED;
如果文件 FD 错误,返回IMAGE_RESULT_FILE_FD_ERROR;
如果数据流错误,返回IMAGE_RESULT_STREAM_SIZE_ERROR;
如果查找文件失败,返回IMAGE_RESULT_SEEK_FAILED;
如果速览文件失败,返回IMAGE_RESULT_PEEK_FAILED;
如果读取文件失败,返回IMAGE_RESULT_FREAD_FAILED。
**起始版本:**
10
**参见:**
[OhosImageSource](_ohos_image_source.md), [OhosImageSourceOps](_ohos_image_source_ops.md), [OH_ImageSource_UpdateData](#oh_imagesource_updatedata)
### OH_ImageSource_CreatePixelMap()
```
int32_t OH_ImageSource_CreatePixelMap (const ImageSourceNative * native, struct OhosImageDecodingOps * ops, napi_value * res )
```
**描述:**
通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层[ImageSourceNative](#imagesourcenative)值的指针。 |
| ops | 表明为了解码图像源的选项,查看[OhosImageDecodingOps](_ohos_image_decoding_ops.md)。 |
| res | 表明JavaScript native层API**PixelMap**对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED;
如果检查格式不对,返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL。
如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST;
如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL;
如果图片解码异常,返回 IMAGE_RESULT_DECODE_ABNORMAL;
如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL;
如果裁剪错误,返回 IMAGE_RESULT_CROP;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED;
如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT;
如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED;
如果ipc失败,返回 IMAGE_RESULT_ERR_IPC;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR;
如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageDecodingOps](_ohos_image_decoding_ops.md)
### OH_ImageSource_CreatePixelMapList()
```
int32_t OH_ImageSource_CreatePixelMapList (const ImageSourceNative * native, struct OhosImageDecodingOps * ops, napi_value * res )
```
**描述:**
通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| ops | 表明为了解码图像源的选项,查看[OhosImageDecodingOps](_ohos_image_decoding_ops.md)。 |
| res | 表明JavaScript native层API**PixelMap** 列表对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED;
如果检查格式不对,返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST;
如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL;
如果图片解码异常,返回 IMAGE_RESULT_DECODE_ABNORMAL;
如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL;
如果裁剪错误,返回 IMAGE_RESULT_CROP;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED;
如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT;
如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED;
如果ipc失败,返回 IMAGE_RESULT_ERR_IPC;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR;
如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageDecodingOps](_ohos_image_decoding_ops.md)
### OH_ImageSource_GetDelayTime()
```
int32_t OH_ImageSource_GetDelayTime (const ImageSourceNative * native, struct OhosImageSourceDelayTimeList * res )
```
**描述:**
从一些**ImageSource**(如GIF图像源)获取延迟时间列表。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| res | 表明延迟时间列表 [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) 的指针。 当输入的res中**delayTimeList**是空指针并且**size**是0时,将通过res的**size**中返回延迟时间列表大小 为了获取延迟时间,需要比返回的**delayTimeList**大小值大的足够空间 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md)
### OH_ImageSource_GetFrameCount()
```
int32_t OH_ImageSource_GetFrameCount (const ImageSourceNative * native, uint32_t * res )
```
**描述:**
**ImageSource**中获取帧计数。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| res | 表明帧计数的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative)
### OH_ImageSource_GetImageInfo()
```
int32_t OH_ImageSource_GetImageInfo (const ImageSourceNative * native, int32_t index, struct OhosImageSourceInfo * info )
```
**描述:**
通过索引从**ImageSource**获取图像源信息。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| index | 表明帧计数的指针。 |
| info | 表明图像源信息[OhosImageSourceInfo](_ohos_image_source_info.md)的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageSourceInfo](_ohos_image_source_info.md)
### OH_ImageSource_GetImageProperty()
```
int32_t OH_ImageSource_GetImageProperty (const ImageSourceNative * native, struct OhosImageSourceProperty * key, struct OhosImageSourceProperty * value )
```
**描述:**
通过关键字从**ImageSource**中获取图像源属性。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| key | 表明属性关键字[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 |
| value | 表明作为结果的属性值[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 当输入的value中**value**是空指针并且**size**是0时,将通过value中的**size**返回属性值的大小。 为了获取属性值,需要比**value**中的结果大小大的足够的空间。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageSourceProperty](_ohos_image_source_property.md)
### OH_ImageSource_GetSupportedFormats()
```
int32_t OH_ImageSource_GetSupportedFormats (struct OhosImageSourceSupportedFormatList * res)
```
**描述:**
获取所有支持的解码格式元标记。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| res | 表明指向**[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md)**结构的列表指针。 当**supportedFormatList**为nullptr并且**size**以res为0作为输入时,它将以res** size**返回支持的格式大小。<br/>为了获得所有的格式标记,它需要比**supportedFormatList**中的结果大小大的足够空间, 还需要为[OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md)项目中的每个格式提供足够的空间。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果检查格式不对,返回MAGE_RESULT_CHECK_FORMAT_ERROR。
**起始版本:**
10
**参见:**
[OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md), [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md)
### OH_ImageSource_InitNative()
```
ImageSourceNative* OH_ImageSource_InitNative (napi_env env, napi_value source )
```
**描述:**
从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](#imagesourcenative)值。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | 表明JNI环境的指针。 |
| source | 表明JavaScript native层API** ImageSource**对象的指针。 |
**返回:**
如果操作成功返回[ImageSourceNative](#imagesourcenative)指针;如果操作失败,返回空指针。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OH_ImageSource_Release](#oh_imagesource_release)
### OH_ImageSource_ModifyImageProperty()
```
int32_t OH_ImageSource_ModifyImageProperty (const ImageSourceNative * native, struct OhosImageSourceProperty * key, struct OhosImageSourceProperty * value )
```
**描述:**
通过关键字为**ImageSource**修改图像源属性。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针 |
| key | 表明属性关键字[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 |
| value | 为了修改表明属性值[OhosImageSourceProperty](_ohos_image_source_property.md)的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果图片解码异常, IMAGE_RESULT_DECODE_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果解码的EXIF不支持,返回 IMAGE_RESULT_DECODE_EXIF_UNSUPPORT;
如果图片属性不存在,返回 IMAGE_RESULT_PROPERTY_NOT_EXIST。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageSourceProperty](_ohos_image_source_property.md)
### OH_ImageSource_Release()
```
int32_t OH_ImageSource_Release (ImageSourceNative * native)
```
**描述:**
释放native层图像源 **ImageSourceNative**
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OH_ImageSource_Create](#oh_imagesource_create), [OH_ImageSource_CreateIncremental](#oh_imagesource_createincremental)
### OH_ImageSource_UpdateData()
```
int32_t OH_ImageSource_UpdateData (const ImageSourceNative * native, struct OhosImageSourceUpdateData * data )
```
**描述:**
为了增量类型的**ImageSource**更新源数据。
\@Syscap SystemCapability.Multimedia.Image
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | 表明native层 [ImageSourceNative](#imagesourcenative) 值的指针。 |
| data | 表明更新数据信息[OhosImageSourceUpdateData](_ohos_image_source_update_data.md)的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功返回OHOS_IMAGE_RESULT_SUCCESS;
如果参数错误,返回IMAGE_RESULT_BAD_PARAMETER;
如果 JNI 环境异常,返回IMAGE_RESULT_JNI_ENV_ABNORMAL;
如果参数无效,IMAGE_RESULT_INVALID_PARAMETER;
如果获取图片数据异常,返回 IMAGE_RESULT_GET_DATA_ABNORMAL;
如果解码失败,返回IMAGE_RESULT_DECODE_FAILED;
如果图像解码头错误,返回IMAGE_RESULT_DECODE_HEAD_ABNORMAL;
如果创建解码器失败,返回 IMAGE_RESULT_CREATE_DECODER_FAILED;
如果创建编码器失败,返回 IMAGE_RESULT_CREATE_ENCODER_FAILED;
如果检查格式不对,返回IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia错误,返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR;
如果输入图片数据错误,返回 IMAGE_RESULT_DATA_ABNORMAL;
如果共享内存错误,返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST;
如果共享内存数据异常,返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL;
如果图片解码异常,返回IMAGE_RESULT_DECODE_ABNORMAL;
如果图像错误,返回 IMAGE_RESULT_MALLOC_ABNORMAL;
如果图片初始化错误,返回 IMAGE_RESULT_DATA_UNSUPPORT;
如果图片输入数据错误,返回 IMAGE_RESULT_INIT_ABNORMAL;
如果裁剪错误,返回 IMAGE_RESULT_CROP;
如果图片格式未知,返回 IMAGE_RESULT_UNKNOWN_FORMAT;
如果注册插件失败,返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED;
如果创建插件失败。返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED;
如果增加位图失败,返回 IMAGE_RESULT_ENCODE_FAILED;
如果不支持图片硬解码,返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT;
如果硬解码失败,返回 IMAGE_RESULT_HW_DECODE_FAILED;
如果ipc失败,返回 IMAGE_RESULT_ERR_IPC;
如果索引无效,返回 IMAGE_RESULT_INDEX_INVALID;
如果透明度类型错误,返回 IMAGE_RESULT_ALPHA_TYPE_ERROR;
如果内存分配类型错误,返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR。
**起始版本:**
10
**参见:**
[ImageSourceNative](#imagesourcenative), [OhosImageSourceUpdateData](_ohos_image_source_update_data.md)
### OH_PixelMap_AccessPixels()
```
int32_t OH_PixelMap_AccessPixels (const NativePixelMap * native, void ** addr )
```
**描述:**
获取native **PixelMap** 对象数据的内存地址,并锁定该内存。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| addr | 用于指向的内存地址的双指针对象。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
AccessPixels
### OH_PixelMap_CreateAlphaPixelMap()
```
int32_t OH_PixelMap_CreateAlphaPixelMap (napi_env env, napi_value source, napi_value * alpha )
```
**描述:**
根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | napi的环境指针。 |
| source | **PixelMap**数据设置项。 |
| alpha | alpha通道的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果图像头解码失败则返回 IMAGE_RESULT_DECODE_HEAD_ABNORMAL ;
如果创建解码器失败则返回 IMAGE_RESULT_CREATE_DECODER_FAILED ;
如果创建编码器失败则返回 IMAGE_RESULT_CREATE_ENCODER_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像解码失败则返回 IMAGE_RESULT_DECODE_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果图像添加像素位图失败则返回 IMAGE_RESULT_ENCODE_FAILED ;
如果图像不支持硬件解码则返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT ;
如果硬件解码失败则返回 IMAGE_RESULT_HW_DECODE_FAILED ;
如果ipc失败则返回 IMAGE_RESULT_INDEX_INVALID ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
CreateAlphaPixelMap
### OH_PixelMap_CreatePixelMap()
```
int32_t OH_PixelMap_CreatePixelMap (napi_env env, OhosPixelMapCreateOps info, void * buf, size_t len, napi_value * res )
```
**描述:**
Creates a **PixelMap** object.
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | napi的环境指针。 |
| info | pixel map 数据设置项。 |
| buf | 图片的buffer数据。 |
| len | 图片大小信息。 |
| res | 应用层的 **PixelMap** 对象的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果图像头解码失败则返回 IMAGE_RESULT_DECODE_HEAD_ABNORMAL ;
如果创建解码器失败则返回 IMAGE_RESULT_CREATE_DECODER_FAILED ;
如果创建编码器失败则返回 IMAGE_RESULT_CREATE_ENCODER_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像解码失败则返回 IMAGE_RESULT_DECODE_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果图像添加像素位图失败则返回 IMAGE_RESULT_ENCODE_FAILED ;
如果图像不支持硬件解码则返回 IMAGE_RESULT_HW_DECODE_UNSUPPORT ;
如果硬件解码失败则返回 IMAGE_RESULT_HW_DECODE_FAILED ;
如果ipc失败则返回 IMAGE_RESULT_INDEX_INVALID ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
CreatePixelMap
### OH_PixelMap_Crop()
```
int32_t OH_PixelMap_Crop (const NativePixelMap * native, int32_t x, int32_t y, int32_t width, int32_t height )
```
**描述:**
设置**PixelMap**对象的裁剪。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| x | 目标图片左上角的x坐标。 |
| y | 目标图片左上角的y坐标。 |
| width | 裁剪区域的宽度。 |
| height | 裁剪区域的高度。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
Crop
### OH_PixelMap_Flip()
```
int32_t OH_PixelMap_Flip (const NativePixelMap * native, int32_t x, int32_t y )
```
**描述:**
设置**PixelMap**对象的翻转。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| x | 根据水平方向x轴进行图片翻转。 |
| y | 根据垂直方向y轴进行图片翻转。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
Flip
### OH_PixelMap_GetBytesNumberPerRow()
```
int32_t OH_PixelMap_GetBytesNumberPerRow (const NativePixelMap * native, int32_t * num )
```
**描述:**
获取**PixelMap**对象每行字节数。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| num | **PixelMap**对象的每行字节数指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
GetBytesNumberPerRow
### OH_PixelMap_GetDensity()
```
int32_t OH_PixelMap_GetDensity (const NativePixelMap * native, int32_t * density )
```
**描述:**
获取**PixelMap**对象像素密度。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| density | 像素密度指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
GetDensity
### OH_PixelMap_GetImageInfo()
```
int32_t OH_PixelMap_GetImageInfo (const NativePixelMap * native, OhosPixelMapInfos * info )
```
**描述:**
获取**PixelMap**对象图像信息。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| info | 图像信息指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
[OhosPixelMapInfos](_ohos_pixel_map_infos.md)
### OH_PixelMap_GetIsEditable()
```
int32_t OH_PixelMap_GetIsEditable (const NativePixelMap * native, int32_t * editable )
```
**描述:**
获取**PixelMap**对象是否可编辑的状态。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| editable | **PixelMap** 对象是否可编辑的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
GetIsEditable
### OH_PixelMap_InitNativePixelMap()
```
NativePixelMap* OH_PixelMap_InitNativePixelMap (napi_env env, napi_value source )
```
**描述:**
初始化**PixelMap**对象数据。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | napi的环境指针。 |
| source | **PixelMap** 数据设置项。 |
**返回:**
操作成功则返回NativePixelMap的指针;如果操作失败,则返回错误码。
**起始版本:**
10
**参见:**
InitNativePixelMap
### OH_PixelMap_IsSupportAlpha()
```
int32_t OH_PixelMap_IsSupportAlpha (const NativePixelMap * native, int32_t * alpha )
```
**描述:**
获取**PixelMap**对象是否支持Alpha通道。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| alpha | 是否支持Alpha的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
IsSupportAlpha
### OH_PixelMap_Rotate()
```
int32_t OH_PixelMap_Rotate (const NativePixelMap * native, float angle )
```
**描述:**
设置**PixelMap**对象的旋转。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| angle | 旋转角度。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
Rotate
### OH_PixelMap_Scale()
```
int32_t OH_PixelMap_Scale (const NativePixelMap * native, float x, float y )
```
**描述:**
设置**PixelMap**对象的缩放。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| x | 缩放宽度。 |
| y | 缩放高度。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果图像初始化失败则返回 IMAGE_RESULT_INIT_ABNORMAL ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
Scale
### OH_PixelMap_SetAlphaAble()
```
int32_t OH_PixelMap_SetAlphaAble (const NativePixelMap * native, int32_t alpha )
```
**描述:**
设置**PixelMap**对象的Alpha通道。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| alpha | Alpha通道。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
SetAlphaAble
### OH_PixelMap_SetDensity()
```
int32_t OH_PixelMap_SetDensity (const NativePixelMap * native, int32_t density )
```
**描述:**
设置**PixelMap**对象像素密度。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| density | 像素密度。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
GetDensity
### OH_PixelMap_SetOpacity()
```
int32_t OH_PixelMap_SetOpacity (const NativePixelMap * native, float opacity )
```
**描述:**
设置**PixelMap**对象的透明度。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| opacity | 透明度。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT 。
**起始版本:**
10
**参见:**
SetOpacity
### OH_PixelMap_Translate()
```
int32_t OH_PixelMap_Translate (const NativePixelMap * native, float x, float y )
```
**描述:**
设置**PixelMap**对象的偏移。
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
| x | 水平偏移量。 |
| y | 垂直偏移量。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
Translate
### OH_PixelMap_UnAccessPixels()
```
int32_t OH_PixelMap_UnAccessPixels (const NativePixelMap * native)
```
**描述:**
释放native **PixelMap**对象数据的内存锁,用于匹配方法[OH_PixelMap_AccessPixels](#oh_pixelmap_accesspixels)
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| native | NativePixelMap的指针。 |
**返回:**
参考[IRNdkErrCode](#irndkerrcode)
如果操作成功则返回 IMAGE_RESULT_SUCCESS ;
如果参数错误则返回 IMAGE_RESULT_BAD_PARAMETER ;
如果JNI环境异常则返回 IMAGE_RESULT_JNI_ENV_ABNORMAL ;
如果参数无效则返回 IMAGE_RESULT_INVALID_PARAMETER ;
如果图像获取数据失败则返回 IMAGE_RESULT_GET_DATA_ABNORMAL ;
如果解码失败则返回 IMAGE_RESULT_DECODE_FAILED ;
如果检查格式失败则返回 IMAGE_RESULT_CHECK_FORMAT_ERROR ;
如果skia能力失败则返回 IMAGE_RESULT_THIRDPART_SKIA_ERROR ;
如果图像输入数据失败则返回 IMAGE_RESULT_DATA_ABNORMAL ;
如果共享内存失败则返回 IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST ;
如果共享内存数据错误则返回 IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL ;
如果图像分配内存失败则返回 IMAGE_RESULT_MALLOC_ABNORMAL ;
如果图像数据不支持则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果裁剪失败失败则返回 IMAGE_RESULT_CROP ;
如果图像格式未知则返回 IMAGE_RESULT_UNKNOWN_FORMAT ;
如果注册插件失败失败则返回 IMAGE_RESULT_PLUGIN_REGISTER_FAILED ;
如果创建插件失败失败则返回 IMAGE_RESULT_PLUGIN_CREATE_FAILED ;
如果属性无效则返回 IMAGE_RESULT_DATA_UNSUPPORT ;
如果透明度类型错误则返回 IMAGE_RESULT_ALPHA_TYPE_ERROR ;
如果内存分配类型错误则返回 IMAGE_RESULT_ALLOCATER_TYPE_ERROR 。
**起始版本:**
10
**参见:**
UnAccessPixels
### OH_UnAccessPixels()
```
int32_t OHOS::Media::OH_UnAccessPixels (napi_env env, napi_value value )
```
**描述:**
释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| env | napi的环境指针。 |
| value | 应用层的 **PixelMap** 对象。 |
**返回:**
操作成功则返回 **OHOS_IMAGE_RESULT_SUCCESS**;如果操作失败,则返回错误码。
**起始版本:**
8
**废弃起始版本:**
10
**参见:**
AccessPixels
## 变量说明
### alphaType
```
int32_t OhosImageSourceInfo::alphaType
```
**描述:**
图像源透明度类型
**起始版本:**
10
### buffer [1/2]
```
uint8_t* OhosImageSource::buffer = nullptr
```
**描述:**
图像源缓冲区资源,解手格式化包缓冲区或者base64缓冲区
**起始版本:**
10
### buffer [2/2]
```
uint8_t* OhosImageSourceUpdateData::buffer = nullptr
```
**描述:**
图像源更新数据缓冲区
**起始版本:**
10
### bufferSize [1/2]
```
size_t OhosImageSource::bufferSize = 0
```
**描述:**
图像源缓冲区资源大小
**起始版本:**
10
### bufferSize [2/2]
```
size_t OhosImageSourceUpdateData::bufferSize = 0
```
**描述:**
图像源更新数据缓冲区大小
**起始版本:**
10
### colorSpace
```
int32_t OhosImageSourceInfo::colorSpace
```
**描述:**
图像源色彩空间
**起始版本:**
10
### delayTimeList
```
int32_t* OhosImageSourceDelayTimeList::delayTimeList
```
**描述:**
图像源延迟时间列表头地址
**起始版本:**
10
### density [1/2]
```
int32_t OhosImageSourceOps::density
```
**描述:**
图像源像素密度
**起始版本:**
10
### density [2/2]
```
int32_t OhosImageSourceInfo::density
```
**描述:**
图像源密度, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置
**起始版本:**
10
### editable
```
int8_t OhosImageDecodingOps::editable
```
**描述:**
定义输出的像素位图是否可编辑
**起始版本:**
10
### fd
```
int32_t OhosImageSource::fd = -1
```
**描述:**
图像源文件资源描述符
**起始版本:**
10
### fitDensity
```
int32_t OhosImageDecodingOps::fitDensity
```
**描述:**
定义解码目标的像素密度
**起始版本:**
10
### format
```
char* OhosImageSourceSupportedFormat::format = nullptr
```
**描述:**
图像源支持的格式字符串头地址
**起始版本:**
10
### height
```
int32_t OhosImageRegion::height
```
**描述:**
高度范围,用pixels表示
**起始版本:**
10
### index
```
uint32_t OhosImageDecodingOps::index
```
**描述:**
定义图像源解码指数
**起始版本:**
10
### isCompleted
```
int8_t OhosImageSourceUpdateData::isCompleted = 0
```
**描述:**
图像源更新数据在此节中完成
**起始版本:**
10
### offset
```
uint32_t OhosImageSourceUpdateData::offset = 0
```
**描述:**
图像源更新数据缓冲区的开端
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE
```
const char* OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE = "BitsPerSample"
```
**描述:**
定义每个样本比特的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL
```
const char* OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL = "CompressedBitsPerPixel"
```
**描述:**
定义每个像素的压缩比特的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL
```
const char* OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL = "DateTimeOriginal"
```
**描述:**
定义初始日期时间的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_EXPOSURE_TIME
```
const char* OHOS_IMAGE_PROPERTY_EXPOSURE_TIME = "ExposureTime"
```
**描述:**
定义曝光时间的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_F_NUMBER
```
const char* OHOS_IMAGE_PROPERTY_F_NUMBER = "FNumber"
```
**描述:**
定义FNumber的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_GPS_LATITUDE
```
const char* OHOS_IMAGE_PROPERTY_GPS_LATITUDE = "GPSLatitude"
```
**描述:**
定义GPS纬度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF
```
const char* OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF = "GPSLatitudeRef"
```
**描述:**
定义GPS纬度参考的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_GPS_LONGITUDE
```
const char* OHOS_IMAGE_PROPERTY_GPS_LONGITUDE = "GPSLongitude"
```
**描述:**
定义GPS经度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF
```
const char* OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF = "GPSLongitudeRef"
```
**描述:**
定义GPS经度参考的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_IMAGE_LENGTH
```
const char* OHOS_IMAGE_PROPERTY_IMAGE_LENGTH = "ImageLength"
```
**描述:**
定义图像长度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_IMAGE_WIDTH
```
const char* OHOS_IMAGE_PROPERTY_IMAGE_WIDTH = "ImageWidth"
```
**描述:**
定义图像宽度的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS
```
const char* OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS = "ISOSpeedRatings"
```
**描述:**
定义ISO速度等级的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_ORIENTATION
```
const char* OHOS_IMAGE_PROPERTY_ORIENTATION = "Orientation"
```
**描述:**
定义方向的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### OHOS_IMAGE_PROPERTY_SCENE_TYPE
```
const char* OHOS_IMAGE_PROPERTY_SCENE_TYPE = "SceneType"
```
**描述:**
定义场景类型的图像属性关键字。 此标签给[OH_ImageSource_GetImageProperty](#oh_imagesource_getimageproperty)[OH_ImageSource_ModifyImageProperty](#oh_imagesource_modifyimageproperty)这两个接口使用。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
### pixelFormat [1/3]
```
int32_t OhosImageSourceOps::pixelFormat
```
**描述:**
图像源像素格式,通常用于描述YUV缓冲区
**起始版本:**
10
### pixelFormat [2/3]
```
int32_t OhosImageDecodingOps::pixelFormat
```
**描述:**
定义输出的像素格式
**起始版本:**
10
### pixelFormat [3/3]
```
int32_t OhosImageSourceInfo::pixelFormat
```
**描述:**
图像源像素格式, 由 [OH_ImageSource_Create](#oh_imagesource_create) 设置
**起始版本:**
10
### region
```
struct OhosImageRegion OhosImageDecodingOps::region
```
**描述:**
定义图像源解码的像素范围
**起始版本:**
10
### rotate
```
uint32_t OhosImageDecodingOps::rotate
```
**描述:**
定义解码旋转选项
**起始版本:**
10
### sampleSize
```
uint32_t OhosImageDecodingOps::sampleSize
```
**描述:**
定义解码样本大小选项
**起始版本:**
10
### size [1/7]
```
struct OhosImageSize OhosImageSourceOps::size
```
**描述:**
图像源像素宽高的大小
**起始版本:**
10
### size [2/7]
```
struct OhosImageSize OhosImageDecodingOps::size
```
**描述:**
定义解码目标像素宽高的大小
**起始版本:**
10
### size [3/7]
```
struct OhosImageSize OhosImageSourceInfo::size
```
**描述:**
图像源像素宽高的大小
**起始版本:**
10
### size [4/7]
```
size_t OhosImageSourceDelayTimeList::size = 0
```
**描述:**
图像源延迟时间列表大小
**起始版本:**
10
### size [5/7]
```
size_t OhosImageSourceSupportedFormat::size = 0
```
**描述:**
图像源支持的格式字符串大小
**起始版本:**
10
### size [6/7]
```
size_t OhosImageSourceSupportedFormatList::size = 0
```
**描述:**
图像源支持的格式字符串列表大小
**起始版本:**
10
### size [7/7]
```
size_t OhosImageSourceProperty::size = 0
```
**描述:**
定义图像源属性键值字符串大小
**起始版本:**
10
### supportedFormatList
```
struct OhosImageSourceSupportedFormat** OhosImageSourceSupportedFormatList::supportedFormatList = nullptr
```
**描述:**
图像源支持的格式字符串列表头地址
**起始版本:**
10
### updateLength
```
uint32_t OhosImageSourceUpdateData::updateLength = 0
```
**描述:**
图像源更新数据缓冲区的更新数据长度
**起始版本:**
10
### uri
```
char* OhosImageSource::uri = nullptr
```
**描述:**
图像源资源标识符,接受文件资源或者base64资源
**起始版本:**
10
### uriSize
```
size_t OhosImageSource::uriSize = 0
```
**描述:**
图像源资源长度
**起始版本:**
10
### value
```
char* OhosImageSourceProperty::value = nullptr
```
**描述:**
定义图像源属性键值字符串头地址
**起始版本:**
10
### width
```
int32_t OhosImageRegion::width
```
**描述:**
宽度范围,用pixels表示
**起始版本:**
10
### x
```
int32_t OhosImageRegion::x
```
**描述:**
起始x坐标,用pixels表示
**起始版本:**
10
### y
```
int32_t OhosImageRegion::y
```
**描述:**
起始y坐标,用pixels表示
**起始版本:**
10
**起始版本:**
8
# image_mdk.h
## 概述
声明访问图像剪辑矩形、大小、格式和组件数据的函数。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OHOS::Media::OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) | 定义图像矩形信息。 |
| [OHOS::Media::OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) | 定义图像组成信息。 |
### 类型定义
| 名称 | 描述 |
| -------- | -------- |
| [OHOS::Media::ImageNative](image.md#imagenative) | 为图像接口定义native层图像对象。 |
### 枚举
| 名称 | 描述 |
| -------- | -------- |
| { [OHOS::Media::OHOS_IMAGE_FORMAT_YCBCR_422_SP](image.md) = 1000,<br/>[OHOS::Media::OHOS_IMAGE_FORMAT_JPEG](image.md) = 2000, } | 图像格式枚举值。 |
| { [OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_Y](image.md) = 1,<br/>[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_U](image.md) = 2,<br/>[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_YUV_V](image.md) = 3,<br/>[OHOS::Media::OHOS_IMAGE_COMPONENT_FORMAT_JPEG](image.md) = 4, } | 图像组成类型枚举值。 |
### 函数
| 名称 | 描述 |
| -------- | -------- |
| [OHOS::Media::OH_Image_InitImageNative](image.md#oh_image_initimagenative) (napi_env env, napi_value source) | 从输入的JavaScript Native API **图像** 对象中解析 native **ImageNative** 对象。 |
| [OHOS::Media::OH_Image_ClipRect](image.md#oh_image_cliprect) (const [ImageNative](image.md#imagenative) \*native, struct [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) \*rect) | 获取native **ImageNative** 对象 [OhosImageRect](_o_h_o_s_1_1_media_1_1_ohos_image_rect.md) 信息。 |
| [OHOS::Media::OH_Image_Size](image.md#oh_image_size) (const [ImageNative](image.md#imagenative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 获取native **ImageNative** 对象的 [OhosImageSize](_ohos_image_size.md) 信息。 |
| [OHOS::Media::OH_Image_Format](image.md#oh_image_format) (const [ImageNative](image.md#imagenative) \*native, int32_t \*format) | 获取native **ImageNative** 对象的图像格式。 |
| [OHOS::Media::OH_Image_GetComponent](image.md#oh_image_getcomponent) (const [ImageNative](image.md#imagenative) \*native, int32_t componentType, struct [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md) \*componentNative) | 从 native **ImageNative** 对象中获取 [OhosImageComponent](_o_h_o_s_1_1_media_1_1_ohos_image_component.md)。 |
| [OHOS::Media::OH_Image_Release](image.md#oh_image_release) ([ImageNative](image.md#imagenative) \*native) | 释放 **ImageNative** native对象。 |
# image_mdk_common.h
## 概述
声明图像常用的枚举值和结构体。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OhosImageSize](_ohos_image_size.md) | 定义图像大小。 |
### 宏定义
| 名称 | 描述 |
| -------- | -------- |
| **IMAGE_RESULT_BASE** 62980096 | 接口返回值的基础值 |
### 枚举
| 名称 | 描述 |
| -------- | -------- |
| [IRNdkErrCode](image.md#irndkerrcode) {<br/>IMAGE_RESULT_SUCCESS = 0,<br/>IMAGE_RESULT_BAD_PARAMETER = -1,<br/>IMAGE_RESULT_IMAGE_RESULT_BASE = IMAGE_RESULT_BASE,<br/>IMAGE_RESULT_ERR_IPC = IMAGE_RESULT_BASE + 1,<br/>IMAGE_RESULT_ERR_SHAMEM_NOT_EXIST = IMAGE_RESULT_BASE + 2,<br/>IMAGE_RESULT_ERR_SHAMEM_DATA_ABNORMAL = IMAGE_RESULT_BASE + 3,<br/>IMAGE_RESULT_DECODE_ABNORMAL = IMAGE_RESULT_BASE + 4,<br/>IMAGE_RESULT_DATA_ABNORMAL = IMAGE_RESULT_BASE + 5,<br/>IMAGE_RESULT_MALLOC_ABNORMAL = IMAGE_RESULT_BASE + 6,<br/>IMAGE_RESULT_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 7,<br/>IMAGE_RESULT_INIT_ABNORMAL = IMAGE_RESULT_BASE + 8,<br/>IMAGE_RESULT_GET_DATA_ABNORMAL = IMAGE_RESULT_BASE + 9,<br/>IMAGE_RESULT_TOO_LARGE = IMAGE_RESULT_BASE + 10,<br/>IMAGE_RESULT_TRANSFORM = IMAGE_RESULT_BASE + 11,<br/>IMAGE_RESULT_COLOR_CONVERT = IMAGE_RESULT_BASE + 12,<br/>IMAGE_RESULT_CROP = IMAGE_RESULT_BASE + 13,<br/>IMAGE_RESULT_SOURCE_DATA = IMAGE_RESULT_BASE + 14,<br/>IMAGE_RESULT_SOURCE_DATA_INCOMPLETE = IMAGE_RESULT_BASE + 15,<br/>IMAGE_RESULT_MISMATCHED_FORMAT = IMAGE_RESULT_BASE + 16,<br/>IMAGE_RESULT_UNKNOWN_FORMAT = IMAGE_RESULT_BASE + 17,<br/>IMAGE_RESULT_SOURCE_UNRESOLVED = IMAGE_RESULT_BASE + 18,<br/>IMAGE_RESULT_INVALID_PARAMETER = IMAGE_RESULT_BASE + 19,<br/>IMAGE_RESULT_DECODE_FAILED = IMAGE_RESULT_BASE + 20,<br/>IMAGE_RESULT_PLUGIN_REGISTER_FAILED = IMAGE_RESULT_BASE + 21,<br/>IMAGE_RESULT_PLUGIN_CREATE_FAILED = IMAGE_RESULT_BASE + 22,<br/>IMAGE_RESULT_ENCODE_FAILED = IMAGE_RESULT_BASE + 23,<br/>IMAGE_RESULT_ADD_PIXEL_MAP_FAILED = IMAGE_RESULT_BASE + 24,<br/>IMAGE_RESULT_HW_DECODE_UNSUPPORT = IMAGE_RESULT_BASE + 25,<br/>IMAGE_RESULT_DECODE_HEAD_ABNORMAL = IMAGE_RESULT_BASE + 26,<br/>IMAGE_RESULT_DECODE_EXIF_UNSUPPORT = IMAGE_RESULT_BASE + 27,<br/>IMAGE_RESULT_PROPERTY_NOT_EXIST = IMAGE_RESULT_BASE + 28,<br/>IMAGE_RESULT_MEDIA_DATA_UNSUPPORT = IMAGE_RESULT_BASE + 30,<br/>IMAGE_RESULT_MEDIA_TOO_LARGE = IMAGE_RESULT_BASE + 31,<br/>IMAGE_RESULT_MEDIA_MALLOC_FAILED = IMAGE_RESULT_BASE + 32,<br/>IMAGE_RESULT_MEDIA_END_OF_STREAM = IMAGE_RESULT_BASE + 33,<br/>IMAGE_RESULT_MEDIA_IO_ABNORMAL = IMAGE_RESULT_BASE + 34,<br/>IMAGE_RESULT_MEDIA_MALFORMED = IMAGE_RESULT_BASE + 35,<br/>IMAGE_RESULT_MEDIA_BUFFER_TOO_SMALL = IMAGE_RESULT_BASE + 36,<br/>IMAGE_RESULT_MEDIA_OUT_OF_RANGE = IMAGE_RESULT_BASE + 37,<br/>IMAGE_RESULT_MEDIA_STATUS_ABNORMAL = IMAGE_RESULT_BASE + 38,<br/>IMAGE_RESULT_MEDIA_VALUE_INVALID = IMAGE_RESULT_BASE + 39,<br/>IMAGE_RESULT_MEDIA_NULL_POINTER = IMAGE_RESULT_BASE + 40,<br/>IMAGE_RESULT_MEDIA_INVALID_OPERATION = IMAGE_RESULT_BASE + 41,<br/>IMAGE_RESULT_MEDIA_ERR_PLAYER_NOT_INIT = IMAGE_RESULT_BASE + 42,<br/>IMAGE_RESULT_MEDIA_EARLY_PREPARE = IMAGE_RESULT_BASE + 43,<br/>IMAGE_RESULT_MEDIA_SEEK_ERR = IMAGE_RESULT_BASE + 44,<br/>IMAGE_RESULT_MEDIA_PERMISSION_DENIED = IMAGE_RESULT_BASE + 45,<br/>IMAGE_RESULT_MEDIA_DEAD_OBJECT = IMAGE_RESULT_BASE + 46,<br/>IMAGE_RESULT_MEDIA_TIMED_OUT = IMAGE_RESULT_BASE + 47,<br/>IMAGE_RESULT_MEDIA_TRACK_NOT_ALL_SUPPORTED = IMAGE_RESULT_BASE + 48,<br/>IMAGE_RESULT_MEDIA_ADAPTER_INIT_FAILED = IMAGE_RESULT_BASE + 49,<br/>IMAGE_RESULT_MEDIA_WRITE_PARCEL_FAIL = IMAGE_RESULT_BASE + 50,<br/>IMAGE_RESULT_MEDIA_READ_PARCEL_FAIL = IMAGE_RESULT_BASE + 51,<br/>IMAGE_RESULT_MEDIA_NO_AVAIL_BUFFER = IMAGE_RESULT_BASE + 52,<br/>IMAGE_RESULT_MEDIA_INVALID_PARAM = IMAGE_RESULT_BASE + 53, IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 54,<br/>IMAGE_RESULT_MEDIA_CREATE_CODEC_ADAPTER_FAILED = IMAGE_RESULT_BASE + 55,<br/>IMAGE_RESULT_MEDIA_CODEC_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 56,<br/>IMAGE_RESULT_MEDIA_ZCODEC_CREATE_FAILED = IMAGE_RESULT_BASE + 57,<br/>IMAGE_RESULT_MEDIA_ZCODEC_NOT_EXIST = IMAGE_RESULT_BASE + 58,<br/>IMAGE_RESULT_MEDIA_JNI_CLASS_NOT_EXIST = IMAGE_RESULT_BASE + 59,<br/>IMAGE_RESULT_MEDIA_JNI_METHOD_NOT_EXIST = IMAGE_RESULT_BASE + 60,<br/>IMAGE_RESULT_MEDIA_JNI_NEW_OBJ_FAILED = IMAGE_RESULT_BASE + 61,<br/>IMAGE_RESULT_MEDIA_JNI_COMMON_ERROR = IMAGE_RESULT_BASE + 62,<br/>IMAGE_RESULT_MEDIA_DISTRIBUTE_NOT_SUPPORT = IMAGE_RESULT_BASE + 63,<br/>IMAGE_RESULT_MEDIA_SOURCE_NOT_SET = IMAGE_RESULT_BASE + 64,<br/>IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_INIT = IMAGE_RESULT_BASE + 65,<br/>IMAGE_RESULT_MEDIA_RTSP_ADAPTER_NOT_EXIST = IMAGE_RESULT_BASE + 66,<br/>IMAGE_RESULT_MEDIA_RTSP_SURFACE_UNSUPPORT = IMAGE_RESULT_BASE + 67,<br/>IMAGE_RESULT_MEDIA_RTSP_CAPTURE_NOT_INIT = IMAGE_RESULT_BASE + 68,<br/>IMAGE_RESULT_MEDIA_RTSP_SOURCE_URL_INVALID = IMAGE_RESULT_BASE + 69,<br/>IMAGE_RESULT_MEDIA_RTSP_VIDEO_TRACK_NOT_FOUND = IMAGE_RESULT_BASE + 70,<br/>IMAGE_RESULT_MEDIA_RTSP_CAMERA_NUM_REACH_MAX = IMAGE_RESULT_BASE + 71,<br/>IMAGE_RESULT_MEDIA_SET_VOLUME = IMAGE_RESULT_BASE + 72,<br/>IMAGE_RESULT_MEDIA_NUMBER_OVERFLOW = IMAGE_RESULT_BASE + 73,<br/>IMAGE_RESULT_MEDIA_DIS_PLAYER_UNSUPPORTED = IMAGE_RESULT_BASE + 74,<br/>IMAGE_RESULT_MEDIA_DENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 75,<br/>IMAGE_RESULT_MEDIA_ENCODE_ICC_FAILED = IMAGE_RESULT_BASE + 76,<br/>IMAGE_RESULT_MEDIA_READ_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 150,<br/>IMAGE_RESULT_MEDIA_WRITE_PIXELMAP_FAILED = IMAGE_RESULT_BASE + 151,<br/>IMAGE_RESULT_MEDIA_PIXELMAP_NOT_ALLOW_MODIFY = IMAGE_RESULT_BASE + 152,<br/>IMAGE_RESULT_MEDIA_CONFIG_FAILED = IMAGE_RESULT_BASE + 153,<br/>IMAGE_RESULT_JNI_ENV_ABNORMAL = IMAGE_RESULT_BASE + 154,<br/>IMAGE_RESULT_SURFACE_GRALLOC_BUFFER_FAILED = IMAGE_RESULT_BASE + 155,<br/>IMAGE_RESULT_CREATE_SURFACE_FAILED = IMAGE_RESULT_BASE + 156,<br/>IMAGE_RESULT_SURFACE_GET_PARAMETER_FAILED = IMAGE_RESULT_BASE + 157,<br/>IMAGE_RESULT_GET_SURFACE_FAILED = IMAGE_RESULT_BASE + 158,<br/>IMAGE_RESULT_SURFACE_ACQUIRE_BUFFER_FAILED = IMAGE_RESULT_BASE + 159,<br/>IMAGE_RESULT_SURFACE_REQUEST_BUFFER_FAILED = IMAGE_RESULT_BASE + 160,<br/>IMAGE_RESULT_REGISTER_LISTENER_FAILED = IMAGE_RESULT_BASE + 161,<br/>IMAGE_RESULT_REGISTER_BUFFER_FAILED = IMAGE_RESULT_BASE + 162,<br/>IMAGE_RESULT_FREAD_FAILED = IMAGE_RESULT_BASE + 163,<br/>IMAGE_RESULT_PEEK_FAILED = IMAGE_RESULT_BASE + 164,<br/>IMAGE_RESULT_SEEK_FAILED = IMAGE_RESULT_BASE + 165,<br/>IMAGE_RESULT_STREAM_SIZE_ERROR = IMAGE_RESULT_BASE + 166,<br/>IMAGE_RESULT_FILE_FD_ERROR = IMAGE_RESULT_BASE + 167,<br/>IMAGE_RESULT_FILE_DAMAGED = IMAGE_RESULT_BASE + 168,<br/>IMAGE_RESULT_CREATE_DECODER_FAILED = IMAGE_RESULT_BASE + 169,<br/>IMAGE_RESULT_CREATE_ENCODER_FAILED = IMAGE_RESULT_BASE + 170,<br/>IMAGE_RESULT_CHECK_FORMAT_ERROR = IMAGE_RESULT_BASE + 171,<br/>IMAGE_RESULT_THIRDPART_SKIA_ERROR = IMAGE_RESULT_BASE + 172,<br/>IMAGE_RESULT_HW_DECODE_FAILED = IMAGE_RESULT_BASE + 173,<br/>IMAGE_RESULT_ALLOCATER_TYPE_ERROR = IMAGE_RESULT_BASE + 174,<br/>IMAGE_RESULT_ALPHA_TYPE_ERROR = IMAGE_RESULT_BASE + 175,<br/>IMAGE_RESULT_INDEX_INVALID = IMAGE_RESULT_BASE + 176,<br/>IMAGE_RESULT_MEDIA_UNKNOWN = IMAGE_RESULT_BASE + 200<br/>} | 可能出现的返回值的枚举。 |
# image_pixel_map_mdk.h
## 概述
声明可以锁定并访问pixelmap数据的方法,声明解锁的方法。 Need link **libpixelmapndk.z.so**
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OhosPixelMapInfos](_ohos_pixel_map_infos.md) | 用于定义 pixel map 的相关信息。 |
| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 |
### 类型定义
| 名称 | 描述 |
| -------- | -------- |
| [NativePixelMap](image.md#nativepixelmap) | 定义native层pixelmap数据类型名称。 |
| [OhosPixelMapInfos](image.md#ohospixelmapinfos) | 用于定义 pixel map 的相关信息。 |
### 枚举
| 名称 | 描述 |
| -------- | -------- |
| { [OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN](image.md) = 0,<br/>[OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE](image.md) = 1,<br/>[OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL](image.md) = 2,<br/>[OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL](image.md) = 3 } | PixelMap 透明度类型的枚举。 |
| { [OHOS_PIXEL_MAP_READ_ONLY](image.md) = 0,<br/>[OHOS_PIXEL_MAP_EDITABLE](image.md) = 1 } | PixelMap 编辑类型的枚举。 |
### 函数
| 名称 | 描述 |
| -------- | -------- |
| [OH_PixelMap_CreatePixelMap](image.md#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 |
| [OH_PixelMap_CreateAlphaPixelMap](image.md#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 |
| [OH_PixelMap_InitNativePixelMap](image.md#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 |
| [OH_PixelMap_GetBytesNumberPerRow](image.md#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 |
| [OH_PixelMap_GetIsEditable](image.md#oh_pixelmap_getiseditable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*editable) | 获取**PixelMap**对象是否可编辑的状态。 |
| [OH_PixelMap_IsSupportAlpha](image.md#oh_pixelmap_issupportalpha) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 |
| [OH_PixelMap_SetAlphaAble](image.md#oh_pixelmap_setalphaable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 |
| [OH_PixelMap_GetDensity](image.md#oh_pixelmap_getdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 |
| [OH_PixelMap_SetDensity](image.md#oh_pixelmap_setdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 |
| [OH_PixelMap_SetOpacity](image.md#oh_pixelmap_setopacity) (const [NativePixelMap](image.md#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 |
| [OH_PixelMap_Scale](image.md#oh_pixelmap_scale) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 |
| [OH_PixelMap_Translate](image.md#oh_pixelmap_translate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 |
| [OH_PixelMap_Rotate](image.md#oh_pixelmap_rotate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 |
| [OH_PixelMap_Flip](image.md#oh_pixelmap_flip) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 |
| [OH_PixelMap_Crop](image.md#oh_pixelmap_crop) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y, int32_t width, int32_t height) | 设置**PixelMap**对象的裁剪。 |
| [OH_PixelMap_GetImageInfo](image.md#oh_pixelmap_getimageinfo) (const [NativePixelMap](image.md#nativepixelmap) \*native, [OhosPixelMapInfos](_ohos_pixel_map_infos.md) \*info) | 获取**PixelMap**对象图像信息。 |
| [OH_PixelMap_AccessPixels](image.md#oh_pixelmap_accesspixels) (const [NativePixelMap](image.md#nativepixelmap) \*native, void \*\*addr) | 获取native **PixelMap** 对象数据的内存地址,并锁定该内存。 |
| [OH_PixelMap_UnAccessPixels](image.md#oh_pixelmap_unaccesspixels) (const [NativePixelMap](image.md#nativepixelmap) \*native) | 释放native **PixelMap**对象数据的内存锁,用于匹配方法 [OH_PixelMap_AccessPixels](image.md#oh_pixelmap_accesspixels)。 |
...@@ -19,122 +19,24 @@ ...@@ -19,122 +19,24 @@
### 结构体 ### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OhosPixelMapInfo](_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 |
| [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) | 用于定义创建 pixel map 设置选项的相关信息。 |
### 类型定义
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [NativePixelMap](image.md#nativepixelmap) | 用于定义NativePixelMap数据类型名称。 | | [OHOS::Media::OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) | 用于定义 pixel map 的相关信息。 |
### 枚举 ### 枚举
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| { OHOS_IMAGE_RESULT_SUCCESS = 0, OHOS_IMAGE_RESULT_BAD_PARAMETER = -1 } | 函数方法返回值的错误码的枚举。 | | { [OHOS::Media::OHOS_IMAGE_RESULT_SUCCESS](image.md) = 0,<br/>[OHOS::Media::OHOS_IMAGE_RESULT_BAD_PARAMETER](image.md) = -1 } | 函数方法返回值的错误码的枚举。 |
| { OHOS_PIXEL_MAP_FORMAT_NONE = 0, OHOS_PIXEL_MAP_FORMAT_RGBA_8888 = 3, OHOS_PIXEL_MAP_FORMAT_RGB_565 = 2 } | pixel 格式的枚举。 | | { [OHOS::Media::OHOS_PIXEL_MAP_FORMAT_NONE](image.md) = 0,<br/>[OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGBA_8888](image.md) = 3,<br/>[OHOS::Media::OHOS_PIXEL_MAP_FORMAT_RGB_565](image.md) = 2 } | pixel 格式的枚举。 |
| { OHOS_PIXEL_MAP_ALPHA_TYPE_UNKNOWN = 0, OHOS_PIXEL_MAP_ALPHA_TYPE_OPAQUE = 1, OHOS_PIXEL_MAP_ALPHA_TYPE_PREMUL = 2, OHOS_PIXEL_MAP_ALPHA_TYPE_UNPREMUL = 3 } | PixelMap alpha 类型的枚举。 | | { [OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE](image.md) = 0,<br/>[OHOS::Media::OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP](image.md) = 1 } | PixelMap 缩放类型的枚举。 |
| { OHOS_PIXEL_MAP_SCALE_MODE_FIT_TARGET_SIZE = 0, OHOS_PIXEL_MAP_SCALE_MODE_CENTER_CROP = 1 } | PixelMap 缩放类型的枚举。 |
| { OHOS_PIXEL_MAP_READ_ONLY = 0, OHOS_PIXEL_MAP_EDITABLE = 1 } | PixelMap 编辑类型的枚举。 |
### 函数 ### 函数
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_GetImageInfo](image.md#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_ohos_pixel_map_info.md)结构中。 | | [OHOS::Media::OH_GetImageInfo](image.md#oh_getimageinfo) (napi_env env, napi_value value, [OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md) \*info) | 获取 **PixelMap** 的信息,并记录信息到[OhosPixelMapInfo](_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)结构中。 |
| [OH_AccessPixels](image.md#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 | | [OHOS::Media::OH_AccessPixels](image.md#oh_accesspixels) (napi_env env, napi_value value, void \*\*addrPtr) | 获取**PixelMap**对象数据的内存地址,并锁定该内存。 |
| [OH_UnAccessPixels](image.md#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法[OH_AccessPixels](image.md#oh_accesspixels)。 | | [OHOS::Media::OH_UnAccessPixels](image.md#oh_unaccesspixels) (napi_env env, napi_value value) | 释放**PixelMap**对象数据的内存锁, 用于匹配方法**OH_AccessPixels**。 |
| [OH_PixelMap_CreatePixelMap](image.md#oh_pixelmap_createpixelmap) (napi_env env, [OhosPixelMapCreateOps](_ohos_pixel_map_create_ops.md) info, void \*buf, size_t len, napi_value \*res) | 创建**PixelMap**对象。 |
| [OH_PixelMap_CreateAlphaPixelMap](image.md#oh_pixelmap_createalphapixelmap) (napi_env env, napi_value source, napi_value \*alpha) | 根据Alpha通道的信息,来生成一个仅包含Alpha通道信息的**PixelMap**对象。 |
| [OH_PixelMap_InitNativePixelMap](image.md#oh_pixelmap_initnativepixelmap) (napi_env env, napi_value source) | 初始化**PixelMap**对象数据。 |
| [OH_PixelMap_GetBytesNumberPerRow](image.md#oh_pixelmap_getbytesnumberperrow) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*num) | 获取**PixelMap**对象每行字节数。 |
| [OH_PixelMap_GetIsEditable](image.md#oh_pixelmap_getiseditable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*[editable](#editable)) | 获取**PixelMap**对象是否可编辑的状态。 |
| [OH_PixelMap_IsSupportAlpha](image.md#oh_pixelmap_issupportalpha) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*alpha) | 获取**PixelMap**对象是否支持Alpha通道。 |
| [OH_PixelMap_SetAlphaAble](image.md#oh_pixelmap_setalphaable) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t alpha) | 设置**PixelMap**对象的Alpha通道。 |
| [OH_PixelMap_GetDensity](image.md#oh_pixelmap_getdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t \*density) | 获取**PixelMap**对象像素密度。 |
| [OH_PixelMap_SetDensity](image.md#oh_pixelmap_setdensity) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t density) | 设置**PixelMap**对象像素密度。 |
| [OH_PixelMap_SetOpacity](image.md#oh_pixelmap_setopacity) (const [NativePixelMap](image.md#nativepixelmap) \*native, float opacity) | 设置**PixelMap**对象的透明度。 |
| [OH_PixelMap_Scale](image.md#oh_pixelmap_scale) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的缩放。 |
| [OH_PixelMap_Translate](image.md#oh_pixelmap_translate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float x, float y) | 设置**PixelMap**对象的偏移。 |
| [OH_PixelMap_Rotate](image.md#oh_pixelmap_rotate) (const [NativePixelMap](image.md#nativepixelmap) \*native, float angle) | 设置**PixelMap**对象的旋转。 |
| [OH_PixelMap_Flip](image.md#oh_pixelmap_flip) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y) | 设置**PixelMap**对象的翻转。 |
| [OH_PixelMap_Crop](image.md#oh_pixelmap_crop) (const [NativePixelMap](image.md#nativepixelmap) \*native, int32_t x, int32_t y, int32_t [width](#width), int32_t [height](#height)) | 设置**PixelMap**对象的裁剪。 |
### 变量
| 名称 | 描述 |
| -------- | -------- |
| [width](#width) | 图片的宽, 用pixels表示。|
| [height](#height) | 图片的高, 用pixels表示。|
| [pixelFormat](#pixelformat) | 图片的格式。|
| [editable](#editable) | 图片的编辑类型。|
| [alphaType](#alphatype) | 图片的alpha类型。|
| [scaleMode](#scalemode) | 图片的缩放类型。|
## 变量说明
### alphaType
```
uint32_t alphaType
```
**描述:**
图片的alpha类型。
### editable
```
uint32_t editable
```
**描述:**
图片的编辑类型。
### height
```
uint32_t height
```
**描述:**
图片的高, 用pixels表示。
### pixelFormat
```
int32_t pixelFormat
```
**描述:**
图片的格式。
### scaleMode
```
uint32_t scaleMode
```
**描述:**
图片的缩放类型。
### width
```
uint32_t width
```
**描述:**
图片的宽, 用pixels表示。
# image_receiver_mdk.h
## 概述
声明从native层获取图片数据的方法。
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OhosImageReceiverInfo](_ohos_image_receiver_info.md) | 定义**ImageReceiver**的相关信息。 |
### 类型定义
| 名称 | 描述 |
| -------- | -------- |
| [ImageReceiverNative](image.md#imagereceivernative) | 用于定义ImageReceiverNative数据类型名称。 |
| (\*[OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback)) () | 定义native层图片的回调方法。 |
### 函数
| 名称 | 描述 |
| -------- | -------- |
| [OH_Image_Receiver_CreateImageReceiver](image.md#oh_image_receiver_createimagereceiver) (napi_env env, struct [OhosImageReceiverInfo](_ohos_image_receiver_info.md) info, napi_value \*res) | 创建应用层 **ImageReceiver** 对象。 |
| [OH_Image_Receiver_InitImageReceiverNative](image.md#oh_image_receiver_initimagereceivernative) (napi_env env, napi_value source) | 通过应用层**ImageReceiver**对象初始化native层[ImageReceiverNative](image.md#imagereceivernative)对象。 |
| [OH_Image_Receiver_GetReceivingSurfaceId](image.md#oh_image_receiver_getreceivingsurfaceid) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, char \*id, size_t len) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取receiver的id。 |
| [OH_Image_Receiver_ReadLatestImage](image.md#oh_image_receiver_readlatestimage) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取最新的一张图片。 |
| [OH_Image_Receiver_ReadNextImage](image.md#oh_image_receiver_readnextimage) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, napi_value \*image) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取下一张图片。 |
| [OH_Image_Receiver_On](image.md#oh_image_receiver_on) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, [OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback) callback) | 注册一个[OH_Image_Receiver_On_Callback](image.md#oh_image_receiver_on_callback)回调事件。每当接收新图片,该回调事件就会响应。 |
| [OH_Image_Receiver_GetSize](image.md#oh_image_receiver_getsize) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, struct [OhosImageSize](_ohos_image_size.md) \*size) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的大小。 |
| [OH_Image_Receiver_GetCapacity](image.md#oh_image_receiver_getcapacity) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, int32_t \*capacity) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的容量。 |
| [OH_Image_Receiver_GetFormat](image.md#oh_image_receiver_getformat) (const [ImageReceiverNative](image.md#imagereceivernative) \*native, int32_t \*format) | 通过[ImageReceiverNative](image.md#imagereceivernative)获取**ImageReceiver**的格式。 |
| [OH_Image_Receiver_Release](image.md#oh_image_receiver_release) ([ImageReceiverNative](image.md#imagereceivernative) \*native) | 释放native层 [ImageReceiverNative](image.md#imagereceivernative) 对象。 |
# image_source_mdk.h
## 概述
声明将图片源解码成像素位图的方法。
\@Syscap SystemCapability.Multimedia.Image
**起始版本:**
10
**相关模块:**
[Image](image.md)
## 汇总
### 结构体
| 名称 | 描述 |
| -------- | -------- |
| [OhosImageRegion](_ohos_image_region.md) | 定义图像源解码的范围选项。 |
| [OhosImageSourceOps](_ohos_image_source_ops.md) | 定义图像源选项信息。 |
| [OhosImageDecodingOps](_ohos_image_decoding_ops.md) | 定义图像源解码选项。 |
| [OhosImageSourceInfo](_ohos_image_source_info.md) | 定义图像源信息。 |
| [OhosImageSource](_ohos_image_source.md) | 定义图像源输入资源,每次仅接收一种类型。 |
| [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) | 定义图像源延迟时间列表。 |
| [OhosImageSourceSupportedFormat](_ohos_image_source_supported_format.md) | 定义图像源支持的格式字符串。 |
| [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) | 定义图像源支持的格式字符串列表。 |
| [OhosImageSourceProperty](_ohos_image_source_property.md) | 定义图像源属性键值字符串。 |
| [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) | 定义图像源更新数据选项。 |
### 类型定义
| 名称 | 描述 |
| -------- | -------- |
| [ImageSourceNative](image.md#imagesourcenative) | 为图像源方法定义native层图像源对象。 |
### 函数
| 名称 | 描述 |
| -------- | -------- |
| [OH_ImageSource_Create](image.md#oh_imagesource_create) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*src, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的信息[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构体,获取JavaScript native层API**ImageSource**对象。 |
| [OH_ImageSource_CreateIncremental](image.md#oh_imagesource_createincremental) (napi_env env, struct [OhosImageSource](_ohos_image_source.md) \*source, struct [OhosImageSourceOps](_ohos_image_source_ops.md) \*ops, napi_value \*res) | 通过给定的infomations[OhosImageSource](_ohos_image_source.md)[OhosImageSourceOps](_ohos_image_source_ops.md)结构, 获取增量类型的JavaScript Native API ImageSource对象,图像数据应通过OH_ImageSource_UpdateData更新。 |
| [OH_ImageSource_GetSupportedFormats](image.md#oh_imagesource_getsupportedformats) (struct [OhosImageSourceSupportedFormatList](_ohos_image_source_supported_format_list.md) \*res) | 获取所有支持的解码格式元标记。 |
| \*[OH_ImageSource_InitNative](image.md#oh_imagesource_initnative) (napi_env env, napi_value source) | 从输入JavaScript native层API **ImageSource** 对象中,转换成[ImageSourceNative](image.md#imagesourcenative)值。 |
| [OH_ImageSource_CreatePixelMap](image.md#oh_imagesource_createpixelmap) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码JavaScript native层API**PixelMap**对象 |
| [OH_ImageSource_CreatePixelMapList](image.md#oh_imagesource_createpixelmaplist) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageDecodingOps](_ohos_image_decoding_ops.md) \*ops, napi_value \*res) | 通过一个给定的选项[OhosImageDecodingOps](_ohos_image_decoding_ops.md)结构体,从**ImageSource**中解码所有的JavaScript native层API**PixelMap**对象列表 |
| [OH_ImageSource_GetDelayTime](image.md#oh_imagesource_getdelaytime) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceDelayTimeList](_ohos_image_source_delay_time_list.md) \*res) | 从一些**ImageSource**(如GIF图像源)获取延迟时间列表。 |
| [OH_ImageSource_GetFrameCount](image.md#oh_imagesource_getframecount) (const [ImageSourceNative](image.md#imagesourcenative) \*native, uint32_t \*res) | 从**ImageSource**中获取帧计数。 |
| [OH_ImageSource_GetImageInfo](image.md#oh_imagesource_getimageinfo) (const [ImageSourceNative](image.md#imagesourcenative) \*native, int32_t index, struct [OhosImageSourceInfo](_ohos_image_source_info.md) \*info) | 通过索引从**ImageSource**获取图像源信息。 |
| [OH_ImageSource_GetImageProperty](image.md#oh_imagesource_getimageproperty) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字从**ImageSource**中获取图像源属性。 |
| [OH_ImageSource_ModifyImageProperty](image.md#oh_imagesource_modifyimageproperty) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*key, struct [OhosImageSourceProperty](_ohos_image_source_property.md) \*value) | 通过关键字为**ImageSource**修改图像源属性。 |
| [OH_ImageSource_UpdateData](image.md#oh_imagesource_updatedata) (const [ImageSourceNative](image.md#imagesourcenative) \*native, struct [OhosImageSourceUpdateData](_ohos_image_source_update_data.md) \*data) | 为了增量类型的**ImageSource**更新源数据。 |
| [OH_ImageSource_Release](image.md#oh_imagesource_release) ([ImageSourceNative](image.md#imagesourcenative) \*native) | 释放native层图像源 **ImageSourceNative**。 |
### 变量
| 名称 | 描述 |
| -------- | -------- |
| \*[OHOS_IMAGE_PROPERTY_BITS_PER_SAMPLE](image.md#ohos_image_property_bits_per_sample) = "BitsPerSample" | 定义每个样本比特的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_ORIENTATION](image.md#ohos_image_property_orientation) = "Orientation" | 定义方向的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_IMAGE_LENGTH](image.md#ohos_image_property_image_length) = "ImageLength" | 定义图像长度的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_IMAGE_WIDTH](image.md#ohos_image_property_image_width) = "ImageWidth" | 定义图像宽度的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_GPS_LATITUDE](image.md#ohos_image_property_gps_latitude) = "GPSLatitude" | 定义GPS纬度的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_GPS_LONGITUDE](image.md#ohos_image_property_gps_longitude) = "GPSLongitude" | 定义GPS经度的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_GPS_LATITUDE_REF](image.md#ohos_image_property_gps_latitude_ref) = "GPSLatitudeRef" | 定义GPS纬度参考的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_GPS_LONGITUDE_REF](image.md#ohos_image_property_gps_longitude_ref) = "GPSLongitudeRef" | 定义GPS经度参考的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_DATE_TIME_ORIGINAL](image.md#ohos_image_property_date_time_original) = "DateTimeOriginal" | 定义初始日期时间的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_EXPOSURE_TIME](image.md#ohos_image_property_exposure_time) = "ExposureTime" | 定义曝光时间的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_SCENE_TYPE](image.md#ohos_image_property_scene_type) = "SceneType" | 定义场景类型的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_ISO_SPEED_RATINGS](image.md#ohos_image_property_iso_speed_ratings) = "ISOSpeedRatings" | 定义ISO速度等级的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_F_NUMBER](image.md#ohos_image_property_f_number) = "FNumber" | 定义FNumber的图像属性关键字。 |
| \*[OHOS_IMAGE_PROPERTY_COMPRESSED_BITS_PER_PIXEL](image.md#ohos_image_property_compressed_bits_per_pixel) = "CompressedBitsPerPixel" | 定义每个像素的压缩比特的图像属性关键字。 |
...@@ -30,6 +30,7 @@ ...@@ -30,6 +30,7 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_ColumnType](_r_d_b.md#oh_columntype) | 数据库字段类型. |
| [OH_Cursor](_r_d_b.md#oh_cursor) | 表示结果集。 | | [OH_Cursor](_r_d_b.md#oh_cursor) | 表示结果集。 |
...@@ -37,4 +38,4 @@ ...@@ -37,4 +38,4 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_ColumnType](_r_d_b.md#oh_columntype)&nbsp;{<br/>TYPE_NULL&nbsp;=&nbsp;0,&nbsp;TYPE_INT64,&nbsp;TYPE_REAL,&nbsp;TYPE_TEXT,<br/>TYPE_BLOB<br/>} | 数据库字段类型. | | [OH_ColumnType](_r_d_b.md#oh_columntype) {<br/>TYPE_NULL = 0, TYPE_INT64, TYPE_REAL, TYPE_TEXT,<br/>TYPE_BLOB<br/>} | 数据库字段类型. |
...@@ -28,6 +28,7 @@ ...@@ -28,6 +28,7 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_OrderType](_r_d_b.md#oh_ordertype) | 排序方式。 |
| [OH_Predicates](_r_d_b.md#oh_predicates) | 表示谓词。 | | [OH_Predicates](_r_d_b.md#oh_predicates) | 表示谓词。 |
...@@ -35,4 +36,4 @@ ...@@ -35,4 +36,4 @@
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------- |
| [OH_OrderType](_r_d_b.md#oh_ordertype)&nbsp;{&nbsp;ASC&nbsp;=&nbsp;0,&nbsp;DESC&nbsp;=&nbsp;1&nbsp;} | 排序方式。 | | [OH_OrderType](_r_d_b.md#oh_ordertype) { ASC = 0, DESC = 1 } | 排序方式。 |
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
10 10
**相关模块:** **相关模块**
[RDB](_r_d_b.md) [RDB](_r_d_b.md)
...@@ -25,6 +25,13 @@ ...@@ -25,6 +25,13 @@
| [OH_Rdb_Store](_o_h___rdb___store.md) | 表示数据库类型。 | | [OH_Rdb_Store](_o_h___rdb___store.md) | 表示数据库类型。 |
### 类型定义
| 名称 | 描述 |
| -------- | -------- |
| [OH_Rdb_SecurityLevel](_r_d_b.md#oh_rdb_securitylevel) | 数据库的安全级别枚举。 |
### 枚举 ### 枚举
| 名称 | 描述 | | 名称 | 描述 |
...@@ -41,7 +48,7 @@ ...@@ -41,7 +48,7 @@
| [OH_Rdb_CreatePredicates](_r_d_b.md#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 | | [OH_Rdb_CreatePredicates](_r_d_b.md#oh_rdb_createpredicates) (const char \*table) | 创建[OH_Predicates](_o_h___predicates.md)实例。 |
| [OH_Rdb_GetOrOpen](_r_d_b.md#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 | | [OH_Rdb_GetOrOpen](_r_d_b.md#oh_rdb_getoropen) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config, int \*errCode) | 获得一个相关的[OH_Rdb_Store](_o_h___rdb___store.md)实例,操作关系型数据库。 |
| [OH_Rdb_CloseStore](_r_d_b.md#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 | | [OH_Rdb_CloseStore](_r_d_b.md#oh_rdb_closestore) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store) | 销毁[OH_Rdb_Store](_o_h___rdb___store.md)对象,并回收该对象占用的内存。 |
| [OH_Rdb_DeleteStore](_r_d_b.md#oh_rdb_deletestore) (const char \*path) | 使用指定的数据库文件配置删除数据库。 | | [OH_Rdb_DeleteStore](_r_d_b.md#oh_rdb_deletestore) (const [OH_Rdb_Config](_o_h___rdb___config.md) \*config) | 使用指定的数据库文件配置删除数据库。 |
| [OH_Rdb_Insert](_r_d_b.md#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 | | [OH_Rdb_Insert](_r_d_b.md#oh_rdb_insert) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, const char \*table, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket) | 向目标表中插入一行数据。 |
| [OH_Rdb_Update](_r_d_b.md#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 | | [OH_Rdb_Update](_r_d_b.md#oh_rdb_update) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_VBucket](_o_h___v_bucket.md) \*valuesBucket, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件更新数据库中的数据。 |
| [OH_Rdb_Delete](_r_d_b.md#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 | | [OH_Rdb_Delete](_r_d_b.md#oh_rdb_delete) ([OH_Rdb_Store](_o_h___rdb___store.md) \*store, [OH_Predicates](_o_h___predicates.md) \*predicates) | 根据指定的条件删除数据库中的数据。 |
......
...@@ -860,7 +860,7 @@ ...@@ -860,7 +860,7 @@
## ohos.permission.SET_ABILITY_CONTROLLER ## ohos.permission.SET_ABILITY_CONTROLLER
允许应用拦截Ability组件启动,主要用测试调试,比如稳定性金刚测试。 允许应用拦截Ability组件启动,主要用测试调试,比如稳定性金刚测试。
**权限级别**:system_basic **权限级别**:system_basic
...@@ -1656,7 +1656,7 @@ ...@@ -1656,7 +1656,7 @@
## ohos.permission.CAMERA ## ohos.permission.CAMERA
允许应用使用相机拍摄照片和录制视频 允许应用使用相机。
**权限级别**:normal **权限级别**:normal
......
...@@ -43,8 +43,8 @@ ...@@ -43,8 +43,8 @@
- [资源分类与访问](quick-start/resource-categories-and-access.md) - [资源分类与访问](quick-start/resource-categories-and-access.md)
- 学习ArkTS语言 - 学习ArkTS语言
- [初识ArkTS语言](quick-start/arkts-get-started.md) - [初识ArkTS语言](quick-start/arkts-get-started.md)
- [ArkTS语言介绍](quick-start/arkts/introduction-to-arkts.md) - [ArkTS语言介绍](quick-start/introduction-to-arkts.md)
- [从TypeScript到ArkTS的迁移指导](quick-start/arkts/typescript-to-arkts-migration-guide.md) - [从TypeScript到ArkTS的迁移指导](quick-start/typescript-to-arkts-migration-guide.md)
- UI范式 - UI范式
- 基本语法 - 基本语法
- [基本语法概述](quick-start/arkts-basic-syntax-overview.md) - [基本语法概述](quick-start/arkts-basic-syntax-overview.md)
...@@ -76,11 +76,14 @@ ...@@ -76,11 +76,14 @@
- [其他状态管理概述](quick-start/arkts-other-state-mgmt-functions-overview.md) - [其他状态管理概述](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [\@Watch装饰器:状态变量更改通知](quick-start/arkts-watch.md) - [\@Watch装饰器:状态变量更改通知](quick-start/arkts-watch.md)
- [$$语法:内置组件双向同步](quick-start/arkts-two-way-sync.md) - [$$语法:内置组件双向同步](quick-start/arkts-two-way-sync.md)
- [MVVM模式](quick-start/arkts-mvvm.md)
- [状态管理优秀实践](quick-start/arkts-state-management-best-practices.md)
- 渲染控制 - 渲染控制
- [渲染控制概述](quick-start/arkts-rendering-control-overview.md) - [渲染控制概述](quick-start/arkts-rendering-control-overview.md)
- [if/else:条件渲染](quick-start/arkts-rendering-control-ifelse.md) - [if/else:条件渲染](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach:循环渲染](quick-start/arkts-rendering-control-foreach.md) - [ForEach:循环渲染](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach:数据懒加载](quick-start/arkts-rendering-control-lazyforeach.md) - [LazyForEach:数据懒加载](quick-start/arkts-rendering-control-lazyforeach.md)
- [渲染控制优秀实践](quick-start/arkts-rendering-control-best-practices.md)
- 开发 - 开发
- 应用模型 - 应用模型
- 应用模型概述 - 应用模型概述
...@@ -147,7 +150,6 @@ ...@@ -147,7 +150,6 @@
- [跨端迁移(仅对系统应用开放)](application-models/hop-cross-device-migration.md) - [跨端迁移(仅对系统应用开放)](application-models/hop-cross-device-migration.md)
- [多端协同(仅对系统应用开放)](application-models/hop-multi-device-collaboration.md) - [多端协同(仅对系统应用开放)](application-models/hop-multi-device-collaboration.md)
- [订阅系统环境变量的变化](application-models/subscribe-system-environment-variable-changes.md) - [订阅系统环境变量的变化](application-models/subscribe-system-environment-variable-changes.md)
- [原子化服务支持分享](application-models/atomic-services-support-sharing.md)
- 了解进程模型 - 了解进程模型
- [进程模型概述](application-models/process-model-stage.md) - [进程模型概述](application-models/process-model-stage.md)
- 公共事件 - 公共事件
...@@ -959,7 +961,7 @@ ...@@ -959,7 +961,7 @@
- [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md) - [@ohos.arkui.drawableDescriptor (DrawableDescriptor)](reference/apis/js-apis-arkui-drawableDescriptor.md)
- [@ohos.arkui.inspector (布局回调)](reference/apis/js-apis-arkui-inspector.md) - [@ohos.arkui.inspector (布局回调)](reference/apis/js-apis-arkui-inspector.md)
- [@ohos.arkui.UIContext (UIContext)](reference/apis/js-apis-arkui-UIContext.md) - [@ohos.arkui.UIContext (UIContext)](reference/apis/js-apis-arkui-UIContext.md)
- [@ohos.componentUtils (componentUtils)](reference/apis/js-apis-componentUtils.md) - [@ohos.arkui.componentUtils (componentUtils)](reference/apis/js-apis-arkui-componentUtils.md)
- [@ohos.curves (插值计算)](reference/apis/js-apis-curve.md) - [@ohos.curves (插值计算)](reference/apis/js-apis-curve.md)
- [@ohos.font (注册自定义字体)](reference/apis/js-apis-font.md) - [@ohos.font (注册自定义字体)](reference/apis/js-apis-font.md)
- [@ohos.matrix4 (矩阵变换)](reference/apis/js-apis-matrix4.md) - [@ohos.matrix4 (矩阵变换)](reference/apis/js-apis-matrix4.md)
...@@ -1143,6 +1145,7 @@ ...@@ -1143,6 +1145,7 @@
- [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md) - [@ohos.multimodalInput.touchEvent (触摸输入事件)](reference/apis/js-apis-touchevent.md)
- [@ohos.multimodalInput.shortKey(快捷键)](reference/apis/js-apis-shortKey.md) - [@ohos.multimodalInput.shortKey(快捷键)](reference/apis/js-apis-shortKey.md)
- [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md) - [@ohos.power (系统电源管理)](reference/apis/js-apis-power.md)
- [@ohos.resourceschedule.deviceStandby (设备待机模块)](reference/apis/js-apis-resourceschedule-deviceStandby.md)
- [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md) - [@ohos.runningLock (Runninglock锁)](reference/apis/js-apis-runninglock.md)
- [@ohos.sensor (传感器)](reference/apis/js-apis-sensor.md) - [@ohos.sensor (传感器)](reference/apis/js-apis-sensor.md)
- [@ohos.settings (设置数据项名称)](reference/apis/js-apis-settings.md) - [@ohos.settings (设置数据项名称)](reference/apis/js-apis-settings.md)
...@@ -1772,11 +1775,17 @@ ...@@ -1772,11 +1775,17 @@
- [drawing_text_typography.h](reference/native-apis/drawing__text__typography_8h.md) - [drawing_text_typography.h](reference/native-apis/drawing__text__typography_8h.md)
- [drawing_types.h](reference/native-apis/drawing__types_8h.md) - [drawing_types.h](reference/native-apis/drawing__types_8h.md)
- [external_window.h](reference/native-apis/external__window_8h.md) - [external_window.h](reference/native-apis/external__window_8h.md)
- [image_mdk.h](reference/native-apis/image__mdk_8h.md)
- [image_mdk_common.h](reference/native-apis/image__mdk__common_8h.md)
- [image_pixel_map_mdk.h](reference/native-apis/image__pixel__map__mdk_8h.md)
- [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md) - [image_pixel_map_napi.h](reference/native-apis/image__pixel__map__napi_8h.md)
- [image_receiver_mdk.h](reference/native-apis/image__receiver__mdk_8h.md)
- [image_source_mdk.h](reference/native-apis/image__source__mdk_8h.md)
- [log.h](reference/native-apis/log_8h.md) - [log.h](reference/native-apis/log_8h.md)
- [native_buffer.h](reference/native-apis/native__buffer_8h.md) - [native_buffer.h](reference/native-apis/native__buffer_8h.md)
- [native_image.h](reference/native-apis/native__image_8h.md) - [native_image.h](reference/native-apis/native__image_8h.md)
- [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md) - [native_interface_xcomponent.h](reference/native-apis/native__interface__xcomponent_8h.md)
- [native_xcomponent_key_event.h](reference/native-apis/native__xcomponent__key__event_8h.md)
- [native_vsync.h](reference/native-apis/native__vsync_8h.md) - [native_vsync.h](reference/native-apis/native__vsync_8h.md)
- [raw_dir.h](reference/native-apis/raw__dir_8h.md) - [raw_dir.h](reference/native-apis/raw__dir_8h.md)
- [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md) - [raw_file_manager.h](reference/native-apis/raw__file__manager_8h.md)
...@@ -1830,8 +1839,23 @@ ...@@ -1830,8 +1839,23 @@
- [OH_NativeXComponent_TouchPoint](reference/native-apis/_o_h___native_x_component___touch_point.md) - [OH_NativeXComponent_TouchPoint](reference/native-apis/_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](reference/native-apis/_o_h_ext_data_handle.md) - [OHExtDataHandle](reference/native-apis/_o_h_ext_data_handle.md)
- [OHHDRMetaData](reference/native-apis/_o_h_h_d_r_meta_data.md) - [OHHDRMetaData](reference/native-apis/_o_h_h_d_r_meta_data.md)
- [OHOS::Media::OhosImageComponent](reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_component.md)
- [OHOS::Media::OhosImageRect](reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_image_rect.md)
- [OHOS::Media::OhosPixelMapInfo](reference/native-apis/_o_h_o_s_1_1_media_1_1_ohos_pixel_map_info.md)
- [OhosImageDecodingOps](reference/native-apis/_ohos_image_decoding_ops.md)
- [OhosImageReceiverInfo](reference/native-apis/_ohos_image_receiver_info.md)
- [OhosImageRegion](reference/native-apis/_ohos_image_region.md)
- [OhosImageSize](reference/native-apis/_ohos_image_size.md)
- [OhosImageSource](reference/native-apis/_ohos_image_source.md)
- [OhosImageSourceDelayTimeList](reference/native-apis/_ohos_image_source_delay_time_list.md)
- [OhosImageSourceInfo](reference/native-apis/_ohos_image_source_info.md)
- [OhosImageSourceOps](reference/native-apis/_ohos_image_source_ops.md)
- [OhosImageSourceProperty](reference/native-apis/_ohos_image_source_property.md)
- [OhosImageSourceSupportedFormat](reference/native-apis/_ohos_image_source_supported_format.md)
- [OhosImageSourceSupportedFormatList](reference/native-apis/_ohos_image_source_supported_format_list.md)
- [OhosImageSourceUpdateData](reference/native-apis/_ohos_image_source_update_data.md)
- [OhosPixelMapCreateOps](reference/native-apis/_ohos_pixel_map_create_ops.md) - [OhosPixelMapCreateOps](reference/native-apis/_ohos_pixel_map_create_ops.md)
- [OhosPixelMapInfo](reference/native-apis/_ohos_pixel_map_info.md) - [OhosPixelMapInfos](reference/native-apis/_ohos_pixel_map_infos.md)
- [RawFileDescriptor](reference/native-apis/_raw_file_descriptor.md) - [RawFileDescriptor](reference/native-apis/_raw_file_descriptor.md)
- [Region](reference/native-apis/_region.md) - [Region](reference/native-apis/_region.md)
- [Rect](reference/native-apis/_rect.md) - [Rect](reference/native-apis/_rect.md)
......
...@@ -157,8 +157,9 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及 ...@@ -157,8 +157,9 @@ OpenHarmony是由开放原子开源基金会(OpenAtom Foundation)孵化及
2. 了解发行版详情。 2. 了解发行版详情。
1. 仔细阅读发行版的说明信息,以了解使用场景、特性、组件构成、使用方法以及如何进行定制化,如下图所示。 1. 仔细阅读发行版的说明信息,以了解使用场景、特性、组件构成、使用方法以及如何进行定制化,如下图所示。
2. 点击「直接下载」,将发行版下载到本地。 2. 当前支持两种下载方式:
3. 点击「设备组件裁剪」,将对发行版包含的组件进行定制(添加/删除)。 - 点击「直接下载」,将发行版下载到本地。
- 点击「设备组件裁剪」,将对发行版包含的组件进行定制(添加/删除)。
**图2** 发行版示例 **图2** 发行版示例
......
...@@ -13,53 +13,39 @@ ...@@ -13,53 +13,39 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 如需安装代理,请参考[配置代理](quickstart-pkg-common-proxy.md)。 > 如需安装代理,请参考[配置代理](quickstart-pkg-common-proxy.md)。
1. 运行如下命令安装hb并更新至最新版本 1. 在源码根目录运行如下命令安装hb并更新至最新版本。
``` ```shell
pip3 install --user build/lite python3 -m pip install --user build/hb
``` ```
2. 设置环境变量 2. 设置环境变量
``` ```shell
vim ~/.bashrc vim ~/.bashrc
``` ```
将以下命令拷贝到.bashrc文件的最后一行,保存并退出。 将以下命令拷贝到.bashrc文件的最后一行,保存并退出。
``` ```shell
export PATH=~/.local/bin:$PATH export PATH=~/.local/bin:$PATH
``` ```
执行如下命令更新环境变量。 执行如下命令更新环境变量。
``` ```shell
source ~/.bashrc source ~/.bashrc
``` ```
3. 在源码目录执行"hb -h",界面打印以下信息即表示安装成功: 3. 在源码目录执行"hb help",界面打印以下信息即表示安装成功。
``` ![hb_help](figures/hb_help.png)
usage: hb
OHOS build system
positional arguments:
{build,set,env,clean}
build Build source code
set OHOS build settings
env Show OHOS build env
clean Clean output
optional arguments:
-h, --help show this help message and exit
```
> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:**
> - 可采用以下命令卸载hb: > - 可采用以下命令卸载hb:
> >
> ``` > ```shell
> pip3 uninstall ohos-build > python3 -m pip uninstall ohos-build
> ``` > ```
> >
> - 若安装hb的过程中遇到问题,请参见下文[常见问题](quickstart-pkg-common-hberr.md)进行解决。 > - 若安装hb的过程中遇到问题,请参见下文[常见问题](quickstart-pkg-common-hberr.md)进行解决。
...@@ -78,25 +64,25 @@ ...@@ -78,25 +64,25 @@
3. 解压LLVM安装包至~/llvm路径下。 3. 解压LLVM安装包至~/llvm路径下。
``` ```shell
tar -zxvf llvm.tar -C ~/ tar -zxvf llvm.tar -C ~/
``` ```
4. 设置环境变量。 4. 设置环境变量。
``` ```shell
vim ~/.bashrc vim ~/.bashrc
``` ```
将以下命令拷贝到.bashrc文件的最后一行,保存并退出。 将以下命令拷贝到.bashrc文件的最后一行,保存并退出。
``` ```shell
export PATH=~/llvm/bin:$PATH export PATH=~/llvm/bin:$PATH
``` ```
5. 生效环境变量。 5. 生效环境变量。
``` ```shell
source ~/.bashrc source ~/.bashrc
``` ```
...@@ -191,3 +191,9 @@ HiDumper可以为开发者导出系统当前基本信息,通过这些基本信 ...@@ -191,3 +191,9 @@ HiDumper可以为开发者导出系统当前基本信息,通过这些基本信
``` ```
hidumper -t [timeout] hidumper -t [timeout]
``` ```
19. 运行 hidumper --mem-smaps pid [-v] 命令获取指定进程内存信息的详细使用情况。
```
hidumper --mem-smaps pid [-v]
```
# arkui子系统ChangeLog
## cl.arkui.1 TextInput、TextArea、Search组件行为变更
arkui子系统TextInput、TextArea、Search组件行为存在变更:
- 获焦默认拉起输入法
开发者需要根据以下说明对应用进行适配。
**变更影响**
影响Api version 10的TextInput、TextArea、Search组件
**关键的接口/组件变更**
- TextInput、TextArea、Search组件获焦会拉起输入法
**适配指导**
不同场景下的启动规则说明如下:
开发者适配内容:
- TextInput、TextArea、Search组件获焦会拉起输入法
- 通过接口enableKeyboardOnFocus(bool)控制是否获焦拉起输入法,此接口参数默认值为true。
...@@ -7,3 +7,42 @@ FormComponent组件中的JS卡片禁止使用网络图片。 ...@@ -7,3 +7,42 @@ FormComponent组件中的JS卡片禁止使用网络图片。
**变更影响** **变更影响**
影响FormComponent中JS卡片中网络图片的加载显示。变更前JS卡片支持网络图片加载,变更后JS卡片不支持网络图片的加载。变更后建议将所需的网络图片下载至内存后刷新。 影响FormComponent中JS卡片中网络图片的加载显示。变更前JS卡片支持网络图片加载,变更后JS卡片不支持网络图片的加载。变更后建议将所需的网络图片下载至内存后刷新。
## cl.arkui.2 TextInput、TextArea、Search组件行为变更
TextInput、TextArea、Search组件获焦默认拉起输入法
开发者需要根据以下说明对应用进行适配。
**变更影响**
影响Api version 10的TextInput、TextArea、Search组件
**关键的接口/组件变更**
TextInput、TextArea、Search组件获焦会拉起输入法
**适配指导**
可以通过接口enableKeyboardOnFocus(bool)控制是否获焦拉起输入法,此接口参数默认值为true。
## cl.arkui.3 组件属性以及参数非法值拦截
非法值使用默认值
开发者需要根据以下说明对应用进行适配。
**变更影响**
影响所有设置了非法值的组件属性
**关键的接口/组件变更**
原先属性值由正常值变为非法值会跳过非法值的设置,变更后会拦截非法值并设置属性的默认值。对于没有默认值的属性如width、height等,则会取消其原先的正常值设置。
**适配指导**
组件属性以及参数非法值拦截排查非法值如"100abc"等,将其改为正常值。
...@@ -226,4 +226,38 @@ API version 10及以后:onReady在组件创建完成时触发,在组件位 ...@@ -226,4 +226,38 @@ API version 10及以后:onReady在组件创建完成时触发,在组件位
**变更影响** **变更影响**
onReady事件在组件位置发生变化时行为变更,API version 9及以前会触发,API version 10及以后不会触发。 onReady事件在组件位置发生变化时行为变更,API version 9及以前会触发,API version 10及以后不会触发。
\ No newline at end of file
## cl.arkui.4 Margin属性百分比计算变更
当前margin会计算两次,margin的百分比参照在第一次margin计算之后会减去margin的大小,计算完之后百分比类型margin第二次计算时数值偏小。变更后margin第一次计算的结果为最终值,不进行第二次计算。
**变更影响**
所有设置百分比的margin大小。
**错误示例:**
```ts
// xxx.ets
@Entry
@Component
struct TextInputExample {
@State text: string = ''
controller: TextInputController = new TextInputController()
build() {
Column(){
Row().margin({left:"50%"}).width(100).height(100)
}.width("100%").height("100%")
}
}
```
**关键接口/组件变更**
不涉及
**适配指导**
变更后margin的百分比参照固定为父组件的宽减去父组件的padding且不会减去第一次margin的计算结果,其百分比参照比变更前稍大,建议调整margin百分比的数值。
\ No newline at end of file
# 分布式数据管理子系统ChangeLog
## cl.distributeddatamgr.1 OH_Cursor结构体的函数指针成员变量**int** (*close)(OH_Cursor *cursor)变更为**int** (*destroy)(OH_Cursor *cursor)
**变更影响**
该变更为不兼容变更,函数指针名称由close更改为destroy,入参及返回值均未更改。
**关键接口/组件变更**
修改前的OH_Cursor该成员变量原型:
```ts
int (*close)(OH_Cursor *cursor);
```
修改后的OH_Predicates成员变量原型:
```ts
int (*destroy)(OH_Cursor *cursor);
```
**适配指导**
示例代码如下:
变更前代码示例:
```
cursor->close(cursor);
```
变更后代码示例:
```
cursor->destroy(cursor);
```
## cl.distributeddatamgr.2 OH_Predicates结构体的函数指针成员变量**int** (*destroyPredicates)(OH_Predicates *predicates)变更为 **int** (*destroy)(OH_Predicates *predicates)
**变更影响**
该变更为不兼容变更,函数指针名称由destroyPredicates更改为destroy,入参及返回值均未更改。
**关键接口/组件变更**
修改前的OH_Predicates该成员变量原型:
```ts
int (*destroyPredicates)(OH_Predicates *predicates);
```
修改后的OH_Predicates成员变量原型:
```ts
int (*destroy)(OH_Predicates *predicates);
```
**适配指导**
示例代码如下:
变更前代码示例:
```
predicates->destroyPredicates(predicates);
```
变更后代码示例:
```
predicates->destroy(predicates);
```
## cl.distributeddatamgr.3 OH_VObject结构体的函数指针成员变量**int** (*destroyValueObject)(OH_VObject *valueObject)变更为 **int** (*destroy)(OH_VObject *valueObject)
**变更影响**
该变更为不兼容变更,函数指针名称由destroyValueObject更改为destroy,入参及返回值均未更改。
**关键接口/组件变更**
修改前的OH_VObject该成员变量原型:
```ts
int (*destroyValueObject)(OH_VObject *valueObject);
```
修改后的OH_Predicates成员变量原型:
```ts
int (*destroy)(OH_VObject *valueObject);
```
**适配指导**
示例代码如下:
变更前代码示例:
```
valueObject->destroyValueObject(valueObject);
```
变更后代码示例:
```
valueObject->destroy(valueObject);
```
## cl.distributeddatamgr.4 OH_VBucket结构体的函数指针成员变量**int** (*destroyValuesBucket)(OH_VBucket *bucket)变更为 int (*destroy)(OH_VBucket *bucket)
**变更影响**
该变更为不兼容变更,函数指针名称由destroyValuesBucket更改为destroy,入参及返回值均未更改。
**关键接口/组件变更**
修改前的OH_VBucket该成员变量原型:
```ts
int (*destroyValuesBucket)(OH_VBucket *bucket);
```
修改后的OH_Predicates成员变量原型:
```ts
int (*destroy)(OH_VBucket *bucket);
```
**适配指导**
示例代码如下:
变更前代码示例:
```
valueBucket->destroyValuesBucket(valueBucket);
```
变更后代码示例:
```
valueBucket->destroy(valueBucket);
```
## cl.distributeddatamgr.5 OH_Rdb_Config结构体成员变量变更
**变更影响**
该变更为不兼容变更,将成员变量securityLevel的类型由enum OH_Rdb_SecurityLevel改为in;删除成员变量path;并新增成员变量selfSize、dataBaseDir、storeName、bundleName、moduleName。
**关键接口/组件变更**
修改前的OH_Rdb_Config:
```ts
typedef struct {
const char *path;
bool isEncrypt;
enum OH_Rdb_SecurityLevel securityLevel;
} OH_Rdb_Config;
```
修改后的OH_Rdb_Config:
```ts
typedef struct {
int selfSize;
const char *dataBaseDir;
const char *storeName;
const char *bundleName;
const char *moduleName;
bool isEncrypt;
int securityLevel;
} OH_Rdb_Config;
```
**适配指导**
用户在利用OH_Rdb_Config创建数据库时,需要传入包名以及模块名等信息。
## cl.distributeddatamgr.6 **OH_Rdb_DeleteStore**接口入参**const** **char** *pat变更为**const** OH_Rdb_Config *config
**变更影响**
该变更为不兼容变更,函数入参由const char *path变更为const OH_Rdb_Config *config。
**关键接口/组件变更**
修改前OH_Rdb_DeleteStore接口:
```ts
int OH_Rdb_DeleteStore(const char *path);
```
修改后OH_Rdb_DeleteStore接口:
```ts
int OH_Rdb_DeleteStore(const OH_Rdb_Config *config);
```
**适配指导**
示例代码如下:
变更前代码示例:
```
OH_Rdb_DeleteStore(“”)
```
变更后代码示例:
```
OH_Rdb_DeleteStore(config)
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册