diff --git a/CODEOWNERS b/CODEOWNERS index 63dee6787f1bea126047ec423f333ad3de9fe5e9..f395d69420381a4e61268211787acd0cff417ec5 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -243,7 +243,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-system-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-settings.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-settings.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-document.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-environment.md @qinxiaowang @@ -261,15 +261,18 @@ zh-cn/application-dev/reference/apis/js-apis-sms.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-request.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-wifi.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -277,34 +280,34 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-system-time.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-brightness.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-device-info.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-device-manager.md zh-cn/application-dev/reference/apis/js-apis-geolocation.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-power.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-power.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-sensor.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-thermal.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-thermal.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-update.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-vibrator.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-appAccount.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-osAccount.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-osAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-convertxml.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-process.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-uri.md @zengyawen @@ -344,4 +347,5 @@ zh-cn/application-dev/quick-start/syscap.md @RayShih zh-cn/application-dev/napi/napi-guidelines.md @RayShih zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen \ No newline at end of file +zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen +zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease \ No newline at end of file diff --git a/README.md b/README.md index 7e19add93fd8c1818e41387bfd4c8ad34efa2b71..0b1fe4ea284ed5df055c0031d96d3cfb759948a3 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,11 @@ This repository stores device and application development documents provided by - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) + This version is upgraded to OpenHarmony 3.1.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.1.1-release.md) + - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) - This version is upgraded to OpenHarmony 3.0.3 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.3-LTS.md) + This version is upgraded to OpenHarmony 3.0.5 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.5-LTS.md) - OpenHarmony 2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) @@ -41,10 +43,14 @@ OpenHarmony_v1.x_release: OpenHarmony v1.1.4 LTS. [Learn more](en/release-notes/ Third-party license: [Third-Party Open-Source Software and License Notice](en/contribute/third-party-open-source-software-and-license-notice.md) -## How to Contribute +## Contribution A great open-source project wouldn't be possible without the hard work of many contributors. We'd like to invite anyone from around the world to [participate](en/contribute/how-to-contribute.md) in this exciting journey, and we're grateful for your time, passion, and efforts! You can evaluate available documents, make simple modifications, provide feedback on document quality, and contribute your original content. For details, see [Documentation Contribution](en/contribute/documentation-contribution.md). Excellent contributors will be awarded and the contributions will be publicized in the developer community. + +- Mail list: docs@openharmony.io + +- Zulip group: documentation_sig \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile index 70560a93c1dd890bf8b6ff1d9f03d2e778adbfe0..46dd8e3d0fe4ee945af2b5e0154ee0b876850d1a 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -35,14 +35,15 @@ RUN sed -i "s@http://.*archive.ubuntu.com@http://repo.huaweicloud.com@g" /etc/ap && pip3 install six --upgrade --ignore-installed six \ && mkdir -p /home/tools \ && mkdir -p /home/tools/gn \ - && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/clang/10.0.1-62608/linux/llvm.tar.gz \ + && wget -P /home/tools https://repo.huaweicloud.com/openharmony/compiler/clang/12.0.1-530132/linux/clang-530132-linux-x86_64.tar.bz2 \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/gcc_riscv32/7.3.0/linux/gcc_riscv32-linux-7.3.0.tar.gz \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/ninja/1.9.0/linux/ninja.1.9.0.tar \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/gn/1717/linux/gn-linux-x86-1717.tar.gz \ && wget -P /home/tools https://mirrors.huaweicloud.com/nodejs/v14.15.4/node-v14.15.4-linux-x64.tar.xz \ && wget -P /home/tools https://hm-verify.obs.cn-north-4.myhuaweicloud.com/qemu-5.2.0.tar.xz \ - && tar -xvf /home/tools/llvm.tar.gz -C /home/tools \ + && tar -jxvf /home/tools/clang-530132-linux-x86_64.tar.bz2 -C /home/tools \ + && mv /home/tools/clang-530132 /home/tools/llvm \ && tar -xvf /home/tools/hc-gen-0.65-linux.tar -C /home/tools \ && tar -xvf /home/tools/gcc_riscv32-linux-7.3.0.tar.gz -C /home/tools \ && tar -xvf /home/tools/ninja.1.9.0.tar -C /home/tools \ diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 75a605c39be73f29e1db8cecf988535c5495ee4a..48270359d9d49f9ea7d7111b021cd8b81da3df82 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -30,7 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music }, onConnect(want) { console.log('ServiceAbility OnConnect'); - return null; + return new FirstServiceAbilityStub('test'); }, onDisconnect(want) { console.log('ServiceAbility OnDisConnect'); @@ -113,8 +113,6 @@ let promise = featureAbility.startAbility( Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. - - ### Connecting to a Local Service Ability If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. @@ -124,7 +122,7 @@ You can use either of the following methods to connect to a Service ability: 1. Using the IDL to automatically generate code - Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts). + Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see “Development Using TS" in [OpenHarmony IDL Specifications and User Guide](../IDL/idl-guidelines.md). 2. Writing code in the corresponding file @@ -134,42 +132,37 @@ You can use either of the following methods to connect to a Service ability: ```javascript import prompt from '@system.prompt' - - let mRemote; - function onConnectCallback(element, remote){ - console.log('onConnectLocalService onConnectDone element: ' + element); - console.log('onConnectLocalService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectLocalService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); + + var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectLocalService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectLocalService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); - - } - - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect Callback') - } - - function onFailedCallback(code){ - console.log('ConnectAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectLocalService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectLocalService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -196,45 +189,28 @@ You can use either of the following methods to connect to a Service ability: ```javascript import rpc from "@ohos.rpc"; - - let mMyStub; - export default { - onStart() { - class MyStub extends rpc.RemoteObject{ - constructor(des) { - if (typeof des === 'string') { - super(des); - } - return null; - } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); - if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); - } else { - console.log("ServiceAbility unknown request code"); - } - return true; - } - } - mMyStub = new MyStub("ServiceAbility-test"); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return mMyStub; - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - }, + + class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des) + } else { + return + } + } + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) + if (code === 1) { + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) + } else { + console.log(printLog + ` unknown request code`) + } + return true; } ``` @@ -253,40 +229,36 @@ The following code snippet shows how to implement the callbacks: ```ts import prompt from '@system.prompt' -let mRemote; -function onConnectCallback(element, remote){ - console.log('onConnectRemoteService onConnectDone element: ' + element); - console.log('onConnectRemoteService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectRemoteService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); +var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectRemoteService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectRemoteService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); -} - -function onDisconnectCallback(element){ - console.log('ConnectRemoteAbility onDisconnect Callback') -} - -function onFailedCallback(code){ - console.log('ConnectRemoteAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectRemoteService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectRemoteService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -372,23 +344,25 @@ The following code snippet shows how the Service ability instance returns itself ```ts import rpc from "@ohos.rpc"; -class FirstServiceAbilityStub extends rpc.RemoteObject{ - constructor(des) { +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { if (typeof des === 'string') { - super(des); + super(des) } else { - return null; + return } } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) } else { - console.log("ServiceAbility unknown request code"); + console.log(printLog + ` unknown request code`) } return true; } diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 9f7ccd0d08e8683aca6e6c86ddef80f8e0e5aad4..a8aff91550cb265137a89d8718f6232c34e1aa43 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -3,12 +3,19 @@ - Distributed Data Service - [Distributed Data Service Overview](database-mdds-overview.md) - [Distributed Data Service Development](database-mdds-guidelines.md) + - Relational Database - [RDB Overview](database-relational-overview.md) - [RDB Development](database-relational-guidelines.md) + - Preferences - [Preferences Overview](database-preference-overview.md) - [Preferences Development](database-preference-guidelines.md) + - Distributed Data Object - [Distributed Data Object Overview](database-distributedobject-overview.md) - [Distributed Data Object Development](database-distributedobject-guidelines.md) + +- Data Share + - [DataShare Overview](database-datashare-overview.md) + - [DataShare Development](database-datashare-guidelines.md) diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..251c33fbc54aadba8aa07b92f0292ab86f322d70 --- /dev/null +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -0,0 +1,191 @@ +# DataShare Development +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. + +## Available APIs + +**Table 1** APIs of the data provider + +|API|Description| +|:------|:------| +|onCreate?(want: Want, callback: AsyncCallback<void>): void|Called to initialize service logic when the data provider application is created, for example, when a database is created.| +|insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Inserts data into the database.| +|update?(uri: string, predicates: DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Updates data in the database.| +|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.| +|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.| + +For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). + +**Table 2** APIs of the data consumer + +| API | Description | +| :----------------------------------------------------------- | :--------------------------------- | +| createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance. | +| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a single data record into the database. | +| update(uri: string, predicates: DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database. | +| query(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data from the database. | +| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database.| + +For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md). + +## When to Use + +**DataShare** can be divided into the following: + +- Data provider: Implement functions of adding, deleting, modifying, and querying data, and opening files, and share data. +- Data consumer: Access the data provided by the provider using **DataShareHelper**. + +Examples are given below. + +### Data Provider Application Development (Only for System Applications) + +1. Import the dependencies. + + ```ts + import Extension from '@ohos.application.DataShareExtensionAbility' + import rdb from '@ohos.data.rdb'; + import fileIo from '@ohos.fileio' + import dataSharePredicates from '@ohos.data.dataSharePredicates' + ``` + +2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the query() API. + +3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. + + ```ts + let DB_NAME = "DB00.db"; + let TBL_NAME = "TBL00"; + let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + + let rdbStore; + let result; + + export default class DataShareExtAbility extends Extension { + private rdbStore_; + + // Override the onCreate() API. + onCreate(want, callback) { + result = this.context.cacheDir + '/datashare.txt' + // Create an RDB. + rdb.getRdbStore(this.context, { + name: DB_NAME + }, 1, function (err, data) { + rdbStore = data; + rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); + }); + callback(); + }); + } + + // Override the query() API. + query(uri, predicates, columns, callback) { + if (predicates == null || predicates == undefined) { + console.info('invalid predicates'); + } + try { + rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + if (resultSet != undefined) { + console.info('resultSet.rowCount: ' + resultSet.rowCount); + } + if (callback != undefined) { + callback(err, resultSet); + } + }); + } catch (err) { + console.error('error' + err); + } + } + // Override other APIs as required. + // ... + }; + ``` + +4. Define **DataShareExtensionAbility** in **module.json5**. + + | Field| Description | + | ------------ | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **Datashare** template.| + | "uri" | URI used for communication. It is the unique identifier for the client to connect to the server. | + | "visible" | Whether it is visible to other applications. Communication with other applications is allowed only when the value is **true**.| + + **module.json5 example** + + ```json + "extensionAbilities": [ + { + "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", + "name": "DataShareExtAbility", + "icon": "$media:icon", + "description": "$string:description_datashareextability", + "type": "dataShare", + "uri": "datashare://com.samples.datasharetest.DataShare", + "visible": true + } + ] + ``` + +### Data Consumer Application Development + +1. Import basic dependencies. + + ```ts + import Ability from '@ohos.application.Ability' + import dataShare from '@ohos.data.dataShare' + import dataSharePredicates from '@ohos.data.dataSharePredicates' + ``` + +2. Define the URI string for communicating with the data provider. + + ```ts + // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). + let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); + ``` + +2. Create a **DataShareHelper** instance. + + ```ts + let dsHelper; + let abilityContext; + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + abilityContext = this.context; + dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{ + dsHelper = data; + }); + } + } + ``` + +3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. + + ```ts + // Construct a piece of data. + var valuesBucket = {"name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1,2,3])}; + var updateBucket = {"name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1,2,3])}; + let da = new dataSharePredicates.DataSharePredicates(); + var valArray =new Array("*"); + let people = new Array( + {"name": "LiSi", "age": 41, "Binary": ar}, + {"name": "WangWu", "age": 21, "Binary": arr}, + {"name": "ZhaoLiu", "age": 61, "Binary": arr}); + // Insert a piece of data. + dsHelper.insert(dseUri, valuesBucket, (err,data) => { + console.log("dsHelper insert result: " + data); + }); + // Delete the specified data. + dsHelper.delete(dseUri, da, (err,data) => { + console.log("dsHelper delete result: " + data); + }); + // Update data. + dsHelper.update(dseUri, da, updateBucket, (err,data) => { + console.log("dsHelper update result: " + data); + }); + // Query data. + dsHelper.query(dseUri, da, valArray, (err,data) => { + console.log("dsHelper query result: " + data); + }); + ``` + diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..857e9fa4205cd0545803643af1515da485b83d8a --- /dev/null +++ b/en/application-dev/database/database-datashare-overview.md @@ -0,0 +1,54 @@ +# DataShare Overview + +## Introduction + +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. + +**DataShare** is used in application scenarios, such as contacts, short message service (SMS), and media gallery. However, not all data, such as accounts and passwords, can be accessed by other applications. Some data, such as SMS messages, can only be queried by other applications. **DataShare** provides a secure data sharing mechanism for applications. + +The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty. + +## Basic Concepts + + +Before you get started, familiarize yourself with the following concepts: + + +- Data provider + + An application that provides data and implements related services. It is also called a producer or server. + +- Data consumer + + An application that accesses the data or services provided by a data provider. It is also called a client. + +- Value bucket (**ValuesBucket**) + + One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. + +- Result set + + A collection of query results. Flexible data access modes are provided for users to obtain data. + +- Predicate + + Conditions specified for updating, deleting, or querying data in the database. + +## Working Principles + +**Figure 1** DataShare mechanism + + +![](figures/en_DataShare.png) + +- The **DataShareExtAbility** module, as the data provider, implements data sharing between applications. +- The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data. +- The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage. + +- The **ResultSet** module is implemented through shared memory. Share memory stores the result sets, and interfaces are provided to traverse result sets. + +## Constraints + +- **DataShare** is subject to the limitations on the database used by the data provider. For example, the supported data models, length of the keys and values, and maximum number of databases that can be accessed at a time by each application vary with the database in use. + +- The payloads of **ValuesBucket**, predicates, and result sets are restricted by IPC. diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index b56401dbedca72e76af3b15efdd63883885bf3d6..7f93b1ca5684d4268ca7fe46e35442a776a3b201 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -74,6 +74,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>): void |Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to query.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to query.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates @@ -85,34 +87,34 @@ The RDB provides **RdbPredicates** for you to set database operation conditions. | -------- | -------- | -------- | | RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| | RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| | RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| | RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| | RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| +| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| +| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNull(field: string): RdbPredicates | Sets an **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets an **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets ta **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets an **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets an **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | distinct(): RdbPredicates | Sets an **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| +| RdbPredicates | limitAs(value: number): RdbPredicates | Sets an **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| | RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets an **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| +| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets an **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| +| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| ### Using the Result Set @@ -131,8 +133,8 @@ A result set can be regarded as a row of data in the queried results. It allows | ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| | ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| | ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| -| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| +| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set.| +| ResultSet | goToLastRow(): boolean | Moves to the last row of the result set.| | ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| | ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| | ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| @@ -162,7 +164,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | +| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned.| | RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** @@ -172,7 +174,7 @@ You can obtain the distributed table name for a remote device based on the local | Class| API| Description| | -------- | -------- | -------- | | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This API uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.| **Registering an RDB Store Observer** @@ -210,6 +212,16 @@ You can obtain the distributed table name for a remote device based on the local | RdbStore |restore(srcName:string, callback: AsyncCallback<void>):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
- **srcName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| | RdbStore |restore(srcName:string): Promise<void>| Restores an RDB store using a backup file. This API uses a promise to return the result.
- **srcName**: name of the RDB backup file.| +**Transaction** + +Table 15 Transaction APIs + +| Class| API| Description| +| -------- | -------- | -------- | +| RdbStore |beginTransaction():void| Starts the transaction before executing SQL statements.| +| RdbStore |commit():void| Commits the executed SQL statements.| +| RdbStore |rollBack():void| Rolls back the SQL statements that have been executed.| + ## How to Develop 1. Create an RDB store. @@ -270,17 +282,17 @@ You can obtain the distributed table name for a remote device based on the local const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) resultSet.close() }) - ``` + ``` 4. Set the distributed tables to be synchronized. (1) Add the following permission to the permission configuration file: - ```js + ```json "requestPermissions": - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } ``` (2) Obtain the required permissions. @@ -321,7 +333,7 @@ You can obtain the distributed table name for a remote device based on the local promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + ' status=' + result[i][1]) + console.log('device=' + result[i][0] + 'status=' + result[i][1]) } }).catch((err) => { console.log('sync failed') @@ -339,7 +351,7 @@ You can obtain the distributed table name for a remote device based on the local ```js function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { - console.log('device=' + device[i] + ' data changed') + console.log('device=' + device[i] + 'data changed') } } try { @@ -361,8 +373,34 @@ You can obtain the distributed table name for a remote device based on the local let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` - -8. Back up and restore an RDB store. + +8. Query data of a remote device. + + + (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. + + (2) Call the resultSet() API to obtain the result. + + The sample code is as follows: + + ```js + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + promiseQuery.then((resultSet) => { + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); + console.info(idx + " " + name + " " + age); + } + resultSet.close(); + }).catch((err) => { + console.info("failed to remoteQuery, err: " + err) + }) + ``` + +9. Back up and restore an RDB store. (1) Back up the current RDB store. @@ -372,23 +410,17 @@ You can obtain the distributed table name for a remote device based on the local ```js let promiseBackup = rdbStore.backup("dbBackup.db") - promiseBackup.then(()=>{ + promiseBackup.then(() => { console.info('Backup success.') - }).catch((err)=>{ + }).catch((err) => { console.info('Backup failed, err: ' + err) }) ``` ```js let promiseRestore = rdbStore.restore("dbBackup.db") - promiseRestore.then(()=>{ + promiseRestore.then(() => { console.info('Restore success.') - }).catch((err)=>{ + }).catch((err) => { console.info('Restore failed, err: ' + err) }) ``` - -## Samples -The following samples are provided for you to better understand the RDB development: -- [`Rdb`: eTS RDB (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) -- [`DistributedRdb`: eTS Distributed Relational Database (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) -- [Relational Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) diff --git a/en/application-dev/database/figures/en_DataShare.png b/en/application-dev/database/figures/en_DataShare.png new file mode 100644 index 0000000000000000000000000000000000000000..e0243b935e8cc61d61c5f572a20c66aadc5edbd3 Binary files /dev/null and b/en/application-dev/database/figures/en_DataShare.png differ diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index fb107049c515d0ff1961313a9f0bebb39c4e4c9d..01fe1ed68b3eb05341438da3d81270afdc4a92e3 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -421,13 +421,13 @@ import stats from '@ohos.bundleState'; ```javascript import stats from '@ohos.bundleState' - //promise + // Promise mode stats.unRegisterGroupCallBack().then(() => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); }).catch(err => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); }); - //callback + // Asynchronous callback mode stats.unRegisterGroupCallBack((err) => { if (err) { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index a32decd05ac0ba0d6db06749c18dcd31d3a7645b..c61c9288eecb35ce4235fb00ce91b595b9160b44 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -84,7 +84,7 @@ To learn more about the APIs for obtaining device location information, see [Geo } ``` - For details about the fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index e58eed34cccb7dd820e1144a616dfb93a10f4d34..86854eb072b19c7ee359dcb70413ce22580cb8f7 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -14,6 +14,7 @@ You can `import` the native .so that contains the JS processing logic. For examp * Add **static** to the **nm_register_func** function to prevent symbol conflicts with other .so files. * The name of the module registration entry, that is, the function decorated by **\_\_attribute\_\_((constructor))**, must be unique. + ### .so Naming Rules Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. @@ -25,6 +26,10 @@ The Ark engine prevents NAPIs from being called to operate JS objects in non-JS * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. +### Importing Header Files + +Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, when only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. + ### napi_create_async_work **napi_create_async_work** has two callbacks: @@ -635,3 +640,8 @@ export default { } } ``` +## Samples +The following samples are provided for native API development: +- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) +- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) +- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 8450f3d8c7f6d0ddfed16215bc8345c2b036c400..d5a6d7bdfbc6dcdd5b94d36e155d4650fc70630c 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -98,11 +98,11 @@ import commonEvent from '@ohos.commonEvent'; ```js // Publish a common event. commonEvent.publish("event", (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish1") - } + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish1") + } }) ``` @@ -118,8 +118,8 @@ import commonEvent from '@ohos.commonEvent' ```js // Attributes of a common event. var options = { - code: 1, // Result code of the common event - data: "initial data";// Result data of the common event + code: 1, // Result code of the common event + data: "initial data",// Result data of the common event } ``` @@ -128,11 +128,11 @@ var options = { ```js // Publish a common event. commonEvent.publish("event", options, (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish2") - } + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish2") + } }) ``` diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index f216c6b08806daa6c5bc87471a3effd749130094..ef0e355c63726bc167dac72801adfdce030827f3 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -89,7 +89,7 @@ Adds an app account name and additional information (information that can be con ### addAccount -addAccount(name: string, extraInfo: string): Promise<void> +addAccount(name: string, extraInfo?: string): Promise<void> Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result. @@ -100,7 +100,7 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| +| extraInfo | string | No | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| **Return value** @@ -1696,7 +1696,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | labels | Array<string> | Yes | Labels to check. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1710,7 +1710,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous ### checkAccountLabels9+ -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<void> +checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> Checks whether an app account has specific labels. This API uses a promise to return the result. @@ -1771,7 +1771,7 @@ Selects the accounts accessible to the requester based on the options. This API ### selectAccountsByOptions9+ -selectAccountsByOptions(options: SelectAccountsOptions): Promise<void> +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result. @@ -1836,7 +1836,7 @@ Verifies the user credential. This API uses an asynchronous callback to return t ### verifyCredential9+ -verifyCredential(name: string, owner: string, options, callback: AuthenticatorCallback): void; +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; Verifies the user credential. This API uses an asynchronous callback to return the result. @@ -1952,11 +1952,11 @@ Defines OAuth token information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | -------- | -| authType | string | Yes | Authentication type.| -| token | string | Yes | Value of the token. | -| account9+ | AppAccountInfo | No | Account information of the token. | +| Name | Type | Mandatory | Description | +| -------------------- | -------------- | ----- | ---------------- | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Value of the token. | +| account9+ | AppAccountInfo | No | Account information of the token.| ## AuthenticatorInfo8+ @@ -1978,7 +1978,7 @@ Represents the options for selecting accounts. | Name | Type | Mandatory | Description | | --------------- | --------------------------- | ----- | ------------------- | -| allowedAccounts | Array<[AppAccountInfo](#appAccountinfo)> | No | Allowed accounts. | +| allowedAccounts | Array<[AppAccountInfo](#appaccountinfo)> | No | Allowed accounts. | | allowedOwners | Array<string> | No | Allowed account owners.| | requiredLabels | Array<string> | No | Labels required for the authenticator. | @@ -2012,21 +2012,21 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | -| KEY_OWNER | "owner" | Owner of an app account.| -| KEY_TOKEN | "token" | Token. | -| KEY_ACTION | "action" | Operation. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | PID of the caller. | -| KEY_CALLER_UID | "callerUid" | UID of the caller. | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | -| KEY_REQUIRED_LABELS | "requiredLabels" | Required labels. | -| KEY_BOOLEAN_RESULT | "booleanResult" | Return value of the Boolean type. | +| Name | Default Value | Description | +| -------------------------------- | ---------------------- | ----------------------- | +| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | +| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | +| KEY_NAME | "name" | App account name. | +| KEY_OWNER | "owner" | Owner of an app account.| +| KEY_TOKEN | "token" | Token. | +| KEY_ACTION | "action" | Operation. | +| KEY_AUTH_TYPE | "authType" | Authentication type. | +| KEY_SESSION_ID | "sessionId" | Session ID. | +| KEY_CALLER_PID | "callerPid" | PID of the caller. | +| KEY_CALLER_UID | "callerUid" | UID of the caller. | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | +| KEY_REQUIRED_LABELS9+ | "requiredLabels" | Required labels. | +| KEY_BOOLEAN_RESULT9+ | "booleanResult" | Return value of the Boolean type. | ## ResultCode8+ @@ -2125,7 +2125,7 @@ Called to redirect a request. ### onRequestContinued9+ -onRequestContinued: () => void +onRequestContinued?: () => void Called to continue to process the request. diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 473c530ac8c4a2af7fc1bd049bdac984d0740429..a518c72880e74ad35cc76e2f0f8c15f92a0b764f 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2148,11 +2148,10 @@ Subscribes to audio capturer change events. **System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** - | Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ------------------------------------------------------------------- ---- | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | | type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| callback | Callback\<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 94182ce2915f60bd6998f512d17288920549d3f8..ae94a539b922fc9aca76dbfe80f3b942171c631c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -18,9 +18,11 @@ The **ApplicationInfo** module provides application information. Unless otherwis | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | +| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead. | +| labelIndex9+ | number | Yes | No | Index of the application label.| | icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | +| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead. | +| iconIndex9+ | number | Yes | No | Index of the application icon.| | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | supportedModes | number | Yes | No | Running modes supported by the application. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 72fcfaca8fb39e4345c2392e761b19b364922499..544a4ba0d27e6c39794e063fc63282ba5455bf5e 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -19,6 +19,10 @@ startTrace(name: string, taskId: number, expectedTime?: number): void Marks the start of a timeslice trace task. +> **NOTE** +> +> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. + **System capability**: SystemCapability.Developtools.Bytrace **Parameters** @@ -29,9 +33,6 @@ Marks the start of a timeslice trace task. | taskId | number | Yes| ID of a timeslice trace task.| | expectedTime | number | No| Expected duration of the trace, in ms.| -> **NOTE** -> -> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. **Example** @@ -47,6 +48,10 @@ finishTrace(name: string, taskId: number): void Marks the end of a timeslice trace task. +> **NOTE** +> +> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. + **System capability**: SystemCapability.Developtools.Bytrace **Parameters** @@ -56,9 +61,6 @@ Marks the end of a timeslice trace task. | name | string | Yes| Name of a timeslice trace task.| | taskId | number | Yes| ID of a timeslice trace task.| -> **NOTE** -> -> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. **Example** @@ -95,7 +97,7 @@ traceByValue(name: string, count: number): void Defines the variable that indicates the number of timeslice trace tasks. -**System capability**: SystemCapability.Developtools.Bytrace +**System capability**: SystemCapability.HiviewDFX.HiTrace **Parameters** | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index bb320e0c8b61e2259aa8c31a6d8efa5866c780fa..381796969cdc260896b9ea4857d0461eebf7d519 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -44,7 +44,7 @@ call.dial("138xxxxxxxx", (err, data) => { dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\): void -Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. +Initiates a call based on the specified options. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.PLACE\_CALL (a system permission) @@ -73,7 +73,7 @@ call.dial("138xxxxxxxx", { dial\(phoneNumber: string, options?: DialOptions\): Promise -Initiates a call. You can set call options as needed. This API uses a promise to return the result. +Initiates a call based on the specified options. This API uses a promise to return the result. **Required permission**: ohos.permission.PLACE\_CALL (a system permission) @@ -304,7 +304,7 @@ call.isEmergencyPhoneNumber("138xxxxxxxx", (err, data) => { isEmergencyPhoneNumber\(phoneNumber: string, options: EmergencyNumberOptions, callback: AsyncCallback\): void -Checks whether the called number is an emergency number based on the phone number. This API uses an asynchronous callback to return the result. +Checks whether the called number is an emergency number based on the specified phone number options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CallManager @@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the phone numbe | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number option. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | **Example** @@ -329,7 +329,7 @@ call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, value) => { isEmergencyPhoneNumber\(phoneNumber: string, options?: EmergencyNumberOptions\): Promise -Checks whether the called number is an emergency number based on the phone number. This API uses a promise to return the result. +Checks whether the called number is an emergency number based on the specified phone number options. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CallManager @@ -338,7 +338,7 @@ Checks whether the called number is an emergency number based on the phone numbe | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number option. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | **Return value** @@ -386,7 +386,7 @@ call.formatPhoneNumber("138xxxxxxxx", (err, data) => { formatPhoneNumber\(phoneNumber: string, options: NumberFormatOptions, callback: AsyncCallback\): void -Formats a phone number based on specified formatting options. This API uses an asynchronous callback to return the result. +Formats a phone number based on the specified formatting options. This API uses an asynchronous callback to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting option, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | | callback | AsyncCallback<string> | Yes | Callback used to return the result. | **Example** @@ -415,7 +415,7 @@ call.formatPhoneNumber("138xxxxxxxx",{ formatPhoneNumber\(phoneNumber: string, options?: NumberFormatOptions\): Promise -Formats a phone number based on specified formatting options. This API uses a promise to return the result. +Formats a phone number based on the specified formatting options. This API uses a promise to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -426,7 +426,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ---------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting option, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | **Return value** @@ -514,15 +514,2242 @@ promise.then(data => { }); ``` +## call.muteRinger8+ + +muteRinger\(callback: AsyncCallback\): void + +Mutes the ringtone while it is playing. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.muteRinger((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.muteRinger8+ + +muteRinger\(\): Promise + +Mutes the ringtone while it is playing. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.muteRinger(); +promise.then(data => { + console.log(`muteRinger success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`muteRinger fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.answer7+ + +answer\(callback: AsyncCallback\): void + +Answers a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.answer((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.answer7+ + +answer\(callId: number, callback: AsyncCallback\): void + +Answers a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.answer(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.answer7+ + +answer(callId?: number\): Promise + +Answers a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.answer(1); +promise.then(data => { + console.log(`answer success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`answer fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.hangup7+ + +hangup\(callback: AsyncCallback\): void + +Ends a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.hangup((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.hangup7+ + +hangup\(callId: number, callback: AsyncCallback\): void + +Ends a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.hangup(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.hangup7+ + +hangup\(callId?: number\): Promise + +Ends a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.hangup(1); +promise.then(data => { + console.log(`hangup success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`hangup fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.reject7+ + +reject\(callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.reject((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject\(options: RejectMessageOptions, callback: AsyncCallback\): void + +Rejects a call based on the specified options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | -------------- | +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject(callId: number, callback: AsyncCallback): + +Rejects a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.reject(1); +promise.then(data => { + console.log(`reject success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`reject fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.reject7+ + +reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void + +Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(1, rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject(callId?: number, options?: RejectMessageOptions\): Promise + +Rejects a call based on the specified call ID and options. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| +| options | [RejectMessageOptions](#rejectmessageoptions7) | No | Options for the call rejection message. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +let promise = call.reject(1, rejectMessageOptions); +promise.then(data => { + console.log(`reject success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`reject fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.holdCall7+ + +holdCall\(callId: number, callback: AsyncCallback\): void + +Holds a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.holdCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.holdCall7+ + +holdCall\(callId: number\): Promise + +Holds a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.holdCall(1); +promise.then(data => { + console.log(`holdCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`holdCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.unHoldCall7+ + +unHoldCall\(callId: number, callback: AsyncCallback\): void + +Unholds a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.unHoldCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.unHoldCall7+ + +unHoldCall\(callId: number\): Promise + +Unholds a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.unHoldCall(1); +promise.then(data => { + console.log(`unHoldCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`unHoldCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.switchCall7+ + +switchCall\(callId: number, callback: AsyncCallback\): void + +Switches a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.switchCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.switchCall7+ + +switchCall\(callId: number\): Promise + +Switches a call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.switchCall(1); +promise.then(data => { + console.log(`switchCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`switchCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.combineConference7+ + +combineConference\(callId: number, callback: AsyncCallback\): void + +Combines two calls into a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.combineConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.combineConference7+ + +combineConference\(callId: number\): Promise + +Combines two calls into a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.combineConference(1); +promise.then(data => { + console.log(`combineConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`combineConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getMainCallId7+ + +getMainCallId\(callId: number, callback: AsyncCallback\): void + +Obtains the main call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getMainCallId(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getMainCallId7+ + +getMainCallId\(callId: number\): Promise + +Obtains the main call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getMainCallId(1); +promise.then(data => { + console.log(`getMainCallId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getMainCallId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getSubCallIdList7+ + +getSubCallIdList\(callId: number, callback: AsyncCallback\>\): void + +Obtains the list of subcall IDs. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ---------------------------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getSubCallIdList(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getSubCallIdList7+ + +getSubCallIdList\(callId: number\): Promise\> + +Obtains the list of subcall IDs. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ----------------------------- | ----------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getSubCallIdList(1); +promise.then(data => { + console.log(`getSubCallIdList success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getSubCallIdList fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallIdListForConference7+ + +getCallIdListForConference\(callId: number, callback: AsyncCallback>\): void + +Obtains the list of call IDs in a conference. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<Array> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getCallIdListForConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallIdListForConference7+ + +getCallIdListForConference\(callId: number\): Promise\> + +Obtains the list of call IDs in a conference. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getCallIdListForConference(1); +promise.then(data => { + console.log(`getCallIdListForConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallIdListForConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallWaitingStatus7+ + +getCallWaitingStatus\(slotId: number, callback: AsyncCallback\): void + +Obtains the call waiting status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.

- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| + +**Example** + +```js +call.getCallWaitingStatus(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallWaitingStatus7+ + +getCallWaitingStatus\(slotId: number\): Promise + +Obtains the call waiting status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[CallWaitingStatus](#callwaitingstatus7)> | Promise used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| + +**Example** + +```js +let promise = call.getCallWaitingStatus(0); +promise.then(data => { + console.log(`getCallWaitingStatus success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallWaitingStatus fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallWaiting7+ + +setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback\): void + +Sets the call waiting switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| activate | boolean | Yes | Whether to enable call waiting.
- **false**: Disable call waiting.
- **true**: Enable call waiting.| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +call.setCallWaiting(0, true, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallWaiting7+ + +setCallWaiting\(slotId: number, activate: boolean\): Promise + +Sets the call waiting switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| activate | boolean | Yes | Whether to enable call waiting.
- **false**: Disable call waiting.
- **true**: Enable call waiting.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.setCallWaiting(0, true); +promise.then(data => { + console.log(`setCallWaiting success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallWaiting fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.startDTMF7+ + +startDTMF\(callId: number, character: string, callback: AsyncCallback\): void + +Enables dual-tone multifrequency (DTMF). This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| character | string | Yes | DTMF code. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +call.startDTMF(1, "0", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.startDTMF7+ + +startDTMF\(callId: number, character: string\): Promise + +Enables DTMF. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| +| character | string | Yes | DTMF code.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.startDTMF(1, "0"); +promise.then(data => { + console.log(`startDTMF success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`startDTMF fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.stopDTMF7+ + +stopDTMF\(callId: number, callback: AsyncCallback\): void + +Stops DTMF. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.stopDTMF(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.stopDTMF7+ + +stopDTMF\(callId: number\): Promise + +Stops DTMF. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.stopDTMF(1); +promise.then(data => { + console.log(`stopDTMF success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`stopDTMF fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isInEmergencyCall7+ + +isInEmergencyCall\(callback: AsyncCallback\): void + +Checks whether a call is an emergency call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isInEmergencyCall((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isInEmergencyCall7+ + +isInEmergencyCall\(\): Promise + +Checks whether a call is an emergency call. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isInEmergencyCall(); +promise.then(data => { + console.log(`isInEmergencyCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isInEmergencyCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.on('callDetailsChange')7+ + +on\(type: 'callDetailsChange', callback: Callback\): void + +Subscribes to **callDetailsChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | -------------------------- | +| type | string | Yes | Call details change during a call.| +| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callDetailsChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('callEventChange')8+ + +on\(type: 'callEventChange', callback: Callback\): void + +Subscribes to **callEventChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | -------------------------- | +| type | string | Yes | Call event change during a call.| +| callback | Callback<[CallEventOptions](#calleventoptions8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callEventChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('callDisconnectedCause')8+ + +on\(type: 'callDisconnectedCause', callback: Callback): void + +Subscribes to **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | -------------------------- | +| type | string | Yes | Cause of the call disconnection.| +| callback | Callback<[DisconnectedDetails](#disconnecteddetails8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callDisconnectedCause', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('mmiCodeResult')9+ + +on\(type: 'mmiCodeResult', callback: Callback\): void + +Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | --------------------- | +| type | string | Yes | Man-machine interface (MMI) code result.| +| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | Yes | Callback used to return the result. | + +**Example** + +```js +isNewCallAllowedcall.on('mmiCodeResult', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callDetailsChange')7+ + +off\(type: 'callDetailsChange', callback?: Callback\): void + +Unsubscribes from **callDetailsChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Unsubscription from call details changes when a call ends.| +| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callDetailsChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callEventChange')8+ + +off\(type: 'callEventChange', callback?: Callback\): void + +Unsubscribes from **callEventChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ---------------------------------- | +| type | string | Yes | Unsubscription from call event changes when a call ends.| +| callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callEventChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callDisconnectedCause')8+ + +off\(type: 'callDisconnectedCause', callback?: Callback\): void + +Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | -------------------- | +| type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.| +| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails8)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callDisconnectedCause', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('mmiCodeResult')9+ + +off\(type: 'mmiCodeResult', callback?: Callback\): void + +Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ----------- | +| type | 'mmiCodeResult' | Yes | MMI code result.| +| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('mmiCodeResult', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.isNewCallAllowed8+ + +isNewCallAllowed\(callback: AsyncCallback\): void + +Checks whether a new call is allowed. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isNewCallAllowed((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isNewCallAllowed8+ + +isNewCallAllowed\(\): Promise + +Checks whether a new call is allowed. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isNewCallAllowed(); +promise.then(data => { + console.log(`isNewCallAllowed success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isNewCallAllowed fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.separateConference8+ + +separateConference\(callId: number, callback: AsyncCallback\): void + +Separates a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.separateConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.separateConference8+ + +separateConference\(callId: number\): Promise + +Separates a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.separateConference(1); +promise.then(data => { + console.log(`separateConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`separateConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallRestrictionStatus8+ + +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: AsyncCallback\): void + +Obtains the call restriction status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type. | +| callback | AsyncCallback<[RestrictionStatus](#restrictionstatus8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getCallRestrictionStatus(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallRestrictionStatus8+ + +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise + +Obtains the call restriction status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | --------------------------- | +| Promise<[RestrictionStatus](#restrictionstatus8)> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getCallRestrictionStatus(0, 1); +promise.then(data => { + console.log(`getCallRestrictionStatus success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallRestrictionStatus fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallRestriction8+ + +setCallRestriction\(slotId: number, info: CallRestrictionInfo, callback: AsyncCallback\): void + +Sets the call restriction status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallRestrictionInfo](#callrestrictioninfo8) | Yes | Call restriction information. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let callRestrictionInfo={ + type: 1, + password: "123456", + mode: 1 +} +call.setCallRestriction(0, callRestrictionInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallRestriction8+ + +setCallRestriction\(slotId: number, info: CallRestrictionInfo\): Promise + +Sets the call restriction status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallRestrictionInfo](#callrestrictioninfo8) | Yes | Call restriction information. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let callRestrictionInfo={ + type: 1, + password: "123456", + mode: 1 +} +let promise = call.setCallRestriction(0, callRestrictionInfo); +promise.then(data => { + console.log(`setCallRestriction success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallRestriction fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallTransferInfo8+ + +getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCallback\): void + +Obtains call transfer information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| callback | AsyncCallback<[CallTransferResult](#calltransferresult8)> | Yes | Callback used to return the result. | + +**Example** + +```js +let callTransferTyp={ + CallTransferType: 1 +} +call.getCallTransferInfo(0, callTransferTyp, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallTransferInfo8+ + +getCallTransferInfo\(slotId: number, type: CallTransferType): Promise + +Obtains call transfer information. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | --------------------------- | +| Promise<[CallTransferResult](#calltransferresult8)> | Promise used to return the result.| + +**Example** + +```js +let callTransferTyp={ + CallTransferType: 1 +} +let promise = call.getCallTransferInfo(0, callTransferTyp); +promise.then(data => { + console.log(`getCallTransferInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallTransferInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallTransfer8+ + +setCallTransfer\(slotId: number, info: CallTransferInfo, callback: AsyncCallback\): void + +Sets call transfer information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallTransferInfo](#calltransferinfo8) | Yes | Call transfer information. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let callTransferInfo={ + transferNum: "111", + type: 1, + settingType: 1 +} +call.setCallTransfer(0, callTransferInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallTransfer8+ + +setCallTransfer\(slotId: number, info: CallTransferInfo): Promise + +Sets call transfer information. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallTransferInfo](#calltransferinfo8) | Yes | Call transfer information. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let callTransferInfo={ + transferNum: "111", + type: 1, + settingType: 1 +} +let promise = call.setCallTransfer(0, callTransferInfo); +promise.then(data => { + console.log(`setCallTransfer success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallTransfer fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isRinging8+ + +isRinging\(callback: AsyncCallback\): void + +Checks whether the ringtone is playing. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isRinging((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isRinging8+ + +isRinging\(\): Promise + +Checks whether the ringtone is playing. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isRinging(); +promise.then(data => { + console.log(`isRinging success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isRinging fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setMuted8+ + +setMuted\(callback: AsyncCallback\): void + +Sets call muting. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.setMuted((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setMuted8+ + +setMuted\(\): Promise + +Sets call muting. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.setMuted(); +promise.then(data => { + console.log(`setMuted success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setMuted fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.cancelMuted8+ + +cancelMuted(callback: AsyncCallback): void + +Cancels call muting. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.cancelMuted((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.cancelMuted8+ + +cancelMuted(): Promise + +Cancels call muting. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.cancelMuted(); +promise.then(data => { + console.log(`cancelMuted success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`cancelMuted fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setAudioDevice8+ + +setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void + +Sets the audio device for a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.setAudioDevice(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setAudioDevice8+ + +setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\): void + +Sets the audio device for a call based on the specified options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | -------------- | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device. | +| options | [AudioDeviceOptions](#audiodeviceoptions9) | Yes | Audio device parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let audioDeviceOptions={ + bluetoothAddress: "IEEE 802-2014" +} +call.setAudioDevice(1, bluetoothAddress, (err, value) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setAudioDevice8+ + +setAudioDevice(device: AudioDevice, options?: AudioDeviceOptions): Promise + +Sets the audio device for a call based on the specified options. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | ------------------ | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device. | +| options | [AudioDeviceOptions](#audiodeviceoptions9) | No | Audio device parameters.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let audioDeviceOptions={ + bluetoothAddress: "IEEE 802-2014" +} +let promise = call.setAudioDevice(1, audioDeviceOptions); +promise.then(data => { + console.log(`setAudioDevice success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setAudioDevice fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.joinConference8+ + +joinConference(mainCallId: number, callNumberList: Array, callback: AsyncCallback): void + +Joins a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------- | ---- | --------------- | +| mainCallId | number | Yes | Main call ID. | +| callNumberList | Array | Yes | List of call numbers.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.joinConference(1, "138XXXXXXXX", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.joinConference8+ + +joinConference(mainCallId: number, callNumberList: Array): Promise + +Joins a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | -------------- | ---- | --------------- | +| mainCallId | number | Yes | Main call ID. | +| callNumberList | Array | Yes | List of call numbers.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.joinConference(1, "138XXXXXXXX"); +promise.then(data => { + console.log(`joinConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`joinConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.updateImsCallMode8+ + +updateImsCallMode(callId: number, mode: ImsCallMode, callback: AsyncCallback): void + +Updates the IMS call mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------- | +| callId | number | Yes | Call ID. | +| mode | [ImsCallMode](#imscallmode8) | Yes | IMS call mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.updateImsCallMode(1, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.updateImsCallMode8+ + +updateImsCallMode(callId: number, mode: ImsCallMode): Promise + +Updates the IMS call mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | -------------- | +| callId | number | Yes | Call ID. | +| mode | [ImsCallMode](#imscallmode8) | Yes | IMS call mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.updateImsCallMode(1, 1); +promise.then(data => { + console.log(`updateImsCallMode success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`updateImsCallMode fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.enableImsSwitch8+ + +enableImsSwitch(slotId: number, callback: AsyncCallback): void + +Enables the IMS switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.enableImsSwitch(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.enableImsSwitch8+ + +enableImsSwitch(slotId: number): Promise + +Enables the IMS switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.enableImsSwitch(0); +promise.then(data => { + console.log(`enableImsSwitch success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`enableImsSwitch fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.disableImsSwitch8+ + +disableImsSwitch(slotId: number, callback: AsyncCallback): void + +Disables the IMS switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.disableImsSwitch(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.disableImsSwitch8+ + +disableImsSwitch(slotId: number): Promise + +Disables the IMS switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.disableImsSwitch(0); +promise.then(data => { + console.log(`disableImsSwitch success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`disableImsSwitch fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isImsSwitchEnabled8+ + +isImsSwitchEnabled(slotId: number, callback: AsyncCallback): void + +Checks whether the IMS switch is enabled. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | + +**Example** + +```js +call.isImsSwitchEnabled(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.isImsSwitchEnabled8+ + +isImsSwitchEnabled(slotId: number): Promise + +Checks whether the IMS switch is enabled. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isImsSwitchEnabled(0); +promise.then(data => { + console.log(`isImsSwitchEnabled success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isImsSwitchEnabled fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## DialOptions -Provides an option for determining whether a call is a video call. +Defines the dialup options. **System capability**: SystemCapability.Telephony.CallManager -| Name| Type | Mandatory | Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| +| accountId | number | No | Account ID. This API is supported since API version 8. It is a system API. | +| videoState | [VideoStateType](#videostatetype7) | No | Video state type. This API is supported since API version 8. It is a system API. | +| dialScene | [DialScene](#dialscene8) | No | Dialup scenario. This API is supported since API version 8. It is a system API. | +| dialType | [DialType](#dialtype8) | No | Dialup type. This API is supported since API version 8. It is a system API. | ## CallState @@ -539,7 +2766,7 @@ Enumerates call states. ## EmergencyNumberOptions7+ -Provides an option for determining whether a number is an emergency number for the SIM card in the specified slot. +Defines options for determining whether a number is an emergency number. **System capability**: SystemCapability.Telephony.CallManager @@ -549,10 +2776,401 @@ Provides an option for determining whether a number is an emergency number for t ## NumberFormatOptions7+ -Provides an option for number formatting. +Defines the number formatting options. **System capability**: SystemCapability.Telephony.CallManager | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------------------------------------------------- | | countryCode | string | No | Country code, for example, **CN** (China). All country codes are supported. The default value is **CN**. | + +## ImsCallMode8+ + +Enumerates IMS call modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------------- | ---- | ------------------ | +| CALL_MODE_AUDIO_ONLY | 0 | Audio call only. | +| CALL_MODE_SEND_ONLY | 1 | Sending calls only. | +| CALL_MODE_RECEIVE_ONLY | 2 | Receiving calls only. | +| CALL_MODE_SEND_RECEIVE | 3 | Sending and receiving calls.| +| CALL_MODE_VIDEO_PAUSED | 4 | Pausing video calls. | + +## AudioDevice8+ + +Enumerates audio devices. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| DEVICE_EARPIECE | 0 | Headset device. | +| DEVICE_SPEAKER | 1 | Speaker device.| +| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| +| DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | + +## CallRestrictionType8+ + +Enumerates call restriction types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------------------------- | ---- | -------------------------- | +| RESTRICTION_TYPE_ALL_INCOMING | 0 | Barring of all incoming calls. | +| RESTRICTION_TYPE_ALL_OUTGOING | 1 | Barring of all outgoing calls. | +| RESTRICTION_TYPE_INTERNATIONAL | 2 | Barring of international calls. | +| RESTRICTION_TYPE_INTERNATIONAL_EXCLUDING_HOME | 3 | Barring of international calls except those in the home country.| +| RESTRICTION_TYPE_ROAMING_INCOMING | 4 | Barring of incoming roaming calls. | +| RESTRICTION_TYPE_ALL_CALLS | 5 | Barring of all calls. | +| RESTRICTION_TYPE_OUTGOING_SERVICES | 6 | Barring of outgoing services. | +| RESTRICTION_TYPE_INCOMING_SERVICES | 7 | Barring of incoming services. | + +## CallTransferInfo8+ + +Defines the call transfer information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------- | ---- | ---------------- | +| transferNum | string | Yes | Call transfer number. | +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| + +## CallTransferType8+ + +Enumerates call transfer types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------- | ---- | ------------ | +| TRANSFER_TYPE_UNCONDITIONAL | 0 | Call forwarding unconditional. | +| TRANSFER_TYPE_BUSY | 1 | Call forwarding busy. | +| TRANSFER_TYPE_NO_REPLY | 2 | Call forwarding on no reply. | +| TRANSFER_TYPE_NOT_REACHABLE | 3 | Call forwarding on no user not reachable.| + +## CallTransferSettingType8+ + +Enumerates call transfer setting types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------------- | ---- | ------------ | +| CALL_TRANSFER_DISABLE | 0 | Disabling of call transfer.| +| CALL_TRANSFER_ENABLE | 1 | Enabling of call transfer.| +| CALL_TRANSFER_REGISTRATION | 3 | Registration of call transfer.| +| CALL_TRANSFER_ERASURE | 4 | Erasing of call transfer.| + +## CallAttributeOptions7+ + +Defines the call attribute options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------- | ---- | -------------- | +| accountNumber | string | Yes | Account number. | +| speakerphoneOn | boolean | Yes | Speakerphone on.| +| accountId | number | Yes | Account ID. | +| videoState | [VideoStateType](#videostatetype7) | Yes | Video state type. | +| startTime | number | Yes | Start time. | +| isEcc | boolean | Yes | Whether the call is an ECC. | +| callType | [CallType](#calltype7) | Yes | Call type. | +| callId | number | Yes | Call ID. | +| callState | [DetailedCallState](#detailedcallstate7) | Yes | Detailed call state. | +| conferenceState | [ConferenceState](#conferencestate7) | Yes | Conference state. | + +## ConferenceState7+ + +Enumerates conference states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------------------- | ---- | -------------- | +| TEL_CONFERENCE_IDLE | 0 | Idle state. | +| TEL_CONFERENCE_ACTIVE | 1 | Active state. | +| TEL_CONFERENCE_DISCONNECTING | 2 | Disconnecting state. | +| TEL_CONFERENCE_DISCONNECTED | 3 | Disconnected state.| + +## CallType7+ + +Enumerates call types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------- | ---- | ------------ | +| TYPE_CS | 0 | CS call. | +| TYPE_IMS | 1 | IMS call. | +| TYPE_OTT | 2 | OTT call. | +| TYPE_ERR_CALL | 3 | Error call type.| + +## VideoStateType7+ + +Enumerates video state types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------- | ---- | -------- | +| TYPE_VOICE | 0 | Voice state.| +| TYPE_VIDEO | 1 | Video state.| + +## DetailedCallState7+ + +Enumerates detailed call states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------------- | ---- | -------------- | +| CALL_STATUS_ACTIVE | 0 | Active state. | +| CALL_STATUS_HOLDING | 1 | Hold state. | +| CALL_STATUS_DIALING | 2 | Dialing state. | +| CALL_STATUS_ALERTING | 3 | Alerting state. | +| CALL_STATUS_INCOMING | 4 | Incoming state. | +| CALL_STATUS_WAITING | 5 | Waiting state. | +| CALL_STATUS_DISCONNECTED | 6 | Disconnected state.| +| CALL_STATUS_DISCONNECTING | 7 | Disconnecting state. | +| CALL_STATUS_IDLE | 8 | Idle state. | + +## CallRestrictionInfo8+ + +Defines the call restriction information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------ | +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type.| +| password | string | Yes | Password. | +| mode | [CallRestrictionMode](#callrestrictionmode8) | Yes | Call restriction mode.| + +## CallRestrictionMode8+ + +Enumerates call restriction modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ----------------------------- | ---- | ------------ | +| RESTRICTION_MODE_DEACTIVATION | 0 | Call restriction deactivated.| +| RESTRICTION_MODE_ACTIVATION | 1 | Call restriction activated.| + +## CallEventOptions8+ + +Defines the call event options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | -------------- | +| eventId | [CallAbilityEventId](#callabilityeventid8) | Yes | Call ability event ID.| + +## CallAbilityEventId8+ + +Enumerates call ability event IDs. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------------ | ---- | --------------- | +| EVENT_DIAL_NO_CARRIER | 1 | No available carrier during dialing. | +| EVENT_INVALID_FDN_NUMBER | 2 | Invalid FDN.| + +## DialScene8+ + +Enumerates dialup scenarios. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------- | ---- | ------------ | +| CALL_NORMAL | 0 | Common call. | +| CALL_PRIVILEGED | 1 | Privileged call. | +| CALL_EMERGENCY | 2 | Emergency call.| + +## DialType8+ + +Enumerates dialup types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ---------------- | +| DIAL_CARRIER_TYPE | 0 | Carrier. | +| DIAL_VOICE_MAIL_TYPE | 1 | Voice mail.| +| DIAL_OTT_TYPE | 2 | OTT. | + +## RejectMessageOptions7+ + +Defines options for the call rejection message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | -------- | +| messageContent | string | Yes | Message content.| + +## CallTransferResult8+ + +Defines the call transfer result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------- | ---- | -------- | +| status | [TransferStatus](#transferstatus8) | Yes | Transfer status.| +| number | string | Yes | Number. | + +## CallWaitingStatus7+ + +Enumerates call waiting states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| CALL_WAITING_DISABLE | 0 | Call waiting disabled.| +| CALL_WAITING_ENABLE | 1 | Call waiting enabled.| + +## RestrictionStatus8+ + +Enumerates call restriction states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------- | ---- | -------- | +| RESTRICTION_DISABLE | 0 | Call restriction disabled.| +| RESTRICTION_ENABLE | 1 | Call restriction enabled.| + +## TransferStatus8+ + +Enumerates call transfer states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------- | ---- | -------- | +| TRANSFER_DISABLE | 0 | Call transfer disabled.| +| TRANSFER_ENABLE | 1 | Call transfer enabled.| + +## DisconnectedDetails8+ + +Enumerates causes of call disconnection. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------- | ---- | ---------------------- | +| UNASSIGNED_NUMBER | 1 | Unallocated number. | +| NO_ROUTE_TO_DESTINATION | 3 | No route to the destination. | +| CHANNEL_UNACCEPTABLE | 6 | Unacceptable channel. | +| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | +| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | +| USER_BUSY | 17 | User busy. | +| NO_USER_RESPONDING | 18 | No user response. | +| USER_ALERTING_NO_ANSWER | 19 | Alerting but no answer.| +| CALL_REJECTED | 21 | Call rejected. | +| NUMBER_CHANGED | 22 | Number changed. | +| DESTINATION_OUT_OF_ORDER | 27 | Destination fault. | +| INVALID_NUMBER_FORMAT | 28 | Invalid number format. | +| NETWORK_OUT_OF_ORDER | 38 | Network fault. | +| TEMPORARY_FAILURE | 41 | Temporary fault. | +| INVALID_PARAMETER | 1025 | Invalid parameter. | +| SIM_NOT_EXIT | 1026 | SIM card not exit. | +| SIM_PIN_NEED | 1027 | SIM card PIN required. | +| CALL_NOT_ALLOW | 1029 | Call not allowed. | +| SIM_INVALID | 1045 | Invalid SIM card. | +| UNKNOWN | 1279 | Unknown reason. | + +## MmiCodeResults9+ + +Defines the MMI code result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | --------------- | +| result | [MmiCodeResult](#mmicoderesult9) | Yes | MMI code result.| +| message | string | Yes | MMI code message.| + +## MmiCodeResult9+ + +Enumerates MMI code results. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------- | ---- | ------------- | +| MMI_CODE_SUCCESS | 0 | Success.| +| MMI_CODE_FAILED | 1 | Failure.| + +## AudioDeviceOptions9+ + +Defines audio device options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ---------------- | ------ | ---- | -------- | +| bluetoothAddress | string | No | Bluetooth address.| diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index 8819011c106586b3099116d0c43b7644e09da8a2..fac4104f5cb135b5c5afa45127cdbd488a9a6225 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -71,86 +71,80 @@ Enumerates the camera statuses. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | ------------ | -| CAMERA_STATUS_APPEAR | 0 | The camera exists. | -| CAMERA_STATUS_DISAPPEAR | 1 | The camera does not exist.| -| CAMERA_STATUS_AVAILABLE | 2 | The camera is ready. | -| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is not ready.| +| Name | Value | Description | +| ------------------------- | ---- | -------------- | +| CAMERA_STATUS_APPEAR | 0 | A camera appears.| +| CAMERA_STATUS_DISAPPEAR | 1 | The camera disappears. | +| CAMERA_STATUS_AVAILABLE | 2 | The camera is available. | +| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable. | +## Profile -## CameraPosition - -Enumerates the camera positions. +Defines the camera configuration. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------------- | ---- | ---------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| -| CAMERA_POSITION_BACK | 1 | Rear camera. | -| CAMERA_POSITION_FRONT | 2 | Front camera. | +| Name | Type | Read only| Description | +| ------ | ----------------------------- | ---- | ---------- | +| format | [CameraFormat](#cameraformat) | Yes | Output format.| +| size | [Size](#size) | Yes | Resolution. | -## CameraType +## FrameRateRange -Enumerates the camera types. + Defines the frame rate range. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ----------------------- | ---- | ---------------- | -| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type.| -| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | -| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | -| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | -| CAMERA_TYPE_TRUE_DEPTH | 4 | True depth camera. | +| Name| Type | Read only| Description | +| ---- | ------ | ---- | ----------------- | +| min | number | Yes | Minimum rate, in fps.| +| max | number | Yes | Maximum rate, in fps.| +## VideoProfile -## ConnectionType - -Enumerates the camera connection types. +Defines the video configuration. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------------- | ---- | ------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| -| CAMERA_CONNECTION_REMOTE | 2 | Remote camera. | +| Name | Type | Read only| Description | +| --------------- | --------------------------------- | ---- | ------ | +| frameRateRanges | [FrameRateRange](#frameraterange) | Yes | Frame rate range.| -## Size +## CameraOutputCapability -Defines the image size that can be used in previewing, photographing, and video recording. +Defines the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | ------------ | -| height | string | Yes | Yes | Image height.| -| width | number | Yes | Yes | Image width.| +| Name | Type | Read only| Description | +| ---------------------------- | ------------------------------------------------- | ---- | -------------------------- | +| previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview configurations. | +| photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting configurations. | +| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording configurations. | +| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| ## CameraManager Implements camera management. Before calling any API in **CameraManager**, you must use **getCameraManager** to obtain a **CameraManager** instance. -### getCameras +### getSupportedCameras -getCameras(callback: AsyncCallback\>): void +getSupportedCameras(callback: AsyncCallback\>): void -Obtains all cameras supported by the device. This API uses an asynchronous callback to return the array of supported cameras. +Obtains supported cameras. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| **Example** ```js -cameraManager.getCameras((err, cameras) => { +cameraManager.getSupportedCameras((err, cameras) => { if (err) { console.error('Failed to get the cameras. ${err.message}'); return; @@ -159,1015 +153,986 @@ cameraManager.getCameras((err, cameras) => { }) ``` -### getCameras +### getSupportedCameras -getCameras(): Promise\> +getSupportedCameras(): Promise\> -Obtains all cameras supported by the device. This API uses a promise to return the array of supported cameras. +Obtains supported cameras. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | -| Promise\> | Promise used to return the array of supported cameras.| +| Type | Description | +| ----------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the array of supported cameras.| **Example** ```js -cameraManager.getCameras().then((cameraArray) => { +cameraManager.getSupportedCameras().then((cameraArray) => { console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); }) ``` -### createCameraInput - -createCameraInput(cameraId: string, callback: AsyncCallback): void +### getSupportedOutputCapability -Creates a **CameraInput** instance with the specified camera ID. This API uses an asynchronous callback to return the instance. +getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void -**Required permissions**: ohos.permission.CAMERA +Obtains the output capability supported by a camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| cameraId | string | Yes | Camera ID used to create the instance. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------------------- | +| camera | [CameraDevice](#cameraDevice) | Yes | **CameraDevice** object. | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes | Callback used to return the output capability.| **Example** ```js -cameraManager.createCameraInput(cameraId, (err, cameraInput) => { +cameraManager.getSupportedOutputCapability(cameraDevice, (err, cameras) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error('Failed to get the cameras. ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance.'); + console.log('Callback returned with an array of supported outputCapability'); }) ``` -### createCameraInput - -createCameraInput(cameraId: string): Promise +### getSupportedOutputCapability -Creates a **CameraInput** instance with the specified camera ID. This API uses a promise to return the instance. +getSupportedOutputCapability(camera:CameraDevice): Promise -**Required permissions**: ohos.permission.CAMERA +Obtains the output capability supported by a camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | -| cameraId | string | Yes | Camera ID used to create the instance.| +| Name | Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ------------------ | +| camera | [CameraDevice](#cameraDevice) | Yes | **CameraDevice** object.| **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| ----------------------------------------------------------- | --------------------------------------------- | +| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.| + **Example** ```js -cameraManager.createCameraInput(cameraId).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => { + console.log('Promise returned with an array of supported outputCapability'); }) ``` -### createCameraInput - -createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void +### getSupportedMetadataObjectType -Creates a **CameraInput** instance with the specified camera position and camera type. This API uses an asynchronous callback to return the instance. +getSupportedMetadataObjectType(callback: AsyncCallback\>): void -**Required permissions**: ohos.permission.CAMERA +Obtains the metadata information supported by this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position. | -| type | [CameraType](#cameratype) | Yes | Camera type. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the metadata information.| **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { +cameraManager.getSupportedMetadataObjectType((err, metadataobject) => { if (err) { - console.error('Failed to create the CameraInput instance. ${err.message}'); + console.error('Failed to get the supported metadataObjectType. ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance'); + console.log('Callback returned with an array of supported metadataObjectType.' ); }) ``` -### createCameraInput - -createCameraInput(position: CameraPosition, type: CameraType): Promise +### getSupportedMetadataObjectType -Creates a **CameraInput** instance with the specified camera position and camera type. This API uses a promise to return the instance. +getSupportedMetadataObjectType(camera:CameraDevice): Promise -**Required permissions**: ohos.permission.CAMERA +Obtains the metadata information supported by this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ---------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position.| -| type | [CameraType](#cameratype) | Yes | Camera type.| - **Return value** -| Type | Description | -| ------------------------------------- | ---------------------------------------- | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| ------------------------------------------------------- | ----------------------------------------------------- | +| Promise\> | Promise used to return the metadata information.| + **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance.'); +cameraManager.getSupportedMetadataObjectType().then((metadataobject) => { + console.log('Promise returned with an array of supported metadataObjectType.' ); }) ``` -### on('cameraStatus') +### isCameraMuted -on(type: 'cameraStatus', callback: AsyncCallback): void +isCameraMuted(callback: AsyncCallback): void -Listens for camera status changes. This API uses an asynchronous callback to return the camera status changes. +Checks whether this camera is muted. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **cameraStatus**, indicating the camera status change event.| -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| **Example** ```js -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { +cameraManager.isCameraMuted((err, status) => { if (err) { - console.error('Failed to get cameraStatus callback. ${err.message}'); + console.error('Failed to get the cameraMuted status. ${err.message}'); return; } - console.log('camera : ' + cameraStatusInfo.camera.cameraId); - console.log('status: ' + cameraStatusInfo.status); + console.log('Callback returned with cameraMuted status'); }) ``` -## Camera +### isCameraMuted -After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera instance is returned, with camera-related metadata such as **cameraId**, **cameraPosition**, **cameraType**, and **connectionType**. +isCameraMuted(): Promise + +Checks whether this camera is muted. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| -------------- | --------------------------------- | ---- | -------------- | -| cameraId | string | Yes | Camera ID. | -| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | -| cameraType | [CameraType](#cameratype) | Yes | Camera type. | -| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------------------- | +| Promise | Promise used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| + **Example** ```js -async function getCameraInfo("cameraId") { - var cameraManager = await camera.getCameraManager(context); - var cameras = await cameraManager.getCameras(); - var cameraObj = cameras[0]; - var cameraId = cameraObj.cameraId; - var cameraPosition = cameraObj.cameraPosition; - var cameraType = cameraObj.cameraType; - var connectionType = cameraObj.connectionType; -} +cameraManager.isCameraMuted().then((status) => { + console.log('Promise returned with the status whether camera is muted.'); +}) ``` -## CameraStatusInfo - -Describes the camera status information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Description | -| ------ | ----------------------------- | ---------- | -| camera | [Camera](#camera) | Camera object.| -| status | [CameraStatus](#camerastatus) | Camera status.| - - -## CameraInput +### isCameraMuteSupported -Implements a **CameraInput** instance. Before calling any API in **CameraInput**, you must create a **CameraInput** instance. +isCameraMuteSupported(callback: AsyncCallback): void -### getCameraId +Checks whether this camera can be muted. This API uses an asynchronous callback to return the result. -getCameraId(callback: AsyncCallback\): void +This is a system API. -Obtains the camera ID based on which this **CameraInput** instance is created. This API uses an asynchronous callback to return the camera ID. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the camera ID.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| **Example** ```js -cameraInput.getCameraId((err, cameraId) => { +cameraManager.isCameraMuteSupported((err, status) => { if (err) { - console.error('Failed to get the camera ID. ${err.message}'); + console.error('Failed to get the cameraMuteSupported. ${err.message}'); return; } - console.log('Callback returned with the camera ID: ' + cameraId); + console.log('Callback returned with the status whether cameraMuteSupported.'); }) ``` -### getCameraId +### isCameraMuteSupported + +isCameraMuteSupported(): Promise + +Checks whether this camera can be muted. This API uses a promise to return the result. -getCameraId(): Promise +This is a system API. -Obtains the camera ID based on which this **CameraInput** instance is created. This API uses a promise to return the camera ID. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------- | ----------------------------- | -| Promise | Promise used to return the camera ID.| +| Type | Description | +| ----------------- | ------------------------------------------------------- | +| Promise | Promise used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| + **Example** ```js -cameraInput.getCameraId().then((cameraId) => { - console.log('Promise returned with the camera ID:' + cameraId); +cameraManager.isCameraMuteSupported().then((status) => { + console.log('Promise returned with the status whether cameraMuteSupported.'); }) ``` +### muteCamera -### hasFlash +muteCamera(mute:boolean, callback: AsyncCallback): void -hasFlash(callback: AsyncCallback): void +Mutes this camera. This API uses an asynchronous callback to return the result. -Checks whether the device has flash light. This API uses an asynchronous callback to return the result. +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the flash light support status. The value **true** means that the device has flash light.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------ | +| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.hasFlash((err, status) => { +cameraManager.muteCamera(isMuted, (err) => { if (err) { - console.error('Failed to check whether the device has flash light. ${err.message}'); + console.error('Failed to mute the camera. ${err.message}'); return; } - console.log('Callback returned with flash light support status: ' + status); + console.log('Callback returned with the muteCamera.'); }) ``` -### hasFlash +### muteCamera -hasFlash(): Promise +muteCamera(mute:boolean): Promise -Checks whether the device has flash light. This API uses a promise to return the result. +Mutes this camera. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------- | ---- | -------------- | +| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite.| + **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------- | -| Promise | Promise used to return the flash light support status. The value **true** means that the device has flash light.| +| Type | Description | +| -------------- | --------------------------------------------------- | +| Promise| Promise used to return the result.| + **Example** -```js -cameraInput.hasFlash().then((status) => { - console.log('Promise returned with the flash light support status:' + status); +```js +cameraManager.muteCamera(isMuted).then(() => { + console.log('Promise returned muteCamera.'); }) ``` -### isFlashModeSupported +### createCameraInput -isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void +createCameraInput(camera: CameraDevice, callback: AsyncCallback): void -Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. +Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------------------------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | -| callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the specified flash mode is supported.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| camera | [CameraDevice](#cameraDevice) | Yes | **CameraDevice** object. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| **Example** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +cameraManager.createCameraInput(camera, (err, cameraInput) => { if (err) { - console.error('Failed to check whether the flash mode is supported. ${err.message}'); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with the flash mode support status: ' + status); + console.log('Callback returned with the CameraInput instance.'); }) ``` -### isFlashModeSupported +### createCameraInput -isFlashModeSupported(flashMode: FlashMode): Promise +createCameraInput(camera: CameraDevice): Promise -Checks whether a specified flash mode is supported. This API uses a promise to return the result. +Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| +| Name | Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ------------------ | +| camera | [CameraDevice](#cameraDevice) | Yes | **CameraDevice** object.| **Return value** -| Type | Description | -| ----------------- | ------------------------------------------------------------ | -| Promise | Promise used to return the flash mode support status. The value **true** means that the specified flash mode is supported.| +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { - console.log('Promise returned with flash mode support status.' + status); +cameraManager.createCameraInput(camera).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### setFlashMode +### createCameraInput -setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void +createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void -Sets the flash mode. This API uses an asynchronous callback to return the result. +Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result. -Before setting the parameters, do the following checks: +This is a system API. -1. Use [hasFlash](#hasflash) to check whether the device has flash light. -2. Use [isFlashModeSupported](#isflashmodesupported) to check whether the device supports a specified flash mode. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------------------ | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| position | [CameraPosition](#cameraposition) | Yes | Camera position. | +| type | [CameraType](#cameratype) | Yes | Camera type. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| **Example** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { - console.error('Failed to set the flash mode ${err.message}'); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setFlashMode.'); + console.log('Callback returned with the CameraInput instance'); }) ``` -### setFlashMode +### createCameraInput -setFlashMode(flashMode: FlashMode): Promise +createCameraInput(position: CameraPosition, type:CameraType ): Promise -Sets the flash mode. This API uses a promise to return the result. +Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result. -Before setting the parameters, do the following checks: +This is a system API. -1. Use [hasFlash](#hasflash) to check whether the device has flash light. -2. Use [isFlashModeSupported](#isflashmodesupported) to check whether the device supports a specified flash mode. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------- | +| position | [CameraPosition](#cameraposition) | Yes | Camera position.| +| type | [CameraType](#cameratype) | Yes | Camera type.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFlashMode.'); +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### getFlashMode +### createPreviewOutput -getFlashMode(callback: AsyncCallback): void +createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -Obtains the current flash mode. This API uses an asynchronous callback to return the result. +Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the current flash mode.| +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | +| profile | [Profile](#profile) | Yes | Supported preview configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance. | **Example** ```js -cameraInput.getFlashMode((err, flashMode) => { +cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { if (err) { - console.error('Failed to get the flash mode ${err.message}'); + console.error('Failed to gcreate previewOutput. ${err.message}'); return; } - console.log('Callback returned with current flash mode: ' + flashMode); + console.log('Callback returned with previewOutput created.'); }) ``` -### getFlashMode +### createPreviewOutput -getFlashMode(): Promise +createPreviewOutput(profile: Profile, surfaceId: string): Promise -Obtains the current flash mode. This API uses a promise to return the result. +Creates a **PreviewOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------- | ---- | ------------------------------------------------------------ | +| profile | [Profile](#profile) | Yes | Supported preview configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| + **Return value** -| Type | Description | -| --------------------------------- | --------------------------------------- | -| Promise<[FlashMode](#flashmode)\> | Promise used to return the current flash mode.| +| Type | Description | +| ----------------------------------------- | ------------------------------------------ | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| **Example** ```js -cameraInput.getFlashMode().then((flashMode) => { - console.log('Promise returned with current flash mode : ' + flashMode); +cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { + console.log('Promise returned with previewOutput created.'); }) ``` -### isFocusModeSupported +### createDeferredPreviewOutput -isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void +createDeferredPreviewOutput(profile: Profile, callback: AsyncCallback): void -Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. +Creates a **PreviewOutput** instance without a surface ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | -| callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the specified focus mode is supported.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ------------------------------------- | +| profile | [Profile](#profile) | Yes | Supported preview configurations. | +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| **Example** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { +cameraManager.createDeferredPreviewOutput(profile, (err, previewoutput) => { if (err) { - console.error('Failed to check whether the focus mode is supported. ${err.message}'); + console.error('Failed to create deferredPreviewOutput. ${err.message}'); return; } - console.log('Callback returned with the focus mode support status: ' + status); + console.log('Callback returned with deferredPreviewOutput created.'); }) ``` -### isFocusModeSupported +### createDeferredPreviewOutput -isFocusModeSupported(afMode: FocusMode): Promise +createDeferredPreviewOutput(profile: Profile): Promise -Checks whether a specified focus mode is supported. This API uses a promise to return the result. +Creates a **PreviewOutput** instance without a surface ID. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------- | +| profile | [Profile](#profile) | Yes | Supported preview configurations.| **Return value** -| Type | Description | -| ----------------- | ----------------------------------------------------------- | -| Promise | Promise used to return the focus mode support status. The value **true** means that the specified focus mode is supported.| +| Type | Description | +| ----------------------------------------- | ------------------------------------------ | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| **Example** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { - console.log('Promise returned with focus mode support status.' + status); +cameraManager.createDeferredPreviewOutput(profile).then((previewoutput) => { + console.log('Promise returned with DefeerredPreviewOutput created.'); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode, callback: AsyncCallback): void +### createPhotoOutput -Sets the focus mode. This API uses an asynchronous callback to return the result. +createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void -Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. +Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------------ | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| profile | [Profile](#profile) | Yes | Supported shooting configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. | **Example** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { +cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { if (err) { - console.error('Failed to set the focus mode ${err.message}'); + console.error('Failed to create photoOutput. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setFocusMode.'); + console.log('Callback returned with photoOutput created.'); }) ``` -### setFocusMode - -setFocusMode(afMode: FocusMode): Promise +### createPhotoOutput -Sets the focus mode. This API uses a promise to return the result. +createPhotoOutput(profile: Profile, surfaceId: string): Promise -Before setting the focus mode, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. +Creates a **PhotoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ---------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| +| Name | Type | Mandatory| Description | +| --------- | ------------------- | ---- | ------------------------------------------------------------ | +| profile | [Profile](#profile) | Yes | Supported shooting configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance.| **Example** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFocusMode.'); +cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { + console.log('Promise returned with photoOutput created.'); }) ``` -### getFocusMode +### createVideoOutput -getFocusMode(callback: AsyncCallback): void +createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void -Obtains the current focus mode. This API uses an asynchronous callback to return the result. +Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the current focus mode.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance. | **Example** ```js -cameraInput.getFocusMode((err, afMode) => { +cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { if (err) { - console.error('Failed to get the focus mode ${err.message}'); + console.error('Failed to create videoOutput. ${err.message}'); return; } - console.log('Callback returned with current focus mode: ' + afMode); + console.log('Callback returned with an array of supported outputCapability' ); }) ``` -### getFocusMode +### createVideoOutput -getFocusMode(): Promise +createVideoOutput(profile: VideoProfile, surfaceId: string): Promise -Obtains the current focus mode. This API uses a promise to return the result. +Creates a **VideoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording configurations. | +| surfaceId | string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| + **Return value** -| Type | Description | -| ------------------- | ------------------------------------- | -| Promise | Promise used to return the current focus mode.| +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance.| **Example** ```js -cameraInput.getFocusMode().then((afMode) => { - console.log('Promise returned with current focus mode : ' + afMode); +cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { + console.log('Promise returned with videoOutput created.'); }) ``` -### getZoomRatioRange +### createMetadataOutput -getZoomRatioRange\(callback: AsyncCallback\>\): void +createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void -Obtains the zoom ratio range. This API uses an asynchronous callback to return the result. +Creates a **MetadataOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ------------------------ | -| callback | AsyncCallback\> | Yes | Callback used to return the zoom ratio range.| +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------------- | ---- | -------------------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types. | +| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance.| **Example** ```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { if (err) { - console.error('Failed to get the zoom ratio range. ${err.message}'); + console.error('Failed to create metadataOutput. ${err.message}'); return; } - console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); + console.log('Callback returned with metadataOutput created.'); }) ``` -### getZoomRatioRange +### createMetadataOutput -getZoomRatioRange\(\): Promise\> +createMetadataOutput(metadataObjectTypes: Array): Promise -Obtains the zoom ratio range. This API uses a promise to return the result. +Creates a **MetadataOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------------------------------- | ---- | ---------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| + **Return value** -| Type | Description | -| ------------------------ | ------------------------------------------- | -| Promise\> | Promise used to return the zoom ratio range.| +| Type | Description | +| ------------------------------------------- | ------------------------------------------- | +| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.| **Example** ```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { - console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); +cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataoutput) => { + console.log('Promise returned with metadataOutput created.'); }) ``` -### setZoomRatio +### createCaptureSession -setZoomRatio(zoomRatio: number, callback: AsyncCallback): void +createCaptureSession(callback: AsyncCallback): void -Sets a zoom ratio. This API uses an asynchronous callback to return the result. +Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------------ | -| zoomRatio | number | Yes | Zoom ratio to set. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| **Example** ```js -cameraInput.setZoomRatio(1, (err) => { +cameraManager.createCaptureSession((err, capturesession) => { if (err) { - console.error('Failed to set the zoom ratio value ${err.message}'); + console.error('Failed to create captureSession. ${err.message}'); return; } - console.log('Callback returned with the successful execution of setZoomRatio.'); + console.log('Callback returned with captureSession created.'); }) ``` -### setZoomRatio +### createCaptureSession -setZoomRatio(zoomRatio: number): Promise +createCaptureSession(): Promise -Sets a zoom ratio. This API uses a promise to return the result. +Creates a **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------ | -| zoomRatio | number | Yes | Zoom ratio to set.| - **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ------------------------------------------- | ------------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| **Example** ```js -cameraInput.setZoomRatio(1).then(() => { - console.log('Promise returned with the successful execution of setZoomRatio.'); +cameraManager.createCaptureSession().then((capturesession) => { + console.log('Promise returned with captureSession created.'); }) ``` -### getZoomRatio +### on('cameraStatus') -getZoomRatio(callback: AsyncCallback): void +on(type: 'cameraStatus', callback: AsyncCallback): void -Obtains the current zoom ratio. This API uses an asynchronous callback to return the result. +Listens for camera status changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the current zoom ratio.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **cameraStatus**, indicating the camera status change event.| +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | **Example** ```js -cameraInput.getZoomRatio((err, zoomRatio) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { - console.error('Failed to get the zoom ratio ${err.message}'); + console.error('Failed to get cameraStatus callback. ${err.message}'); return; } - console.log('Callback returned with current zoom ratio: ' + zoomRatio); + console.log('camera : ' + cameraStatusInfo.camera.cameraId); + console.log('status: ' + cameraStatusInfo.status); }) ``` -### getZoomRatio - -getZoomRatio(): Promise - -Obtains the current zoom ratio. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ---------------- | --------------------------- | -| Promise | Promise used to return the current zoom ratio.| +### on('cameraMute') -**Example** - -```js -cameraInput.getZoomRatio().then((zoomRatio) => { - console.log('Promise returned with current zoom ratio : ' + zoomRatio); -}) -``` +on(type: 'cameraMute', callback: AsyncCallback): void -### release +Listens for camera mute status changes. This API uses an asynchronous callback to return the result. -release\(callback: AsyncCallback\): void +This is a system API. -Releases this **CameraInput** instance. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **cameraMute**, indicating the camera mute status change event.| +| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | **Example** ```js -cameraInput.release((err) => { +cameraManager.on('cameraMute', (err, status) => { if (err) { - console.error('Failed to release the CameraInput instance ${err.message}'); + console.error('Failed to get cameraMute callback. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); + console.log('status: ' + status); +}) ``` -### release - -release(): Promise +## CameraStatusInfo -Releases this **CameraInput** instance. This API uses a promise to return the result. +Describes the camera status information. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +| Name | Type | Description | +| ------ | ----------------------------- | ---------- | +| camera | [CameraDevice](#cameraDevice) | Camera object.| +| status | [CameraStatus](#camerastatus) | Camera status.| -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +## CameraPosition -**Example** +Enumerates the camera positions. -```js -cameraInput.release().then(() => { - console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); -}) -``` +**System capability**: SystemCapability.Multimedia.Camera.Core -### on('focusStateChange') +| Name | Value | Description | +| --------------------------- | ---- | ---------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| +| CAMERA_POSITION_BACK | 1 | Rear camera. | +| CAMERA_POSITION_FRONT | 2 | Front camera. | -on(type: 'focusStateChange', callback: AsyncCallback): void +## CameraType -Listens for focus state changes. This API uses an asynchronous callback to return the focus state changes. +Enumerates the camera types. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +| Name | Value | Description | +| ----------------------- | ---- | ------------------ | +| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type. | +| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | +| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | +| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | +| CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information.| -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------------- | :--- | :------------------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **focusStateChange**, indicating the focus state change event.| -| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | +## ConnectionType -**Example** +Enumerates the camera connection types. -```js -cameraInput.on('focusStateChange', (focusState) => { - console.log('Focus state : ' + focusState); -}) -``` +**System capability**: SystemCapability.Multimedia.Camera.Core -### on('error') +| Name | Value | Description | +| ---------------------------- | ---- | ---------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB. | +| CAMERA_CONNECTION_REMOTE | 2 | Remote camera.| -on(type: 'error', callback: ErrorCallback): void +## CameraDevice -Listens for **CameraInput** errors. This API uses a callback to return the errors. +Defines the camera device information. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| :------- | :------------------------------- | :--- | :----------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the camera input error event.| -| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Read only| Description | +| -------------- | --------------------------------- | ---- | ---------------- | +| cameraId | string | Yes | **CameraDevice** object.| +| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | +| cameraType | [CameraType](#cameratype) | Yes | Camera type. | +| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type. | **Example** ```js -cameraInput.on('error', (cameraInputError) => { - console.log('Camera input error code: ' + cameraInputError.code); -}) +async function getCameraInfo("cameraId") { + var cameraManager = await camera.getCameraManager(context); + var cameras = await cameraManager.getSupportedCameras(); + var cameraObj = cameras[0]; + var cameraId = cameraObj.cameraId; + var cameraPosition = cameraObj.cameraPosition; + var cameraType = cameraObj.cameraType; + var connectionType = cameraObj.connectionType; +} ``` -## CameraInputErrorCode - -Enumerates the **CameraInput** error codes. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| - -## CameraInputError +## Size -Defines a **CameraInput** error object. +Enumerates the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| - +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------------ | +| height | number | Yes | Yes | Image height, in pixels.| +| width | number | Yes | Yes | Image width, in pixel.| -## FlashMode +## Point -Enumerates the flash modes. +Enumerates the point coordinates, which are used for focus and exposure configuration. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------- | ---- | ------------ | -| FLASH_MODE_CLOSE | 0 | The flash is off.| -| FLASH_MODE_OPEN | 1 | The flash is on.| -| FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| -| FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ----------- | +| x | number | Yes | X coordinate of a point.| +| y | number | Yes | Y coordinate of a point.| -## FocusMode +## CameraFormat -Enumerates the focus modes. +Enumerates the camera output format. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------------- | ---- | ------------------ | -| FOCUS_MODE_MANUAL | 0 | Manual focus. | -| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| -| FOCUS_MODE_AUTO | 2 | Auto focus. | -| FOCUS_MODE_LOCKED | 3 | Locked focus. | - -## FocusState - -Enumerates the focus states. +| Name | Default Value| Description | +| ------------------------ | ------ | ---------------------- | +| CAMERA_FORMAT_YUV_420_SP | 1003 | YUV 420 SP image.| +| CAMERA_FORMAT_JPEG | 2000 | JPEG image. | -**System capability**: SystemCapability.Multimedia.Camera.Core +## CameraInput -| Name | Value | Description | -| --------------------- | ---- | ------------ | -| FOCUS_STATE_SCAN | 0 | Scanning. | -| FOCUS_STATE_FOCUSED | 1 | Focused.| -| FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| +Provides camera information used in **[CaptureSession](#capturesession)**. -## camera.createCaptureSession +### open -createCaptureSession\(context: Context, callback: AsyncCallback\): void +open\(callback: AsyncCallback\): void -Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the instance. +Opens this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------------------------- | -| context | Context | Yes | Application context. | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -camera.createCaptureSession((context), (err, captureSession) => { +cameraInput.open((err) => { if (err) { - console.error('Failed to create the CaptureSession instance. ${err.message}'); + console.error('Failed to open the camera. ${err.message}'); return; } - console.log('Callback returned with the CaptureSession instance.' + captureSession); -}); + console.log('Callback returned with camera opened.'); +}) ``` -## camera.createCaptureSession +### open -createCaptureSession(context: Context\): Promise; +open(): Promise -Creates a **CaptureSession** instance. This API uses a promise to return the instance. +Opens this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------- | ---- | ------------ | -| context | Context | Yes | Application context.| - **Return value** -| Type | Description | -| ------------------------------------------- | ----------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -camera.createCaptureSession(context).then((captureSession) => { - console.log('Promise returned with the CaptureSession instance'); +cameraInput.open().then(() => { + console.log('Promise returned with camera opened.'); }) ``` -## CaptureSession - -Implements session capture. - -### beginConfig +### close -beginConfig\(callback: AsyncCallback\): void +close\(callback: AsyncCallback\): void -Starts configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Closes this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1180,20 +1145,20 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn **Example** ```js -captureSession.beginConfig((err) => { +cameraInput.close((err) => { if (err) { - console.error('Failed to start the configuration. ${err.message}'); + console.error('Failed to close the cameras. ${err.message}'); return; } - console.log('Callback invoked to indicate the begin config success.'); -}); + console.log('Callback returned with camera closed.'); +}) ``` -### beginConfig +### close -beginConfig\(\): Promise +close(): Promise -Starts configuration for this **CaptureSession** instance. This API uses a promise to return the result. +Closes this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1201,22 +1166,21 @@ Starts configuration for this **CaptureSession** instance. This API uses a promi | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise| Promise used to return the result.| **Example** ```js -captureSession.beginConfig().then(() => { - console.log('Promise returned to indicate the begin config success.'); +cameraInput.close().then(() => { + console.log('Promise returned with camera closed.'); }) ``` -### commitConfig +### release -commitConfig\(callback: AsyncCallback\): void +release\(callback: AsyncCallback\): void -Commits the configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Releases this camera. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1229,20 +1193,20 @@ Commits the configuration for this **CaptureSession** instance. This API uses an **Example** ```js -captureSession.commitConfig((err) => { +cameraInput.release((err) => { if (err) { - console.error('Failed to commit the configuration. ${err.message}'); + console.error('Failed to release the CameraInput instance ${err.message}'); return; } - console.log('Callback invoked to indicate the commit config success.'); + console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); }); ``` -### commitConfig +### release -commitConfig\(\): Promise +release(): Promise -Commits the configuration for this **CaptureSession** instance. This API uses a promise to return the result. +Releases this camera. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1250,131 +1214,246 @@ Commits the configuration for this **CaptureSession** instance. This API uses a | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** ```js -captureSession.commitConfig().then(() => { - console.log('Promise returned to indicate the commit config success.'); +cameraInput.release().then(() => { + console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); }) ``` -### addInput +### on('error') -addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +on(type: 'error', callback: ErrorCallback): void -Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Listens for **CameraInput** errors. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **error**, indicating the camera input error event.| +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | **Example** ```js -captureSession.addInput(cameraInput, (err) => { +cameraInput.on('error', (cameraInputError) => { + console.log('Camera input error code: ' + cameraInputError.code); +}) +``` + +## CameraInputErrorCode + +Enumerates the error codes used for camera input. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ------------------------- | ---- | -------------- | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_NO_PERMISSION | 0 | You do not have the required permission. | +| ERROR_DEVICE_PREEMPTED | 1 | The camera is preempted. | +| ERROR_DEVICE_DISCONNECTED | 2 | The camera is disconnected.| +| ERROR_DEVICE_IN_USE | 3 | The camera is in use.| +| ERROR_DRIVER_ERROR | 4 | Driver error. | + +## CameraInputError + +Defines an error object used for **[CameraInput](#camerainput)**. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name| Type | Description | +| ---- | --------------------------------------------- | ----------------------- | +| code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| + + +## FlashMode + +Enumerates the flash modes. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ---------------------- | ---- | ------------ | +| FLASH_MODE_CLOSE | 0 | The flash is off.| +| FLASH_MODE_OPEN | 1 | The flash is on.| +| FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| +| FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| + +## ExposureMode + +Enumerates the exposure modes. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ----------------------------- | ---- | -------------- | +| EXPOSURE_MODE_LOCKED | 0 | Exposure locked.| +| EXPOSURE_MODE_AUTO | 1 | Auto exposure.| +| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.| + +## FocusMode + +Enumerates the focus modes. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| -------------------------- | ---- | -------------- | +| FOCUS_MODE_MANUAL | 0 | Manual focus. | +| FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| +| FOCUS_MODE_AUTO | 2 | Auto focus. | +| FOCUS_MODE_LOCKED | 3 | Focus locked. | + +## FocusState + +Enumerates the focus states. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| FOCUS_STATE_SCAN | 0 | Focusing. | +| FOCUS_STATE_FOCUSED | 1 | Focused. | +| FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| + +## ExposureState + +Enumerates the exposure states. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------- | +| EXPOSURE_STATE_SCAN | 0 | Exposing. | +| EXPOSURE_STATE_CONVERGED | 1 | Exposure converged.| + +## VideoStabilizationMode + +Enumerates the video stabilization modes. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ------ | ---- | ---------------------------------------------------- | +| OFF | 0 | Video stabilization is disabled. | +| LOW | 1 | The basic video stabilization algorithm is used. | +| MIDDLE | 2 | A video stabilization algorithm with a stabilization effect better than that of the **LOW** type is used. | +| HIGH | 3 | A video stabilization algorithm with a stabilization effect better than that of the **MIDDLE** type is used.| +| AUTO | 4 | Automatic video stabilization is used. | + +## CaptureSession + +Implements a shooting session, which saves all **[CameraInput](#camerainput)** and **[CameraOutput](#cameraoutput)** instances required to run the camera and requests the camera to complete shooting or video recording. + +### beginConfig + +beginConfig\(callback: AsyncCallback\): void + +Starts configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +captureSession.beginConfig((err) => { if (err) { - console.error('Failed to add the CameraInput instance. ${err.message}'); + console.error('Failed to start the configuration. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraInput instance is added.'); + console.log('Callback invoked to indicate the begin config success.'); }); ``` -### addInput +### beginConfig -addInput\(cameraInput: CameraInput\): Promise +beginConfig\(\): Promise -Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Starts configuration for this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| - **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| + **Example** ```js -captureSession.addInput(cameraInput).then(() => { - console.log('Promise used to indicate that the CameraInput instance is added.'); +captureSession.beginConfig().then(() => { + console.log('Promise returned to indicate the begin config success.'); }) ``` -### addOutput +### commitConfig -addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +commitConfig\(callback: AsyncCallback\): void -Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Commits the configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.addOutput(previewOutput, (err) => { +captureSession.commitConfig((err) => { if (err) { - console.error('Failed to add the PreviewOutput instance ${err.message}'); + console.error('Failed to commit the configuration. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); + console.log('Callback invoked to indicate the commit config success.'); }); ``` -### addOutput +### commitConfig -addOutput\(previewOutput: PreviewOutput\): Promise +commitConfig\(\): Promise -Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Commits the configuration for this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| - **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** ```js -captureSession.addOutput(previewOutput).then(() => { - console.log('Promise used to indicate that the PreviewOutput instance is added.'); +captureSession.commitConfig().then(() => { + console.log('Promise returned to indicate the commit config success.'); }) ``` -### addOutput +### canAddInput -addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void +canAddInput(cameraInput: CameraInput, callback: AsyncCallback): void -Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Checks whether a **[CameraInput](#camerainput)** instance can be added to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1382,26 +1461,26 @@ Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API us | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addOutput(photoOutput, (err) => { +captureSession.canAddInput(cameraInput, (err, status) => { if (err) { - console.error('Failed to add the PhotoOutput instance ${err.message}'); + console.error('Can not add cameraInput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); -}); + console.log('Callback returned with cameraInput can added.'); +}) ``` -### addOutput +### canAddInput -addOutput\(photoOutput: PhotoOutput\): Promise +canAddInput(cameraInput: CameraInput): Promise -Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Checks whether a **[CameraInput](#camerainput)** instance can be added to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1409,27 +1488,27 @@ Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API us | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to add.| +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| ----------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -captureSession.addOutput(photoOutput).then(() => { - console.log('Promise used to indicate that the PhotoOutput instance is added.'); +captureSession.canAddInput(cameraInput).then(() => { + console.log('Promise returned with cameraInput can added.'); }) ``` -### addOutput +### addInput -addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void +addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1437,26 +1516,26 @@ Adds a **VideoOutput** instance to this **CaptureSession** instance. This API us | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addOutput(videoOutput, (err) => { +captureSession.addInput(cameraInput, (err) => { if (err) { - console.error('Failed to add the VideoOutput instance ${err.message}'); + console.error('Failed to add the CameraInput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is added.'); + console.log('Callback invoked to indicate that the CameraInput instance is added.'); }); ``` -### addOutput +### addInput -addOutput\(videoOutput: VideoOutput\): Promise +addInput\(cameraInput: CameraInput\): Promise -Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. +Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1464,19 +1543,19 @@ Adds a **VideoOutput** instance to this **CaptureSession** instance. This API us | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** ```js -captureSession.addOutput(videoOutput).then(() => { - console.log('Promise used to indicate that the VideoOutput instance is added.'); +captureSession.addInput(cameraInput).then(() => { + console.log('Promise used to indicate that the CameraInput instance is added.'); }) ``` @@ -1484,7 +1563,7 @@ captureSession.addOutput(videoOutput).then(() => { removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1511,7 +1590,7 @@ captureSession.removeInput(cameraInput, (err) => { removeInput\(cameraInput: CameraInput\): Promise -Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1523,9 +1602,9 @@ Removes a **CameraInput** instance from this **CaptureSession** instance. This A **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| --------------- | --------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -1535,174 +1614,172 @@ captureSession.removeInput(cameraInput).then(() => { }) ``` -### removeOutput +### canAddOutput -removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void +canAddOutput(cameraOutput: CameraOutput, callback: AsyncCallback\): void -Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeOutput(previewOutput, (err) => { +captureSession.canAddOutput(cameraOutput, (err, status) => { if (err) { - console.error('Failed to remove the PreviewOutput instance. ${err.message}'); + console.error('Can not add cameraOutput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is removed.'); -}); + console.log('Callback returned with cameraOutput can added.'); +}) ``` -### removeOutput +### canAddOutput -removeOutput(previewOutput: PreviewOutput): Promise +canAddOutput(cameraOutput: CameraOutput): Promise -Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----------------------------- | -| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to add.| **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ----------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -captureSession.removeOutput(previewOutput).then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); +captureSession.canAddOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput can added.'); }) ``` -### removeOutput +### addOutput -removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void +addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeOutput(photoOutput, (err) => { +captureSession.addOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to remove the PhotoOutput instance. ${err.message}'); + console.error('Failed to add output. ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); -}); + console.log('Callback returned with output added.'); +}) ``` -### removeOutput +### addOutput -removeOutput(photoOutput: PhotoOutput): Promise +addOutput\(cameraOutput: CameraOutput\): Promise -Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| - +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to add.| **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise| Promise used to return the result.| **Example** ```js -captureSession.removeOutput(photoOutput).then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); +captureSession.addOutput(cameraOutput).then(() => { + console.log('Promise returned with cameraOutput added.'); }) ``` ### removeOutput -removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void +removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void -Removes a **VideoOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeOutput(videoOutput, (err) => { +captureSession.removeOutput(cameraOutput, (err) => { if (err) { - console.error('Failed to remove the VideoOutput instance. ${err.message}'); + console.error('Failed to remove the CameraOutput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is removed.'); + console.log('Callback invoked to indicate that the CameraOutput instance is removed.'); }); ``` ### removeOutput -removeOutput(videoOutput: VideoOutput): Promise +removeOutput(cameraOutput: CameraOutput): Promise -Removes a **VideoOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. +Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | --------------------------- | -| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| +| Name | Type | Mandatory| Description | +| ------------ | ----------------------------- | ---- | ---------------------------- | +| cameraOutput | [CameraOutput](#cameraOutput) | Yes | **CameraOutput** instance to remove.| **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** ```js -captureSession.removeOutput(videoOutput).then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is removed.'); +captureSession.removeOutput(cameraOutput).then(() => { + console.log('Promise returned to indicate that the CameraOutput instance is removed.'); }) ``` @@ -1710,7 +1787,7 @@ captureSession.removeOutput(videoOutput).then(() => { start\(callback: AsyncCallback\): void -Starts this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Starts this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1736,7 +1813,7 @@ captureSession.start((err) => { start\(\): Promise -Starts this **CaptureSession** instance. This API uses a promise to return the result. +Starts this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1744,7 +1821,7 @@ Starts this **CaptureSession** instance. This API uses a promise to return the r | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** @@ -1758,13 +1835,12 @@ captureSession.start().then(() => { stop\(callback: AsyncCallback\): void -Stops this **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Stops this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** - | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| @@ -1785,7 +1861,7 @@ captureSession.stop((err) => { stop(): Promise -Stops this **CaptureSession** instance. This API uses a promise to return the result. +Stops this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1793,7 +1869,7 @@ Stops this **CaptureSession** instance. This API uses a promise to return the re | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** @@ -1803,11 +1879,11 @@ captureSession.stop().then(() => { }) ``` -### release +### lockForControl -release\(callback: AsyncCallback\): void +lockForControl(callback: AsyncCallback): void -Releases this **CaptureSession** instance. This API uses an asynchronous callback to return the instance. +Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses an asynchronous callback to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the lock. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1820,20 +1896,20 @@ Releases this **CaptureSession** instance. This API uses an asynchronous callbac **Example** ```js -captureSession.release((err) => { +captureSession.lockForControl((err) => { if (err) { - console.error('Failed to release the CaptureSession instance ${err.message}'); + console.error('Failed to lock. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); -}); + console.log('Locked.'); +}) ``` -### release +### lockForControl -release(): Promise +lockForControl(): Promise -Releases this **CaptureSession** instance. This API uses a promise to return the result. +Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses a promise to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the lock. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1841,123 +1917,69 @@ Releases this **CaptureSession** instance. This API uses a promise to return the | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - -**Example** - -```js -captureSession.release().then(() => { - console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); -}) -``` - -### on('error') - -on(type: 'error', callback: ErrorCallback): void - -Listens for **CaptureSession** errors. This API uses a callback to return the errors. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the capture session error event.| -| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | +| Promise| Promise used to return the result.| **Example** ```js -captureSession.on('error', (captureSessionError) => { - console.log('Capture session error code: ' + captureSessionError.code); +captureSession.lockForControl().then(() => { + console.log('Locked.'); }) ``` -## CaptureSessionErrorCode - -Enumerates the **CaptureSession** error codes. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| - -## CaptureSessionError - -Defines a **CaptureSession** error object. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name| Type | Description | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| - -## camera.createPreviewOutput +### unlockForControl -createPreviewOutput(surfaceId: string, callback: AsyncCallback): void +unlockForControl(callback: AsyncCallback): void -Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the instance. +Releases the exclusive control on the device configuration. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------------------------------- | ---- | ------------------------------------- | -| surfaceId | string | Yes | Surface ID received from **XComponent**. | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { +captureSession.unlockForControl((err) => { if (err) { - console.error('Failed to create the PreviewOutput instance. ${err.message}'); + console.error('Failed to unlock. ${err.message}'); return; } - console.log('Callback returned with previewOutput instance'); -}); + console.log('Unlocked.'); +}) ``` -## camera.createPreviewOutput +### unlockForControl -createPreviewOutput(surfaceId: string): Promise\ +unlockForControl(): Promise -Creates a **PreviewOutput** instance. This API uses a promise to return the instance. +Releases the exclusive control on the device configuration. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------------------------------- | -| surfaceId | string | Yes | Surface ID received from **XComponent**.| - **Return value** -| Type | Description | -| ----------------------------------------- | --------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -camera.createPreviewOutput("surfaceId").then((previewOutput) => { - console.log('Promise returned with the PreviewOutput instance'); +captureSession.unlockForControl().then(() => { + console.log('Unlocked.'); }) ``` -## PreviewOutput - -Implements preview output. - ### release -release(callback: AsyncCallback): void +release\(callback: AsyncCallback\): void -Releases this **PreviewOutput** instance. This API uses an asynchronous callback to return the result. +Releases this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1970,12 +1992,12 @@ Releases this **PreviewOutput** instance. This API uses an asynchronous callback **Example** ```js -previewOutput.release((err) => { +captureSession.release((err) => { if (err) { - console.error('Failed to release the PreviewOutput instance ${err.message}'); + console.error('Failed to release the CaptureSession instance ${err.message}'); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); + console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); }); ``` @@ -1983,7 +2005,7 @@ previewOutput.release((err) => { release(): Promise -Releases this **PreviewOutput** instance. This API uses a promise to return the result. +Releases this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1991,18 +2013,1565 @@ Releases this **PreviewOutput** instance. This API uses a promise to return the | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise| Promise used to return the result.| **Example** ```js -previewOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +captureSession.release().then(() => { + console.log('Promise returned to indicate that the CaptureSession instance is released successfully.'); }) ``` -### on('frameStart') +### hasFlash + +hasFlash(callback: AsyncCallback): void + +Checks whether the device has flash light. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the flash light support status. The value **true** means that the device has flash light.| + +**Example** + +```js +cameraInput.hasFlash((err, status) => { + if (err) { + console.error('Failed to check whether the device has flash light. ${err.message}'); + return; + } + console.log('Callback returned with flash light support status: ' + status); +}) +``` + +### hasFlash + +hasFlash(): Promise + +Checks whether the device has flash light. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------- | +| Promise | Promise used to return the flash light support status. The value **true** means that the device has flash light.| + +**Example** + +```js +cameraInput.hasFlash().then((status) => { + console.log('Promise returned with the flash light support status:' + status); +}) +``` + +### isFlashModeSupported + +isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void + +Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------------------------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { + if (err) { + console.error('Failed to check whether the flash mode is supported. ${err.message}'); + return; + } + console.log('Callback returned with the flash mode support status: ' + status); +}) +``` + +### isFlashModeSupported + +isFlashModeSupported(flashMode: FlashMode): Promise + +Checks whether a specified flash mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { + console.log('Promise returned with flash mode support status.' + status); +}) +``` + +### setFlashMode + +setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void + +Sets the flash mode. This API uses an asynchronous callback to return the result. + +Before the setting, do the following checks: + +1. Use **[hasFlash](#hasflash)** to check whether the device has flash light. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------------------ | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { + if (err) { + console.error('Failed to set the flash mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFlashMode.'); +}) +``` + +### setFlashMode + +setFlashMode(flashMode: FlashMode): Promise + +Sets a flash mode. This API uses a promise to return the result. + +Before the setting, do the following checks: + +1. Use **[hasFlash](#hasflash)** to check whether the device has flash light. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFlashMode.'); +}) +``` + +### getFlashMode + +getFlashMode(callback: AsyncCallback): void + +Obtains the flash mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| + +**Example** + +```js +cameraInput.getFlashMode((err, flashMode) => { + if (err) { + console.error('Failed to get the flash mode ${err.message}'); + return; + } + console.log('Callback returned with current flash mode: ' + flashMode); +}) +``` + +### getFlashMode + +getFlashMode(): Promise + +Obtains the flash mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| --------------------------------- | --------------------------------------- | +| Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| + +**Example** + +```js +cameraInput.getFlashMode().then((flashMode) => { + console.log('Promise returned with current flash mode : ' + flashMode); +}) +``` + +### isExposureModeSupported + +isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; + +Checks whether a specified exposure mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------------ | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| callback | AsyncCallback | Yes | Callback used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log('Failed to check exposure mode supported ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of isExposureModeSupported'); +}) +``` + +### isExposureModeSupported + +isExposureModeSupported(aeMode: ExposureMode): Promise + +Checks whether a specified exposure mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ---------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode.| + +**Return value** + +| Name | Description | +| ----------------- | ------------------------------------- | +| Promise | Promise used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log('Promise returned with exposure mode supported : ' + isSupported); +}) +``` + +### getExposureMode + +getExposureMode(callback: AsyncCallback): void + +Obtains the exposure mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.| + +**Example** + +```js +cameraInput.getExposureMode((err, exposureMode) => { + if (err) { + console.log('Failed to get the exposure mode ${err.message}'); + return ; + } + console.log('Callback returned with current exposure mode:' + exposureMode); +}) +``` + +### getExposureMode + +getExposureMode(): Promise + +Obtains the exposure mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| --------------------------------------- | ----------------------------------- | +| Promise<[ExposureMode](#exposuremode)\> | Promise used to return the exposure mode.| + +**Example** + +```js +cameraInput.getExposureMode().then((exposureMode) => { + console.log('Promise returned with current exposure mode : ' + exposureMode); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void + +Sets an exposure mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------------- | +| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { + if (err) { + console.log('Failed to set the exposure mode ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setExposureMode'); +}) +``` + +### setExposureMode + +setExposureMode(aeMode: ExposureMode): Promise + +Sets an exposure mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| -------------- | ------------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { + console.log('Promise returned with the successful execution of setExposureMode.'); +}) +``` + +### getMeteringPoint + +getMeteringPoint(callback: AsyncCallback): void + +Obtains the center of the metering area. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the center of the metering area.| + +**Example** + +```js +cameraInput.getMeteringPoint((err, exposurePoint) => { + if (err) { + console.log('Failed to get the current exposure point ${err.message}'); + return ; + } + console.log('Callback returned with current exposure point:' + exposurePoint); +}) +``` + +### getMeteringPoint + +getMeteringPoint(): Promise + +Obtains the center of the metering area. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ------------------------- | --------------------------------- | +| Promise<[Point](#point)\> | Promise used to return the center of the metering area.| + +**Example** + +```js +cameraInput.getMeteringPoint().then((exposurePoint) => { + console.log('Promise returned with current exposure point : ' + exposurePoint); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point, callback: AsyncCallback): void + +Sets the center of the metering area. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------ | +| exposurePoint | [Point](#point) | Yes | Exposure point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +var Point1 = {x: 1, y: 1}; + +cameraInput.setMeteringPoint(Point1,(err) => { + if (err) { + console.log('Failed to set the exposure point ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setMeteringPoint'); +}) +``` + +### setMeteringPoint + +setMeteringPoint(point: Point): Promise + +Sets the center of the metering area. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------------- | ---- | -------- | +| exposurePoint | [Point](#point) | Yes | Exposure point.| + +**Return value** + +| Name | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the center of the metering area.| + +**Example** + +```js +var Point2 = {x: 2, y: 2}; + +cameraInput.setMeteringPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setMeteringPoint'); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(callback: AsyncCallback\>): void + +Obtains the exposure compensation values. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ---------------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the array of compensation values.| + +**Example** + +```js +cameraInput.getExposureBiasRange((err, biasRangeArray) => { + if (err) { + console.log('Failed to get the array of compenstation range ${err.message}'); + return ; + } + console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); +}) +``` + +### getExposureBiasRange + +getExposureBiasRange(): Promise\> + +Obtains the exposure compensation values. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ------------------------ | ----------------------------------- | +| Promise\> | Promise used to return the array of compensation values.| + +**Example** + +```js +cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { + console.log('Promise returned with exposure mode supported : ' + isSupported); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number, callback: AsyncCallback): void + +Sets an exposure compensation value. This API uses an asynchronous callback to return the result. + +Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | -------------------- | ---- | ------------------------ | +| exposureBias | number | Yes | Compensation value. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.setExposureBias(-4,(err) => { + if (err) { + console.log('Failed to set the exposure bias ${err.message}'); + return ; + } + console.log('Callback returned with the successful excution of setExposureBias'); +}) +``` + +### setExposureBias + +setExposureBias(exposureBias: number): Promise + +Sets an exposure compensation value. This API uses a promise to return the result. + +Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | ---------- | +| exposureBias | number | Yes | Compensation value.| + +**Return value** + +| Name | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +cameraInput.setExposureBias(-4).then(() => { + console.log('Promise returned with the successful execution of setExposureBias.'); +}) +``` + +### getExposureValue + +getExposureValue(callback: AsyncCallback): void + +Obtains the exposure value in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------- | +| callback | AsyncCallback | Yes | Callback used to the exposure value.| + +**Example** + +```js +cameraInput.getExposureValue((err, exposureValue) => { + if (err) { + console.log('Failed to get the exposure value ${err.message}'); + return ; + } + console.log('Callback returned with the exposure value: ' + exposureValue); +}) +``` + +### getExposureValue + +getExposureValue(): Promise + +Obtains the exposure value in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Name | Description | +| ---------------- | ----------------------------- | +| Promise | Promise used to the exposure value.| + +**Example** + +```js +cameraInput.getExposureValue().then((exposureValue) => { + console.log('Promise returned with exposure value: ' + exposureValue); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void + +Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { + if (err) { + console.error('Failed to check whether the focus mode is supported. ${err.message}'); + return; + } + console.log('Callback returned with the focus mode support status: ' + status); +}) +``` + +### isFocusModeSupported + +isFocusModeSupported(afMode: FocusMode): Promise + +Checks whether a specified focus mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------------------- | +| Promise | Promise used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| + +**Example** + +```js +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { + console.log('Promise returned with focus mode support status.' + status); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode, callback: AsyncCallback): void + +Sets a focus mode. This API uses an asynchronous callback to return the result. + +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------ | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { + if (err) { + console.error('Failed to set the focus mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFocusMode.'); +}) +``` + +### setFocusMode + +setFocusMode(afMode: FocusMode): Promise + +Sets a focus mode. This API uses a promise to return the result. + +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFocusMode.'); +}) +``` + +### getFocusMode + +getFocusMode(callback: AsyncCallback): void + +Obtains the focus mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| + +**Example** + +```js +cameraInput.getFocusMode((err, afMode) => { + if (err) { + console.error('Failed to get the focus mode ${err.message}'); + return; + } + console.log('Callback returned with current focus mode: ' + afMode); +}) +``` + +### getFocusMode + +getFocusMode(): Promise + +Obtains the focus mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------- | +| Promise | Promise used to return the focus mode.| + +**Example** + +```js +cameraInput.getFocusMode().then((afMode) => { + console.log('Promise returned with current focus mode : ' + afMode); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point, callback: AsyncCallback): void + +Sets a focus point. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| point | [Point](#Point) | Yes | Focus point. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +var Point1 = {x: 1, y: 1}; + +cameraInput.setFocusPoint(Point1, (err) => { + if (err) { + console.error('Failed to set the focus point ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setFocusPoint.'); +}) +``` + +### setFocusPoint + +setFocusPoint(point: Point): Promise + +Sets a focus point. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------------- | ---- | ------ | +| point | [Point](#Point) | Yes | Focus point.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +var Point2 = {x: 2, y: 2}; + +cameraInput.setFocusPoint(Point2).then(() => { + console.log('Promise returned with the successful execution of setFocusPoint.'); +}) +``` + +### getFocusPoint + +getFocusPoint(callback: AsyncCallback): void + +Obtains the focus point. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the focus point.| + +**Example** + +```js +cameraInput.getFocusPoint((err, point) => { + if (err) { + console.error('Failed to get the current focus point ${err.message}'); + return; + } + console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocusPoint + +getFocusPoint(): Promise + +Obtains the focus point. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise | Promise used to return the focus point.| + +**Example** + +```js +cameraInput.getFocusPoint().then((point) => { + console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); +}) +``` + +### getFocalLength + +getFocalLength(callback: AsyncCallback): void + +Obtains the focal length. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the focal length.| + +**Example** + +```js +cameraInput.getFocalLength((err, focalLength) => { + if (err) { + console.error('Failed to get the current focal length ${err.message}'); + return; + } + console.log('Callback returned with the current focal length: ' + focalLength); +}) +``` + +### getFocalLength + +getFocalLength(): Promise + +Obtains the focal length. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ---------------- | --------------------------- | +| Promise | Promise used to return the focal length.| + +**Example** + +```js +cameraInput.getFocalLength().then((focalLength) => { + console.log('Promise returned with the current focal length: ' + focalLength); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(callback: AsyncCallback\>\): void + +Obtains the zoom range. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return the zoom range.| + +**Example** + +```js +cameraInput.getZoomRatioRange((err, zoomRatioRange) => { + if (err) { + console.error('Failed to get the zoom ratio range. ${err.message}'); + return; + } + console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); +}) +``` + +### getZoomRatioRange + +getZoomRatioRange\(\): Promise\> + +Obtains the zoom range. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ------------------------ | ------------------------------- | +| Promise\> | Promise used to return the zoom range.| + +**Example** + +```js +cameraInput.getZoomRatioRange().then((zoomRatioRange) => { + console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number, callback: AsyncCallback): void + +Sets a zoom ratio. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------ | +| zoomRatio | number | Yes | Zoom ratio. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.setZoomRatio(1, (err) => { + if (err) { + console.error('Failed to set the zoom ratio value ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setZoomRatio.'); +}) +``` + +### setZoomRatio + +setZoomRatio(zoomRatio: number): Promise + +Sets a zoom ratio. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------ | +| zoomRatio | number | Yes | Zoom ratio.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +cameraInput.setZoomRatio(1).then(() => { + console.log('Promise returned with the successful execution of setZoomRatio.'); +}) +``` + +### getZoomRatio + +getZoomRatio(callback: AsyncCallback): void + +Obtains the zoom ratio in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +cameraInput.getZoomRatio((err, zoomRatio) => { + if (err) { + console.error('Failed to get the zoom ratio ${err.message}'); + return; + } + console.log('Callback returned with current zoom ratio: ' + zoomRatio); +}) +``` + +### getZoomRatio + +getZoomRatio(): Promise + +Obtains the zoom ratio in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ---------------- | --------------------------- | +| Promise | Promise used to return the zoom ratio.| + +**Example** + +```js +cameraInput.getZoomRatio().then((zoomRatio) => { + console.log('Promise returned with current zoom ratio : ' + zoomRatio); +}) +``` + +### isVideoStablizationModeSupported + +isVideoStablizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void + +Checks whether a specified video stabilization mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------ | +| vsMode | [VideoStabilizationMode](#videostabilizationMode) | Yes | Video stabilization mode. | +| callback | AsyncCallback | Yes | Callback used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.| + +**Example** + +```js +captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => { + if (err) { + console.error('Failed to check whether video stabilization mode supported. ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of isVideoStabilizationModeSupported: ' + status); +}) +``` + +### isVideoStablizationModeSupported + +isVideoStablizationModeSupported(vsMode: VideoStabilizationMode): Promise + +Checks whether a specified video stabilization mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------------- | +| Promise | Promise used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.| + +**Example** + +```js +captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => { + console.log('Promise returned with video stabilization mode supported: ' + isSupported); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(callback: AsyncCallback): void + +Obtains the video stabilization mode in use. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the video stabilization mode.| + +**Example** + +```js +captureSession.getActiveVideoStabilizationMode((err, vsMode) => { + if (err) { + console.error('Failed to get active video stabilization mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); +}) +``` + +### getActiveVideoStabilizationMode + +getActiveVideoStabilizationMode(): Promise + +Obtains the video stabilization mode in use. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------------------------------------------- | +| Promise | Promise used to return the video stabilization mode.| + +**Example** + +```js +captureSession.getActiveVideoStabilizationMode().then((vsMode) => { + console.log('Promise returned with the current video stabilization mode: ' + vsMode); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void + +Sets a video stabilization mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------ | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode.| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { + if (err) { + console.error('Failed to set the video stabilization mode ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### setVideoStabilizationMode + +setVideoStabilizationMode(mode: VideoStabilizationMode): Promise + +Sets a video stabilization mode. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------------------------------------------------- | ---- | ------------------------ | +| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------------------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { + console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); +}) +``` + +### on('focusStateChange') + +on(type: 'focusStateChange', callback: AsyncCallback): void + +Listens for focus state changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | -------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **focusStateChange**, indicating the focus state change event.| +| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | + +**Example** + +```js +cameraInput.on('focusStateChange', (focusState) => { + console.log('Focus state : ' + focusState); +}) +``` + +### on('exposureStateChange') + +on(type: 'exposureStateChange', callback: AsyncCallback): void + +Listens for exposure state changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'exposureStateChange'**, indicating the exposure state change event.| +| callback | AsyncCallback<[ExposureState](#exposureState)\> | Yes | Callback used to return the exposure state change. | + +**Example** + +```js +cameraInput.on('exposureStateChange', (exposureState) => { + console.log('Exposuer state : ' + exposureState); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for **CaptureSession** errors. This API uses a callback to return the errors. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | --------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **error**, indicating the capture session error event.| +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | + +**Example** + +```js +captureSession.on('error', (captureSessionError) => { + console.log('Capture session error code: ' + captureSessionError.code); +}) +``` + +## CaptureSessionErrorCode + +Enumerates the error codes used in a **CaptureSession**. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ---------------------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| +| ERROR_TIMEOUT | 1 | Timeout. | + +## CaptureSessionError + +Defines a capture session error. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| + +## CameraOutput + +Implements output information used in a **[CaptureSession](#capturesession)**. It is the base class of **output**. + +### release + +release(callback: AsyncCallback): void + +Releases output resources. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +previewOutput.release((err) => { + if (err) { + console.error('Failed to release the PreviewOutput instance ${err.message}'); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +Releases output resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +previewOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +}) +``` + +## PreviewOutput + +Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. + +### addDeferredSurface + +addDeferredSurface(surfaceId: string, callback: AsyncCallback): void + +Adds a surface after a **PreviewOutput** instance is created. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------------------------------------------ | +| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +previewOutput.addDeferredSurface('surfaceId', (err) => { + if (err) { + console.error('Failed to add deferredSurface. ${err.message}'); + return; + } + console.log('Callback returned with deferredSurface added.'); +}) +``` + +### addDeferredSurface + +addDeferredSurface(surfaceId: string): Promise + +Adds a surface after a **PreviewOutput** instance is created. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------------------------ | +| surfaceId | string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +previewOutput.addDeferredSurface('surfaceId').then(() => { + console.log('Promise returned with deferredSurface added.'); +}) +``` + +### start + +start(callback: AsyncCallback): void + +Starts to output preview streams. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +previewOutput.start((err) => { + if (err) { + console.error('Failed to start the previewOutput. ${err.message}'); + return; + } + console.log('Callback returned with previewOutput started.'); +}) +``` + +### start + +start(): Promise + +Starts to output preview streams. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +previewOutput.start().then(() => { + console.log('Promise returned with previewOutput started.'); +}) +``` + +### stop + +stop(callback: AsyncCallback): void + +Stops outputting preview streams. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +previewOutput.stop((err) => { + if (err) { + console.error('Failed to stop the previewOutput. ${err.message}'); + return; + } + console.log('Callback returned with previewOutput stoped.'); +}) +``` + +### stop + +stop(): Promise + +Stops outputting preview streams. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +previewOutput.stop().then(() => { + console.log('Callback returned with previewOutput stoped.'); +}) +``` + +### on('frameStart') on(type: 'frameStart', callback: AsyncCallback): void @@ -2013,8 +3582,8 @@ Listens for preview frame start events. This API uses an asynchronous callback t **Parameters** | Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameStart**, indicating the preview frame start event.| +| -------- | -------------------- | ---- | -------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **frameStart**, indicating the preview frame start event.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -2036,8 +3605,8 @@ Listens for preview frame end events. This API uses an asynchronous callback to **Parameters** | Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameEnd**, indicating the preview frame end event.| +| -------- | -------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **frameEnd**, indicating the preview frame end event.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -2059,8 +3628,8 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err **Parameters** | Name | Type | Mandatory| Description | -| :------- | :----------------------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the preview output error event.| +| -------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **error**, indicating the preview output error event.| | callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | **Example** @@ -2073,7 +3642,7 @@ previewOutput.on('error', (previewOutputError) => { ## PreviewOutputErrorCode -Enumerates the **PreviewOutput** error codes. +Enumerates the error codes used for preview output. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2081,203 +3650,450 @@ Enumerates the **PreviewOutput** error codes. | ------------- | ---- | ---------- | | ERROR_UNKNOWN | -1 | Unknown error.| -## PreviewOutputError +## PreviewOutputError -Defines a **PreviewOutput** error object. +Defines the preview output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------------- | ---------------------- | +| Name| Type | Description | +| ---- | ------------------------------------------------- | ------------------------- | | code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| -## camera.createPhotoOutput +## ImageRotation + +Enumerates the image rotation angles. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ------------ | ---- | --------------- | +| ROTATION_0 | 0 | The image rotates 0 degrees. | +| ROTATION_90 | 90 | The image rotates 90 degrees. | +| ROTATION_180 | 180 | The image rotates 180 degrees.| +| ROTATION_270 | 270 | The image rotates 270 degrees.| + +## Location + +Defines geolocation information. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------- | +| latitude | number | Yes | Latitude, in degree.| +| longitude | number | Yes | Longitude, in degree.| +| altitude | number | Yes | Altitude, in meter.| + +## QualityLevel + +Enumerates the image quality levels. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| -------------------- | ---- | -------------- | +| QUALITY_LEVEL_HIGH | 0 | High image quality. | +| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| +| QUALITY_LEVEL_LOW | 2 | Low image quality. | + + +## PhotoCaptureSetting + +Defines the settings for photo capture. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Type | Mandatory| Default Value | Description | +| -------- | ------------------------------- | ---- | ------------------ | ---------------------- | +| quality | [QualityLevel](#qualitylevel) | No | QUALITY_LEVEL_HIGH | Photo quality. | +| rotation | [ImageRotation](#imagerotation) | No | ROTATION_0 | Rotation angle of the photo. | +| location | [Location](#location) | No | (0,0,0) | Geolocation information of the photo. | +| mirror | boolean | No | false | Whether mirroring is enabled. By default, mirroring is disabled.| + +## PhotoOutput + +Implements output information used in a **CaptureSession**. + +### getDefaultCaptureSetting + +getDefaultCaptureSetting(callback: AsyncCallback): void + +Obtains the default shooting parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[PhotoCaptureSetting](#photocapturesetting)\> | Yes | Callback used to return the result.| + +**Example** + +```js +photoOutput.getDefaultCaptureSetting((err, photocapturesetting) => { + if (err) { + console.error('Failed to get the defaultCaptureSetting. ${err.message}'); + return; + } + console.log('Callback returned with an array of defaultCaptureSetting.'); +}) +``` + +### getDefaultCaptureSetting + +getDefaultCaptureSetting(): Promise + +Obtains the default shooting parameters. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------------- | --------------------------- | +| Promise<[PhotoCaptureSetting](#photocapturesetting)\> | Promise used to return the result.| + +**Example** + +```js +photoOutput.getDefaultCaptureSetting().then((photocapturesetting) => { + console.log('Callback returned with an array of defaultCaptureSetting.'); +}) +``` + +### capture + +capture(callback: AsyncCallback): void + +Captures a photo with the default shooting parameters. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +photoOutput.capture((err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` + +### capture -createPhotoOutput(surfaceId: string, callback: AsyncCallback): void +capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void -Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the instance. +Captures a photo with the specified shooting parameters. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | Yes | Surface ID received from **[ImageReceiver](js-apis-image.md#imagereceiver9)**. | -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------ | +| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} +photoOutput.capture(settings, (err) => { if (err) { - console.error('Failed to create the PhotoOutput instance. ${err.message}'); + console.error('Failed to capture the photo ${err.message}'); return; } - console.log('Callback returned with the PhotoOutput instance.'); + console.log('Callback invoked to indicate the photo capture request success.'); }); ``` -## camera.createPhotoOutput +### capture -createPhotoOutput(surfaceId: string): Promise +capture(setting?: PhotoCaptureSetting): Promise -Creates a **PhotoOutput** instance. This API uses a promise to return the instance. +Captures a photo with the specified shooting parameters. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | Yes | Surface ID received from **[ImageReceiver](js-apis-image.md#imagereceiver9)**. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | ---------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| **Return value** -| Type | Description | -| ------------------------------------- | -------------------------------------- | -| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + **Example** ```js -camera.createPhotoOutput("surfaceId").then((photoOutput) => { - console.log('Promise returned with PhotoOutput instance'); +photoOutput.capture().then(() => { + console.log('Promise returned to indicate that photo capture request success.'); }) ``` -## ImageRotation -Enumerates the image rotation angles. +### isMirrorSupported + +isMirrorSupported(callback: AsyncCallback): void + +Checks whether mirroring is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------ | ---- | --------------- | -| ROTATION_0 | 0 | The image rotates 0 degrees. | -| ROTATION_90 | 90 | The image rotates 90 degrees. | -| ROTATION_180 | 180 | The image rotates 180 degrees.| -| ROTATION_270 | 270 | The image rotates 270 degrees.| +**Parameters** -## QualityLevel +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite.| -Enumerates the image quality levels. +**Example** + +```js +captureSession.isMirrorSupported((err, isSupported) => { + if (err) { + console.error('Failed to check mirror is supported ${err.message}'); + return; + } + console.log('Callback returned with the successful execution of isMirrorSupported.'); +}) +``` + +### isMirrorSupported + +isMirrorSupported(): Promise + +Checks whether mirroring is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------- | ---- | -------------- | -| QUALITY_LEVEL_HIGH | 0 | High image quality. | -| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| -| QUALITY_LEVEL_LOW | 2 | Low image quality. | +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------- | +| Promise | Promise used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite.| + +**Example** + +```js +captureSession.isMirrorSupported().then((isSupported) => { + console.log('Promise returned with mirror supported: ' + isSupported); +}) +``` + +### on('captureStart') + +on(type: 'captureStart', callback: AsyncCallback): void + +Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **captureStart**, indicating the shooting start event.| +| callback | AsyncCallback | Yes | Callback used to return the capture ID. | + +**Example** + +```js +photoOutput.on('captureStart', (err, captureId) => { + console.log('photo capture stated, captureId : ' + captureId); +}) +``` + +### on('frameShutter') + +on(type: 'frameShutter', callback: AsyncCallback): void + +Listens for frame shutter events. This API uses an asynchronous callback to return the event information. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **frameShutter**, indicating the frame shutter event.| +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | + +**Example** + +```js +photoOutput.on('frameShutter', (err, frameShutterInfo) => { + console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); + console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +}) +``` + +### on('captureEnd') + +on(type: 'captureEnd', callback: AsyncCallback): void + +Listens for shooting end events. This API uses an asynchronous callback to return the event information. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ---------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **captureEnd**, indicating the shooting end event.| +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | + +**Example** + +```js +photoOutput.on('captureEnd', (err, captureEndInfo) => { + console.log('photo capture end, captureId : ' + captureEndInfo.captureId); + console.log('frameCount : ' + captureEndInfo.frameCount); +}) +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for **PhotoOutput** errors. This API uses a callback to return the errors. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ----------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **error**, indicating the photo output error event.| +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | + +**Example** + +```js +photoOutput.on('error', (err, photoOutputError) => { + console.log('Photo output error code: ' + photoOutputError.code); +}) +``` + +## FrameShutterInfo + +Defines the frame shutter information. + +**System capability**: SystemCapability.Multimedia.Camera.Core +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------ | +| captureId | number | Yes | ID of this capture action. | +| timestamp | number | Yes | Timestamp when the frame shutter event is triggered.| -## PhotoCaptureSetting +## CaptureEndInfo -Defines the settings for photo capture. +Defines the capture end information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | -------------- | -| quality | [QualityLevel](#qualitylevel) | No | Photo quality. | -| rotation | [ImageRotation](#imagerotation) | No | Rotation angle of the photo.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ---------- | +| captureId | number | Yes | ID of this capture action.| +| frameCount | number | Yes | Number of frames captured. | +## PhotoOutputErrorCode -## PhotoOutput +Enumerates the error codes used for photo output. -Implements photo output. +**System capability**: SystemCapability.Multimedia.Camera.Core -### capture +| Name | Value | Description | +| ---------------------------- | ---- | ------------------ | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| +| ERROR_INSUFFICIENT_RESOURCES | 1 | Insufficient resources. | +| ERROR_TIMEOUT | 2 | Timeout. | -capture(callback: AsyncCallback): void +## PhotoOutputError -Captures a photo. This API uses an asynchronous callback to return the result. +Defines a photo output error. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| -**Example** +## VideoOutput -```js -photoOutput.capture((err) => { - if (err) { - console.error('Failed to capture the photo ${err.message}'); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` +Implements output information used in a video recording session. -### capture +### start -capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void +start(callback: AsyncCallback): void -Captures a photo with the specified capture settings. This API uses an asynchronous callback to return the result. +Starts video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------ | -| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Photo capture settings. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 -} -photoOutput.capture(settings, (err) => { +videoOutput.start((err) => { if (err) { - console.error('Failed to capture the photo ${err.message}'); + console.error('Failed to start the video output ${err.message}'); return; } - console.log('Callback invoked to indicate the photo capture request success.'); + console.log('Callback invoked to indicate the video output start success.'); }); ``` -### capture +### start -capture(setting?: PhotoCaptureSetting): Promise +start(): Promise -Captures a photo with the specified capture settings. This API uses a promise to return the result. +Starts video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------- | ---- | ---------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Photo capture settings.| - **Return value** | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Promise| Promise used to return the result.| **Example** ```js -photoOutput.capture().then(() => { - console.log('Promise returned to indicate that photo capture request success.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that start method execution success.'); }) ``` -### release +### stop -release(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Releases this **PhotoOutput** instance. This API uses an asynchronous callback to return the result. +Stops video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2290,20 +4106,20 @@ Releases this **PhotoOutput** instance. This API uses an asynchronous callback t **Example** ```js -photoOutput.release((err) => { +videoOutput.stop((err) => { if (err) { - console.error('Failed to release the PhotoOutput instance ${err.message}'); + console.error('Failed to stop the video output ${err.message}'); return; } - console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); + console.log('Callback invoked to indicate the video output stop success.'); }); ``` -### release +### stop -release(): Promise +stop(): Promise -Releases this **PhotoOutput** instance. This API uses a promise to return the result. +Stops video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2311,315 +4127,290 @@ Releases this **PhotoOutput** instance. This API uses a promise to return the re | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise| Promise used to return the result.| **Example** ```js -photoOutput.release().then(() => { - console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); +videoOutput.stop().then(() => { + console.log('Promise returned to indicate that stop method execution success.'); }) ``` -### on('captureStart') +### on('frameStart') -on(type: 'captureStart', callback: AsyncCallback): void +on(type: 'frameStart', callback: AsyncCallback): void -Listens for photo capture start events. This API uses an asynchronous callback to return the capture ID. +Listens for video recording start events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------- | :--- | :----------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **captureStart**, indicating the photo capture start event.| -| callback | AsyncCallback | Yes | Callback used to return the capture ID. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **frameStart**, indicating the video recording start event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -photoOutput.on('captureStart', (err, captureId) => { - console.log('photo capture stated, captureId : ' + captureId); +videoOutput.on('frameStart', () => { + console.log('Video frame started'); }) ``` -### on('frameShutter') +### on('frameEnd') -on(type: 'frameShutter', callback: AsyncCallback): void +on(type: 'frameEnd', callback: AsyncCallback): void -Listens for frame shutter events. This API uses an asynchronous callback to return the event information. +Listens for video recording stop events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameShutter**, indicating the frame shutter event.| -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the video recording stop event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -photoOutput.on('frameShutter', (err, frameShutterInfo) => { - console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); - console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); +videoOutput.on('frameEnd', () => { + console.log('Video frame ended'); }) ``` -### on('captureEnd') +### on('error') -on(type: 'captureEnd', callback: AsyncCallback): void +on(type: 'error', callback: ErrorCallback): void -Listens for photo capture end events. This API uses an asynchronous callback to return the event information. +Listens for errors that occur during video recording. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------------------------ | :--- | :--------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **captureEnd**, indicating the photo capture end event.| -| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | --------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **error**, indicating the video output error event.| +| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | **Example** ```js -photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.log('photo capture end, captureId : ' + captureEndInfo.captureId); - console.log('frameCount : ' + captureEndInfo.frameCount); +videoOutput.on('error', (VideoOutputError) => { + console.log('Video output error code: ' + VideoOutputError.code); }) ``` -### on('error') - -on(type: 'error', callback: ErrorCallback): void +## VideoOutputErrorCode -Listens for **PhotoOutput** errors. This API uses a callback to return the errors. +Enumerates the error codes used for video recording. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| :------- | :---------------------------------------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the photo output error event.| -| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | - -**Example** - -```js -photoOutput.on('error', (err, photoOutputError) => { - console.log('Photo output error code: ' + photoOutputError.code); -}) -``` +| Name | Value | Description | +| ------------------ | ---- | ------------------ | +| ERROR_UNKNOWN | -1 | Unknown error. | +| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| -## FrameShutterInfo +## VideoOutputError -Defines the frame shutter information. +Defines a video output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ----------------------------- | -| captureId | number | Yes | ID of this capture action.| -| timestamp | number | Yes | Timestamp when the frame shutter event is triggered. | +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| -## CaptureEndInfo +## MetadataObjectType -Defines the capture end information. +Enumerates metadata streams. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ----------------------------- | -| captureId | number | Yes | ID of this capture action.| -| frameCount | number | Yes | Number of frames captured. | +| Name | Value | Description | +| -------------- | ---- | ------------------ | +| FACE_DETECTION | 0 | Metadata object type.| -## PhotoOutputErrorCode +## Rect -Enumerates the **PhotoOutput** error codes. +Defines a rectangle. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| - -## PhotoOutputError +| Name | Type | Description | +| -------- | ------ | --------------------- | +| topLeftX | number | X-axis coordinate of the upper left corner of the rectangle.| +| topLeftY | number | Y-axis coordinate of the upper left corner of the rectangle.| +| width | number | Width of the rectangle. | +| height | number | Height of the rectangle. | -Defines a **PhotoOutput** error object. +## MetadataObject -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| +Implements camera metadata, which is the data source of **[CameraInput](#camerainput)**. -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string, callback: AsyncCallback): void +getType(callback: AsyncCallback): void -Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the instance. +Obtains the metadata object type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------------------------- | ---- | ----------------------------------- | -| surfaceId | string | Yes | Surface ID received from **VideoRecorder**. | -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[MetadataObjectType](#metadataObjectType)\> | Yes | Callback used to return the result.| **Example** ```js -camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { +metadataObject.getType((err, metadataObjectType) => { if (err) { - console.error('Failed to create the VideoOutput instance. ${err.message}'); + console.error('Failed to get type. ${err.message}'); return; } - console.log('Callback returned with the VideoOutput instance'); -}); + console.log('Callback returned with an array of metadataObjectType.'); +}) ``` -## camera.createVideoOutput +### getType -createVideoOutput(surfaceId: string): Promise +getType(): Promise -Creates a **VideoOutput** instance. This API uses a promise to return the instance. +Obtains the metadata object type. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------------------------------- | -| surfaceId | string | Yes | Surface ID received from **VideoRecorder**.| - **Return value** -| Type | Description | -| ------------------------------------- | -------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance.| +| Type | Description | +| --------------------------------------------------- | --------------------------- | +| Promise<[MetadataObjectType](#metadataObjectType)\> | Promise used to return the result.| **Example** ```js -camera.createVideoOutput("surfaceId" -).then((videoOutput) => { - console.log('Promise returned with the VideoOutput instance'); +metadataObject.getType().then((metadataObjectType) => { + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -## VideoOutput - -Implements video output. - -### start +### getTimestamp -start(callback: AsyncCallback): void +getTimestamp(callback: AsyncCallback): void -Starts the video output. This API uses an asynchronous callback to return the result. +Obtains the metadata timestamp. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.start((err) => { +metadataObject.getTimestamp((err) => { if (err) { - console.error('Failed to start the video output ${err.message}'); + console.error('Failed to get timestamp. ${err.message}'); return; } - console.log('Callback invoked to indicate the video output start success.'); -}); + console.log('Callback returned with timestamp getted.'); +}) ``` -### start +### getTimestamp -start(): Promise +getTimestamp(): Promise -Starts the video output. This API uses a promise to return the result. +Obtains the metadata timestamp. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Type | Description | +| ----------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that start method execution success.'); +metadataObject.getTimestamp().then(() => { + console.log('Callback returned with timestamp getted.'); }) ``` -### stop +### getBoundingBox -stop(callback: AsyncCallback): void +getBoundingBox(callback: AsyncCallback): void -Stops the video output. This API uses an asynchronous callback to return the result. +Obtains the bounding box of metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| **Example** ```js -videoOutput.stop((err) => { +metadataObject.getBoundingBox((err, rect) => { if (err) { - console.error('Failed to stop the video output ${err.message}'); + console.error('Failed to get boundingBox. ${err.message}'); return; } - console.log('Callback invoked to indicate the video output stop success.'); -}); + console.log('Callback returned with boundingBox getted.'); +}) ``` -### stop +### getBoundingBox -stop(): Promise +getBoundingBox(): Promise -Stops the video output. This API uses a promise to return the result. +Obtains the bounding box of metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ----------------------- | --------------------------- | +| Promise<[Rect](#rect)\> | Promise used to return the result.| **Example** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that stop method execution success.'); +metadataObject.getBoundingBox().then((rect) => { + console.log('Callback returned with boundingBox getted.'); }) ``` -### release +## MetadataFaceObject -release(callback: AsyncCallback): void +Implements the face object of metadata. It inherits **[MetadataObject](#metadataobject)**. + +## MetadataOutput + +Implements metadata stream. It inherits **[CameraOutput](#cameraoutput)**. + +### start + +start(callback: AsyncCallback): void -Releases this **VideoOutput** instance. This API uses an asynchronous callback to return the result. +Starts to output metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2632,20 +4423,20 @@ Releases this **VideoOutput** instance. This API uses an asynchronous callback t **Example** ```js -videoOutput.release((err) => { +metadataOutput.start((err) => { if (err) { - console.error('Failed to release the VideoOutput instance ${err.message}'); + console.error('Failed to start metadataOutput. ${err.message}'); return; } - console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); -}); + console.log('Callback returned with metadataOutput started.'); +}) ``` -### release +### start -release(): Promise +start(): Promise -Releases this **VideoOutput** instance. This API uses a promise to return the result. +Starts to output metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2653,102 +4444,127 @@ Releases this **VideoOutput** instance. This API uses a promise to return the re | Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise| Promise used to return the result.| **Example** ```js -videoOutput.release().then(() => { - console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); +metadataOutput.start().then(() => { + console.log('Callback returned with metadataOutput started.'); }) ``` -### on('frameStart') +### stop -on(type: 'frameStart', callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Listens for video frame start events. This API uses an asynchronous callback to return the event information. +Stops outputting metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :----------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameStart**, indicating the video frame start event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.on('frameStart', () => { - console.log('Video frame started'); +metadataOutput.stop((err) => { + if (err) { + console.error('Failed to stop the metadataOutput. ${err.message}'); + return; + } + console.log('Callback returned with metadataOutput stoped.'); }) ``` -### on('frameEnd') +### stop -on(type: 'frameEnd', callback: AsyncCallback): void +stop(): Promise + +Stops outputting metadata. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +metadataOutput.stop().then(() => { + console.log('Callback returned with metadataOutput stoped.'); +}) +``` -Listens for video frame end events. This API uses an asynchronous callback to return the event information. +### on('metadataObjectsAvailable') + +on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void + +Listens for metadata objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :--------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **frameEnd**, indicating the video frame end event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| +| callback | Callback\> | Yes | Callback used to return the error information. | **Example** ```js -videoOutput.on('frameEnd', () => { - console.log('Video frame ended'); +metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { + console.log('metadata output error code: ' + metadataObject.code); }) ``` ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(tuype: 'error', callback: ErrorCallback): void -Listens for **VideoOutput** errors. This API uses a callback to return the errors. +Listens for metadata errors. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------------------------------- | :--- | :-------------------------------------------- | -| type | string | Yes | Type of event to listen for. The value is fixed at **error**, indicating the video output error event.| -| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | --------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| +| callback | Callback<[MetadataOutputError](#metadataOutputError)\> | Yes | Callback used to return the error information. | **Example** ```js -videoOutput.on('error', (VideoOutputError) => { - console.log('Video output error code: ' + VideoOutputError.code); +metadataOutput.on('error', (metadataOutputError) => { + console.log('Metadata output error code: ' + metadataOutputError.code); }) ``` -## VideoOutputErrorCode +## MetadataOutputErrorCode -Enumerates the **VideoOutput** error codes. +Enumerates the error codes used for metadata output. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| +| Name | Value | Description | +| ---------------------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| -## VideoOutputError +## MetadataOutputError -Defines a **VideoOutput** error object. +Defines a metadata output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| +| Name| Type | Description | +| ---- | --------------------------------------------------- | -------------------------- | +| code | [MetadataOutputErrorCode](#MetadataOutputErrorCode) | **MetadataOutput** error code.| diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50c4228a23727b230a2ffab82dcf077be5f6682b..7ba00ae8710ffb3a313d9bc337dc705c9cb60ff0 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -136,6 +136,8 @@ | COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | | COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | | COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | | COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | | COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | | COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 6adaa00f48cfb7f2e685841e013e3d719bc58548..f6702d14d391a025bf9a16f2d8bf79a97772ed0a 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,10 +1,12 @@ # Data Share Result Set -The **DataShareResultSet** module provides methods for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. +The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. ## Modules to Import @@ -13,7 +15,7 @@ The **DataShareResultSet** module provides methods for accessing the result set import DataShareResultSet from '@ohos.data.DataShareResultSet'; ``` -## How to Use +## Usage You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShareResultSet** object. @@ -44,7 +46,10 @@ dataShareHelper.query(uri, da, columns).then((data) => { }); ``` -## Attributes +## DataShareResultSet +Provides methods for accessing the result sets generated by querying the database. + +### Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -55,7 +60,7 @@ dataShareHelper.query(uri, da, columns).then((data) => { | rowCount | number | Yes | Number of rows in the result set. | | isClosed | boolean | Yes | Whether the result set is closed.| -## goToFirstRow +### goToFirstRow goToFirstRow(): boolean @@ -76,7 +81,7 @@ let isGoTOFirstRow = resultSet.goToFirstRow(); console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow); ``` -## goToLastRow +### goToLastRow goToLastRow(): boolean @@ -97,7 +102,7 @@ let isGoToLastRow = resultSet.goToLastRow(); console.info('resultSet.goToLastRow: ' + isGoToLastRow); ``` -## goToNextRow +### goToNextRow goToNextRow(): boolean @@ -118,7 +123,7 @@ let isGoToNextRow = resultSet.goToNextRow(); console.info('resultSet.goToNextRow: ' + isGoToNextRow); ``` -## goToPreviousRow +### goToPreviousRow goToPreviousRow(): boolean @@ -139,7 +144,7 @@ let isGoToPreviousRow = resultSet.goToPreviousRow(); console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow); ``` -## goTo +### goTo goTo(offset:number): boolean @@ -167,7 +172,7 @@ let isGoTo = resultSet.goTo(goToNum); console.info('resultSet.goTo: ' + isGoTo); ``` -## goToRow +### goToRow goToRow(position: number): boolean @@ -179,7 +184,7 @@ Moves to the specified row in the result set. | **Name**| **Type**| **Mandatory**| Description | | ---------- | -------- | -------- | ------------------------ | -| position | number | Yes | Destination position to move.| +| position | number | Yes | Destination position to move to.| **Return value** @@ -195,11 +200,11 @@ let isGoToRow = resultSet.goToRow(goToRowNum); console.info('resultSet.goToRow: ' + isGoToRow); ``` -## getBlob +### getBlob getBlob(columnIndex: number): Uint8Array -Obtains the value in the specified column in the current row as a byte array. +Obtains the value in the form of a byte array based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -224,11 +229,11 @@ let getBlob = resultSet.getBlob(columnIndex); console.info('resultSet.getBlob: ' + getBlob); ``` -## getString +### getString getString(columnIndex: number): *string* -Obtains the value in the specified column in the current row as a string. +Obtains the value in the form of a string based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -253,11 +258,11 @@ let getString = resultSet.getString(columnIndex); console.info('resultSet.getString: ' + getString); ``` -## getLong +### getLong getLong(columnIndex: number): number -Obtains the value in the specified column in the current row as a long integer. +Obtains the value in the form of a long integer based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -282,11 +287,11 @@ let getLong = resultSet.getLong(columnIndex); console.info('resultSet.getLong: ' + getLong); ``` -## getDouble +### getDouble getDouble(columnIndex: number): number -Obtains the value in the specified column in the current row as a double-precision floating-point number. +Obtains the value in the form of a double-precision floating-point number based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -311,7 +316,7 @@ let getDouble = resultSet.getDouble(columnIndex); console.info('resultSet.getDouble: ' + getDouble); ``` -## close +### close close(): void @@ -325,7 +330,7 @@ Closes this result set. resultSet.close(); ``` -## getColumnIndex +### getColumnIndex getColumnIndex(columnName: string): number @@ -353,7 +358,7 @@ let getColumnIndex = resultSet.getColumnIndex(ColumnName) console.info('resultSet.getColumnIndex: ' + getColumnIndex); ``` -## getColumnName +### getColumnName getColumnName(columnIndex: number): *string* @@ -381,7 +386,7 @@ let getColumnName = resultSet.getColumnName(columnIndex) console.info('resultSet.getColumnName: ' + getColumnName); ``` -## getDataType +### getDataType getDataType(columnIndex: number): DataType diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 16c1c1c7b622782a577719bae992d10b1f4634a0..2f54d7d7c47b10403fbc96edf92ce1d55cdcb41b 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,10 +1,12 @@ # Data Share Predicates -You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data with **DataShare**. +You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. ## Modules to Import @@ -13,11 +15,14 @@ You can use **DataSharePredicates** to specify conditions for [updating](js-apis import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -## equalTo +## DataSharePredicates +Provides methods for setting different **DataSharePredicates** objects. + +### equalTo equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -34,7 +39,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -43,11 +48,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose") ``` -## notEqualTo +### notEqualTo notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value not equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -64,7 +69,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -73,11 +78,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notEqualTo("NAME", "Rose") ``` -## beginWrap +### beginWrap beginWrap(): DataSharePredicates -Adds a left parenthesis to this **DataSharePredicates**. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a left parenthesis to this **DataSharePredicates**. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -99,11 +106,13 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## endWrap +### endWrap endWrap(): DataSharePredicates -Adds a right parenthesis to this **DataSharePredicates** object. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a right parenthesis to this **DataSharePredicates** object. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -125,7 +134,7 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## or +### or or(): DataSharePredicates @@ -150,7 +159,7 @@ predicates.equalTo("NAME", "lisi") .equalTo("NAME", "Rose") ``` -## and +### and and(): DataSharePredicates @@ -175,11 +184,13 @@ predicates.equalTo("NAME", "lisi") .equalTo("SALARY", 200.5) ``` -## contains +### contains contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the string that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that contains the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -188,13 +199,13 @@ Sets a **DataSharePredicates** object to match the string that contains the spec | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value contained in the string.| +| value | string | Yes | Value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -203,11 +214,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.contains("NAME", "os") ``` -## beginsWith +### beginsWith beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that starts with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that begins with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -216,13 +229,13 @@ Sets a **DataSharePredicates** object to match a string that starts with the spe | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Start value of the string.| +| value | string | Yes | Start value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -231,11 +244,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.beginsWith("NAME", "os") ``` -## endsWith +### endsWith endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that ends with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -244,13 +259,13 @@ Sets a **DataSharePredicates** object to match a string that ends with the speci | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | End value of the string.| +| value | string | Yes | End value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -259,11 +274,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.endsWith("NAME", "os") ``` -## isNull +### isNull isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is null. +Sets a **DataSharePredicates** object to match the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -279,7 +294,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -288,11 +303,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNull("NAME") ``` -## isNotNull +### isNotNull isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is not null. +Sets a **DataSharePredicates** object to match the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -308,7 +323,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -317,11 +332,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNotNull("NAME") ``` -## like +### like like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -338,7 +353,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -347,11 +362,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.like("NAME", "%os%") ``` -## unlike +### unlike unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is not similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is not not similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -368,7 +383,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -377,11 +392,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.unlike("NAME", "%os%") ``` -## glob +### glob glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the specified string. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the specified string. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -396,7 +413,7 @@ Sets a **DataSharePredicates** object to match the specified string. Currently, | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified string.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -405,11 +422,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.glob("NAME", "?h*g") ``` -## between +### between between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value within the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is within the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -425,7 +444,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -434,11 +453,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.between("AGE", 10, 50) ``` -## notBetween +### notBetween notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value out of the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is out of the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -454,7 +475,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -463,11 +484,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notBetween("AGE", 10, 50) ``` -## greaterThan +### greaterThan greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -484,7 +505,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -493,11 +514,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThan("AGE", 10) ``` -## lessThan +### lessThan lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than the specified value. +Sets a **DataSharePredicates** object to match the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -514,7 +535,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -523,11 +544,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThan("AGE", 50) ``` -## greaterThanOrEqualTo +### greaterThanOrEqualTo greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -544,7 +565,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -553,11 +574,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThanOrEqualTo("AGE", 10) ``` -## lessThanOrEqualTo +### lessThanOrEqualTo lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -574,7 +595,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -583,11 +604,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThanOrEqualTo("AGE", 50) ``` -## orderByAsc +### orderByAsc orderByAsc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in ascending order. +Sets a **DataSharePredicates** object that sorts data in ascending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -603,7 +624,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -612,11 +633,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByAsc("AGE") ``` -## orderByDesc +### orderByDesc orderByDesc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in descending order. +Sets a **DataSharePredicates** object that sorts data in descending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -632,7 +653,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -641,11 +662,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByDesc("AGE") ``` -## distinct +### distinct distinct(): DataSharePredicates -Sets a **DataSharePredicates** object to filter out duplicate records. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to filter out duplicate data records. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -653,7 +676,7 @@ Sets a **DataSharePredicates** object to filter out duplicate records. Currently | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -662,7 +685,7 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").distinct() ``` -## limit +### limit limit(total: number, offset: number): DataSharePredicates @@ -683,7 +706,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -692,11 +715,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").limit(10, 3) ``` -## groupBy +### groupBy groupBy(fields: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to group the records according to the specified parameters. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object group the records according to the specified fields. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -704,13 +729,13 @@ Sets a **DataSharePredicates** object to group the records according to the spec | Name| Type | Mandatory| Description | | ------ | ------------- | ---- | -------------------- | -| fields | Array<string> | Yes | Names of the columns to group.| +| fields | Array<string> | Yes | Names of the columns by which the records are grouped.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -719,11 +744,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.groupBy(["AGE", "NAME"]) ``` -## indexedBy +### indexedBy indexedBy(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to specify the index column. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to list data by the specified index. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -737,7 +764,7 @@ Sets a **DataSharePredicates** object to specify the index column. Currently, on | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -746,11 +773,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.indexedBy("SALARY_INDEX") ``` -## in +### in in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value within the specified range. +Sets a **DataSharePredicates** object to match the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -761,13 +788,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -776,11 +803,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.in("AGE", [18, 20]) ``` -## notIn +### notIn notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value out of the specified range. +Sets a **DataSharePredicates** object to match the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -791,13 +818,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -806,11 +833,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notIn("NAME", ["Lisa", "Rose"]) ``` -## prefixKey +### prefixKey prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a field with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data with the specified key prefix. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -824,7 +853,7 @@ Sets a **DataSharePredicates** object to match a field with the specified key pr | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -833,11 +862,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.prefixKey("NAME") ``` -## inKeys +### inKeys inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to match the fields whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data whose keys are within the given range. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -851,7 +882,7 @@ Sets a **DataSharePredicates** object to match the fields whose keys are within | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 83875a6edb8aa2395b8750e70fb86b7fa596b03d..6f24aa3255f0340e0ad8ef248ae25d62092e0774 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,6 +1,6 @@ # Distributed Data Object -The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. +The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. > **NOTE**
> @@ -307,7 +307,7 @@ g_object.save("local").then((result)=>{ ### revokeSave9+ -revokeSave(callback: AsyncCallback<SaveSuccessResponse>): void +revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void Revokes the saving operation of a distributed data object. This API uses an asynchronous callback to return the result. @@ -334,7 +334,7 @@ g_object.revokeSave((result, data) =>{ ### revokeSave9+ -revokeSave(): Promise<SaveSuccessResponse> +revokeSave(): Promise<RevokeSaveSuccessResponse> Revokes the saving operation of a distributed data object. This API uses a promise to return the result. diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 38c07d6247487e037e9158a00e5c2f752621b44e..adf54efbe8e95058c353a049211cec7c20e72ae3 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -85,7 +85,7 @@ promise.then(async (rdbStore) => { deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void -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. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -211,7 +211,7 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -238,7 +238,7 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -362,7 +362,7 @@ predicates.equalTo("NAME", "Lisa") contains(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string containing the specified value. +Sets an **RdbPredicates** to match a string containing the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -389,7 +389,7 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that starts with the specified value. +Sets an **RdbPredicates** to match a string that starts with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -416,7 +416,7 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that ends with the specified value. +Sets an **RdbPredicates** to match a string that ends with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -443,7 +443,7 @@ predicates.endsWith("NAME", "se") isNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is null. +Sets an **RdbPredicates** to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -469,7 +469,7 @@ predicates.isNull("NAME") isNotNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is not null. +Sets an **RdbPredicates** to match the field whose value is not null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -495,7 +495,7 @@ predicates.isNotNull("NAME") like(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that is similar to the specified value. +Sets an **RdbPredicates** to match a string that is similar to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -522,7 +522,7 @@ predicates.like("NAME", "%os%") glob(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match the specified string. +Sets an **RdbPredicates** to match the specified string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -549,7 +549,7 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -577,7 +577,7 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -604,7 +604,7 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -631,7 +631,7 @@ predicates.greaterThan("AGE", 18) lessThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -659,7 +659,7 @@ predicates.lessThan("AGE", 20) greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -687,7 +687,7 @@ predicates.greaterThanOrEqualTo("AGE", 18) lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -715,7 +715,7 @@ predicates.lessThanOrEqualTo("AGE", 20) orderByAsc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in ascending order. +Sets an **RdbPredicates** to match the column with values sorted in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -742,7 +742,7 @@ predicates.orderByAsc("NAME") orderByDesc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in descending order. +Sets an **RdbPredicates** to match the column with values sorted in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -768,7 +768,7 @@ predicates.orderByDesc("AGE") distinct(): RdbPredicates -Sets the **RdbPredicates** to filter out duplicate records. +Sets an **RdbPredicates** to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -789,7 +789,7 @@ predicates.equalTo("NAME", "Rose").distinct("NAME") limitAs(value: number): RdbPredicates -Sets the **RdbPredicates** to specify the maximum number of records. +Sets an **RdbPredicates** to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -815,7 +815,7 @@ predicates.equalTo("NAME", "Rose").limitAs(3) offsetAs(rowOffset: number): RdbPredicates -Sets the **RdbPredicates** to specify the start position of the returned result. +Sets an **RdbPredicates** to specify the start position of the returned result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -841,7 +841,7 @@ predicates.equalTo("NAME", "Rose").offsetAs(3) groupBy(fields: Array<string>): RdbPredicates -Sets the **RdbPredicates** to group rows that have the same value into summary rows. +Sets an **RdbPredicates** to group rows that have the same value into summary rows. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -866,7 +866,7 @@ predicates.groupBy(["AGE", "NAME"]) indexedBy(field: string): RdbPredicates -Sets the **RdbPredicates** object to specify the index column. +Sets an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -893,7 +893,7 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -921,7 +921,7 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -972,12 +972,12 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; } - console.log("Inserted first row: " + ret) + console.log("Inserted data, rowId = " + rowId); }) ``` @@ -1010,19 +1010,113 @@ const valueBucket = { "CODES": new Uint8Array([1, 2, 3, 4, 5]), } let promise = rdbStore.insert("EMPLOYEE", valueBucket) -promise.then(async (ret) => { - console.log("Inserted first row: " + ret) -}).catch((err) => { - console.log("Failed to insert data, err: " + err) +promise.then((rowId) => { + console.log("Inserted data, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); }) ``` +### batchInsert9+ + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into 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 target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("bathInsert failed, status = " + status); + return; + } + console.log("bathInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert9+ + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +Batch inserts data into 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 target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("bathInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("bathInsert failed, status = " + status); +}) +``` ### update update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void -Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. +Updates data based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1057,7 +1151,7 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> -Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1093,7 +1187,7 @@ promise.then(async (ret) => { ### update9+ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +Updates data based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1128,7 +1222,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. +Updates data based on the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1287,7 +1381,7 @@ promise.then((rows) => { query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in 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. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1317,7 +1411,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in 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 a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1330,7 +1424,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro **Return value** | Type| Description| | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** ```js @@ -1349,7 +1443,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in 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. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1362,6 +1456,7 @@ Queries data in the RDB store based on specified conditions. This API uses an as | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() @@ -1380,7 +1475,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in 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 a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1392,6 +1487,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** + | Type| Description| | -------- | -------- | | Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| @@ -1410,11 +1506,81 @@ promise.then((resultSet) => { }) ``` +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +Queries data from the RDB store of a remote device 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| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Network ID of the remote device.| +| table | string | Yes| Name of the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions for querying data.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new rdb.RdbPredicates('EPLOYEE') +predicates.greaterThan("id", 0) +rdbStore.remoteQuery("deviceId", "EPLOYEE", predicates, function(err, resultSet){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Network ID of the remote device.| +| table | string | Yes| Name of the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions for querying data.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------------- | +| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new rdb.RdbPredicates('EPLOYEE') +predicates.greaterThan("id", 0) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store using the specified SQL statement. This API uses an asynchronous callback to return the result. +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1442,7 +1608,7 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> -Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result. +Queries data using the specified SQL statement. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1455,7 +1621,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a **Return value** | Type| Description| | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** ```js @@ -1473,7 +1639,7 @@ promise.then((resultSet) => { executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses an asynchronous callback to return the result. +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 @@ -1481,8 +1647,8 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| +| callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```js @@ -1501,7 +1667,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses a promise to return the execution result. +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1509,12 +1675,12 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```js @@ -1544,13 +1710,7 @@ const valueBucket = { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1573,13 +1733,7 @@ const valueBucket = { "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1603,13 +1757,7 @@ try { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } - rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) - }) + await rdbStore.insert("test", valueBucket) rdbStore.commit() } catch (e) { rdbStore.rollBack() @@ -1673,7 +1821,7 @@ promiseBackup.then(()=>{ restore(srcName:string, callback: AsyncCallback<void>):void -Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result. +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1698,7 +1846,7 @@ rdbStore.restore("dbBackup.db", function(err) { restore(srcName:string): Promise<void> -Restores an RDB store using a backup file. This API uses a promise to return the result. +Restores an RDB store from a backup file. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1726,7 +1874,7 @@ promiseRestore.then(()=>{ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void -Sets a list of distributed tables. This API uses an asynchronous callback to return the result. +Sets distributed tables. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1747,14 +1895,14 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { } console.info('Set distributed tables successfully.') }) - ``` +``` ### setDistributedTables8+ setDistributedTables(tables: Array<string>): Promise<void> -Sets a list of distributed tables. This API uses a promise to return the result. +Sets distributed tables. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1784,7 +1932,7 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1813,7 +1961,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, obtainDistributedTableName(device: string, table: string): Promise<string> -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a promise to return the result. +Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1947,7 +2095,7 @@ try { off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void -Deletes the specified observer of the RDB store. This API uses a callback to return the result. +Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 25cf9ed242f66a0983303065dcea527989444223..372e6feb7c832d873bd98ed238d5cf474df10a5d 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -174,6 +174,42 @@ Obtains all display objects. This API uses a promise to return the result. }); ``` +## display.hasPrivateWindow9+ + +hasPrivateWindow(displayId: number): boolean + +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling **[setPrivacyMode](js-apis-window.md#setprivacymode7)**. The content in the privacy window cannot be captured or recorded. + +This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- |----------| +| id | number | Yes | ID of the display.| + +**Return value** + +| Type | Description | +| -------------------------------- |-----------------------------------------------------------------------| +|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| + +**Example** + + ```js + var ret = display.hasPrivateWindow(displayClass.id); + if (ret == undefined) { + console.log("HasPrivateWindow undefined."); + } + if (ret) { + console.log("HasPrivateWindow."); + } else if (!ret) { + console.log("Don't HasPrivateWindow."); + } + ``` + ## display.on('add'|'remove'|'change') on(type: 'add'|'remove'|'change', callback: Callback<number>): void diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 7d094be2e3b6a425e1c8b0eea194cb1085fd3505..46b962bb7e0dfbb16ea2ef4ba6a0bf2ac37ec5e0 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -19,8 +19,6 @@ getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. -**System capability**: SystemCapability.Account.OsAccount - - Return value | Type| Description| | -------- | -------- | @@ -43,7 +41,7 @@ Obtains distributed account information. This API uses an asynchronous callback **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - Parameters | Name| Type| Mandatory| Description| @@ -68,7 +66,7 @@ Obtains distributed account information. This API uses a promise to return the r **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - Return value | Type| Description| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data .md b/en/application-dev/reference/apis/js-apis-distributed-data .md deleted file mode 100644 index 5682921badad9367817fd3e421b1afb823970425..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-distributed-data .md +++ /dev/null @@ -1,5671 +0,0 @@ -# Distributed Data Management - -The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. - -This module provides the following functions: - -- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. -- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. -- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates. -- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. -- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. -- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. - ->**NOTE**
-> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import distributedData from '@ohos.data.distributedData'; -``` - - -## distributedData.createKVManager - -createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void - -Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| - -**Example** - -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA model: -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## distributedData.createKVManager - -createKVManager(config: KVManagerConfig): Promise<KVManager> - -Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| - -**Example** - -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA model: -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## KVManagerConfig - -Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| userInfo | [UserInfo](#userinfo) | Yes | User information.| -| bundleName | string | Yes | Bundle name.| - -## UserInfo - -Defines user information. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| userId | string | Yes | User ID.| -| userType | [UserType](#usertype) | Yes | User type.| - - -## UserType - -Enumerates the user types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Value| Description| -| ----- | ------ | ------ | -| SAME_USER_ID | 0 | User who logs in to different devices using the same account.| - - -## KVManager - -Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object. - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void - -Creates and obtains a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| options | [Options](#options) | Yes | Configuration of the KV store.| -| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options, function (err, store) { - if (err) { - console.log("getKVStore err: " + JSON.stringify(err)); - return; - } - console.log("getKVStore success"); - kvStore = store; - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> - -Creates and obtains a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ---------------------- | ---- | -------------------- | -| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| options | [Options](#options) | Yes | Configuration of the KV store.| - - -**Return value** - -| Type | Description | -| -------------------------------------- | ------------------------ | -| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options).then((store) => { - console.log("getKVStore success"); - kvStore = store; - }).catch((err) => { - console.log("getKVStore err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void - -Closes a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - - -| Name | Type | Mandatory| Description | -| ------- | ----------------- | ---- | --------------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -let kvStore; -let kvManager; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); - }); -} catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> - -Closes a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise\ | Promise that returns no value.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} - try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { - console.log('closeKVStore success'); - }).catch((err) => { - console.log('closeKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); - }); - } catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void - -Deletes a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('store', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId', function (err, data) { - console.log('deleteKVStore success'); - }); - }); -} catch (e) { - console.log('DeleteKVStore e ' + e); -} -``` - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string): Promise<void> - -Deletes a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| - - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('deleteKVStore success'); - }).catch((err) => { - console.log('deleteKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('getKVStore err ' + JSON.stringify(err)); - }); -} catch (e) { - console.log('deleteKVStore e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. | - -**Example** - -```js -let kvManager; -try { - kvManager.getAllKVStoreId('appId', function (err, data) { - console.log('GetAllKVStoreId success'); - console.log('GetAllKVStoreId size = ' + data.length); - }); -} catch (e) { - console.log('GetAllKVStoreId e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string): Promise<string[]> - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | - - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise<string[]>| Promise used to return the KV store IDs obtained.| - -**Example** - -```js -let kvManager; -try { - console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('appId').then((data) => { - console.log('getAllKVStoreId success'); - console.log('size = ' + data.length); - }).catch((err) => { - console.log('getAllKVStoreId err ' + JSON.stringify(err)); - }); -} catch(e) { - console.log('getAllKVStoreId e ' + e); -} -``` - - -### on('distributedDataServiceDie')8+ ### - -on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void - -Subscribes to service status changes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| - -**Example** - -```js -let kvManager; -try { - - console.log('KVManagerOn'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.on('distributedDataServiceDie', deathCallback); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### off('distributedDataServiceDie')8+ ### - -off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void - -Unsubscribes from the service status changes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | No | Callback used to return service status changes.| - - -**Example** - -```js -let kvManager; -try { - console.log('KVManagerOff'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.off('distributedDataServiceDie', deathCallback); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} - -``` - -## Options - -Provides KV store configuration. - - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | -| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| -| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## KVStoreType - -Enumerates the KV store types. - - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| -| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## SecurityLevel - -Enumerates the KV store security levels. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public.| -| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| -| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| -| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| -| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| - - -## Constants - -Defines the KV store constants. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | -| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. | -| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.| -| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | -| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| -| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| - -## Schema8+ ## - -Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -| Name | Type| Description | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | JSON root object.| -| indexes8+ | Array\ | String array in JSON format. | -| mode8+ | number | Schema mode. | -| skip8+ | number | Size of a skip of the schema. | - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -## FieldNode8+ ## - -Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -| Name | Type| Description | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | Whether the database field can be null. | -| default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value of the data type corresponding to the specified node.| - -### constructor8+ ### - -constructor(name: string) - -A constructor used to create a **FieldNode** instance with a string field. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | --------------- | -| name | string | Yes | Value of **FieldNode**.| - -### appendChild8+ ### - -appendChild(child: FieldNode): boolean - -Appends a child node to this **FieldNode**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| child | [FieldNode](#fieldnode8) | Yes | Child node to append. | - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -import ddm from '@ohos.data.distributedData'; -try { - let node = new ddm.FieldNode("root"); - let child1 = new ddm.FieldNode("child1"); - let child2 = new ddm.FieldNode("child2"); - let child3 = new ddm.FieldNode("child3"); - node.appendChild(child1); - node.appendChild(child2); - node.appendChild(child3); - console.log("appendNode " + JSON.stringify(node)); - child1 = null; - child2 = null; - child3 = null; - node = null; -} catch (e) { - console.log("AppendChild " + e); -} -``` - - -## KvStoreResultSet8+ ## - -Provides methods to obtain the KV store result sets, and query and move the data read position. - -Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - - -### getCount8+ ### - -getCount(): number - -Obtains the total number of rows in the result set. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| number |Total number of rows obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const count = resultSet.getCount(); - console.log("getCount succeed:" + count); -} catch (e) { - console.log("getCount failed: " + e); -} -``` - -### getPosition8+ ### - -getPosition(): number - -Obtains the current data read position (position from which data is read) in the result set. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| number |Current data read position obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeeded.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const position = resultSet.getPosition(); - console.log("getPosition succeed:" + position); -} catch (e) { - console.log("getPosition failed: " + e); -} -``` - - -### moveToFirst8+ ### - -moveToFirst(): boolean - -Moves the data read position to the first row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved1 = resultSet.moveToFirst(); - console.log("moveToFirst succeed: " + moved1); -} catch (e) { - console.log("moveToFirst failed " + e); -} -``` - - -### moveToLast8+ ### - -moveToLast(): boolean - -Moves the data read position to the last row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved2 = resultSet.moveToLast(); - console.log("moveToLast succeed:" + moved2); -} catch (e) { - console.log("moveToLast failed: " + e); -} -``` - - -### moveToNext8+ ### - -moveToNext(): boolean - -Moves the data read position to the next row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved3 = resultSet.moveToNext(); - console.log("moveToNext succeed: " + moved3); -} catch (e) { - console.log("moveToNext failed: " + e); -} -``` - - -### moveToPrevious8+ ### - -moveToPrevious(): boolean - -Moves the data read position to the previous row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved4 = resultSet.moveToPrevious(); - console.log("moveToPrevious succeed:" + moved4); -} catch (e) { - console.log("moveToPrevious failed: " + e); -} -``` - - -### move8+ ### - -move(offset: number): boolean - -Moves the data read position with the specified offset from the current position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward. | - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved5 = resultSet.move(); - console.log("move succeed:" + moved5); -} catch (e) { - console.log("move failed: " + e); -} -``` - - -### moveToPosition8+ ### - -moveToPosition(position: number): boolean - -Moves the data read position from 0 to an absolute position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| position | number | Yes |Absolute position to move to. | - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved6 = resultSet.moveToPosition(); - console.log("moveToPosition succeed: " + moved6); -} catch (e) { - console.log("moveToPosition failed: " + e); -} -``` - - -### isFirst8+ ### - -isFirst(): boolean - -Checks whether the data read position is the first row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the first row is being read; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isfirst = resultSet.isFirst(); - console.log("Check isFirst succeed:" + isfirst); -} catch (e) { - console.log("Check isFirst failed: " + e); -} -``` - - -### isLast8+ ### - -isLast(): boolean - -Checks whether the data read position is the last row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the last row is being read; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const islast = resultSet.isLast(); - console.log("Check isLast succeed: " + islast); -} catch (e) { - console.log("Check isLast failed: " + e); -} -``` - -### isBeforeFirst8+ ### - -isBeforeFirst(): boolean - -Checks whether the data read position is before the first row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isbeforefirst = resultSet.isBeforeFirst(); - console.log("Check isBeforeFirst succeed: " + isbeforefirst); -} catch (e) { - console.log("Check isBeforeFirst failed: " + e); -} -``` - - -### isAfterLast8+ ### - -isAfterLast(): boolean - -Checks whether the data read position is after the last row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isafterlast = resultSet.isAfterLast(); - console.log("Check isAfterLast succeed:" + isafterlast); -} catch (e) { - console.log("Check isAfterLast failed: " + e); -} -``` - - -### getEntry8+ ### - -getEntry(): Entry - -Obtains the KV pair from the current position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Entry](#entry) |KV pair obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const entry = resultSet.getEntry(); - console.log("getEntry succeed:" + JSON.stringify(entry)); -} catch (e) { - console.log("getEntry failed: " + e); -} -``` - - -## Query8+ ## - -Provides methods to create a **Query** object, which defines different data query criteria. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -### reset8+ ### - -reset(): Query - -Resets the **Query** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object reset.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.equalTo("key", "value"); - console.log("query is " + query.getSqlLike()); - query.reset(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("simply calls should be ok :" + e); -} -``` - - -### equalTo8+ ### - -equalTo(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is equal to the given value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.equalTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notEqualTo8+ ### - -notEqualTo(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is not equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThan8+ ### - -greaterThan(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is greater than the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThan8+ ### - -lessThan(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is less than the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThanOrEqualTo8+ ### - -greaterThanOrEqualTo(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThanOrEqualTo8+ ### - -lessThanOrEqualTo(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNull8+ ### - -isNull(field: string): Query - -Creates a **Query** object to match the specified field whose value is **null**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inNumber8+ ### - -inNumber(field: string, valueList: number[]): Query - -Creates a **Query** object to match the specified field whose value is within the specified list of numbers. - - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inString8+ ### - -inString(field: string, valueList: string[]): Query - -Creates a **Query** object to match the specified field whose value is within the specified list of strings. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInNumber8+ ### - -notInNumber(field: string, valueList: number[]): Query - -Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInString8+ ### - -notInString(field: string, valueList: string[]): Query - -Creates a **Query** object to match the specified field whose value is not within the specified list of strings. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### like8+ ### - -like(field: string, value: string): Query - -Creates a **Query** object to match the specified field whose value is similar to the specified string. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.like("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### unlike8+ ### - -unlike(field: string, value: string): Query - -Creates a **Query** object to match the specified field whose value is not similar to the specified string. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.unlike("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### and8+ ### - -and(): Query - -Creates a **Query** object with the AND condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.and(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### or8+ ### - -or(): Query - -Creates a **Query** object with the OR condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.or(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### orderByAsc8+ ### - -orderByAsc(field: string): Query - -Creates a **Query** object to sort the query results in ascending order. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByAsc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### orderByDesc8+ ### - -orderByDesc(field: string): Query - -Creates a **Query** object to sort the query results in descending order. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByDesc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### limit8+ ### - -limit(total: number, offset: number): Query - -Creates a **Query** object to specify the number of results and where to start. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| total | number | Yes |Number of results to query. | -| offset | number | Yes |Start position for query. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -let total = 10; -let offset = 1; -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.limit(total, offset); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNotNull8+ ### - -isNotNull(field: string): Query - -Creates a **Query** object to match the specified field whose value is not **null**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNotNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### beginGroup8+ ### - -beginGroup(): Query - -Creates a **Query** object for a query condition group with a left parenthesis. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### endGroup8+ ### - -endGroup(): Query - -Creates a **Query** object for a query condition group with a right parenthesis. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### prefixKey8+ ### - -prefixKey(prefix: string): Query - -Creates a **Query** object with a specified key prefix. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| prefix | string | Yes |Key prefix. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.prefixKey("$.name"); - query.prefixKey("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### setSuggestIndex8+ ### - -setSuggestIndex(index: string): Query - -Creates a **Query** object with an index preferentially used for query. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| index | string | Yes |Index preferentially used for query. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.setSuggestIndex("$.name"); - query.setSuggestIndex("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### deviceId8+ ### - -deviceId(deviceId:string):Query - -Creates a **Query** object with the device ID as the key prefix. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId | string | Yes |Device ID. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.deviceId("deviceId"); - console.log("query is " + query.getSqlLike()); -} catch (e) { - console.log("should be ok on Method Chaining : " + e); -} -``` - - -### getSqlLike8+ ### - -getSqlLike():string - -Obtains the query statement of the **Query** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| string |Returns the query statement obtained.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - let sql1 = query.getSqlLike(); - console.log("GetSqlLike sql=" + sql1); -} catch (e) { - console.log("duplicated calls should be ok : " + e); -} -``` - - -## KVStore - -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. - -Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - -### put - -put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void - -Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### put - -put(key: string, value: Uint8Array | string | number | boolean): Promise<void> - -Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete - -delete(key: string, callback: AsyncCallback<void>): void - -Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("delete err: " + JSON.stringify(err)); - return; - } - console.log("delete success"); - }); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete - -delete(key: string): Promise<void> - -Deletes a KV pair from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("delete success"); - }).catch((err) => { - console.log("delete err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) - -Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - kvStore.delete(predicates, function (err, data) { - if (err == undefined) { - console.log('delete success'); - } else { - console.log('delete fail' + err); - } - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> - -Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let arr = ["name"]; - predicates.inKeys(arr); - kvStore.put("name", "bob").then((data) => { - console.log('put success' + JSON.stringify(data)); - kvStore.delete(predicates).then((data) => { - console.log('delete success'); - }).catch((err) => { - console.log('delete fail' + JSON.stringify(err)); - }); - }) .catch((err) => { - console.log(' put fail' + err); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} - -``` - -### on('dataChange') - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data change notifications of the specified type. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### on('syncComplete') - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | - -**Example** - -```js -let kvStore; -kvStore.on('syncComplete', function (data) { - console.log("callback call data: " + data); -}); -``` - -### off('dataChange')8+ - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from data change notifications. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` - -### off('syncComplete')9+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from data change events. This API uses a synchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - -**Example** - -```js -let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[], callback: AsyncCallback<void>): void - -Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[]): Promise<void> - -Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('PutBatch ' + JSON.stringify(entries)); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void - -Writes data to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr, async function (err,data) { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('putBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>): Promise<void> - -Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} - -``` - -### deleteBatch8+ - -deleteBatch(keys: string[], callback: AsyncCallback<void>): void - -Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.deleteBatch(keys, async function (err,data) { - console.log('deleteBatch success'); - }); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### deleteBatch8+ ### - -deleteBatch(keys: string[]): Promise<void> - -Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.deleteBatch(keys).then((err) => { - console.log('deleteBatch success'); - }).catch((err) => { - console.log('deleteBatch fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(callback: AsyncCallback<void>): void - -Starts the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -function putBatchString(len, prefix) { - let entries = []; - for (var i = 0; i < len; i++) { - var entry = { - key : prefix + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - return entries; -} -try { - var count = 0; - kvStore.on('dataChange', 0, function (data) { - console.log('startTransaction 0' + data) - count++; - }); - kvStore.startTransaction(async function (err,data) { - console.log('startTransaction success'); - let entries = putBatchString(10, 'batch_test_string_key'); - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - }); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(): Promise<void> - -Starts the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - var count = 0; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log('startTransaction ' + JSON.stringify(data)); - count++; - }); - kvStore.startTransaction().then(async (err) => { - console.log('startTransaction success'); - }).catch((err) => { - console.log('startTransaction fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### commit8+ ### - -commit(callback: AsyncCallback<void>): void - -Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.commit(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### commit8+ ### - -commit(): Promise<void> - -Commits the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.commit().then(async (err) => { - console.log('commit success'); - }).catch((err) => { - console.log('commit fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### rollback8+ ### - -rollback(callback: AsyncCallback<void>): void - -Rolls back the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.rollback(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### rollback8+ ### - -rollback(): Promise<void> - -Rolls back the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.rollback().then(async (err) => { - console.log('rollback success'); - }).catch((err) => { - console.log('rollback fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### enableSync8+ ### - -enableSync(enabled: boolean, callback: AsyncCallback<void>): void - -Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.enableSync(true, function (err,data) { - if (err == undefined) { - console.log('enableSync success'); - } else { - console.log('enableSync fail'); - } - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### enableSync8+ ### - -enableSync(enabled: boolean): Promise<void> - -Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.enableSync(true).then((err) => { - console.log('enableSync success'); - }).catch((err) => { - console.log('enableSync fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### setSyncRange8+ ### - -setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void - -Sets the data synchronization range. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| localLabels |string[] | Yes |Synchronization labels set for the local device. | -| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { - console.log('SetSyncRange put success'); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -### setSyncRange8+ ### - -setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> - -Sets the data synchronization range. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| localLabels |string[] | Yes |Synchronization labels set for the local device. | -| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('setSyncRange success'); - }).catch((err) => { - console.log('delete fail ' + err); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -## SubscribeType - -Enumerates the subscription types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | -| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | -| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. | - -## ChangeNotification - -Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | -| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | -| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | -| deviceId | string | Yes | Yes|UUID of the device. | - -## Entry - -Defines the KV pairs stored in the KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| key | string | Yes | Yes|Key of the KV pair stored in the KV store. | -| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | - - -## Value - -Defines the **value** object in a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | - -## ValueType - -Enumerates the data types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| STRING |0 |String. | -| INTEGER |1 |Integer. | -| FLOAT |2 |Float (single-precision floating point). | -| BYTE_ARRAY |3 |Byte array. | -| BOOLEAN |4 |Boolean. | -| DOUBLE |5 |Double (double-precision floating point). | - -## SingleKVStore - -Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). - -Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. - -Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. - -### get - -get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void - -Obtains the value of the specified key. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log("get success data: " + data); - }); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### get - -get(key: string): Promise<Uint8Array | string | boolean | number> - -Obtains the value of the specified key. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | - - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("get success data: " + data); - }).catch((err) => { - console.log("get err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### getEntries8+ ### - -getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void - -Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_number_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.INTEGER, - value : 222 - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_number_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(keyPrefix: string): Promise<Entry[]> - -Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match.| -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('GetResultSet putBatch success'); - kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('GetResultSet closeResultSet success'); - }) - }); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string): Promise<KvStoreResultSet> - -Obtains the result set with the specified prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match.| - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResult closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResult e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |Query | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - -### getResultSet9+ ### - -getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates, async function (err, result) { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### getResultSet9+ ### - -getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates) .then((result) => { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query, callback: AsyncCallback<number>): void - -Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query): Promise<number> - -Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void - -Deletes data of a device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of a device. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('removeDeviceData put success'); - }).catch((err) => { - console.log('put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const VALUE_TEST_FLOAT_ELEMENT = 321.12; -try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | - -**Example** - -```js -let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); -} -``` - -### on('dataChange')9+ ### - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); - -``` - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` -### sync7+ - - -sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); -``` - -### sync9+ -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, mode , 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### setSyncParam8+ ### - -setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void - -Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { - console.log('SetSyncParam put success'); - }); -}catch(e) { - console.log('testSingleKvStoreSetSyncParam e ' + e); -} -``` - - -### setSyncParam8+ ### - -setSyncParam(defaultAllowedDelayMs: number): Promise<void> - -Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('SetSyncParam put success'); - }).catch((err) => { - console.log('SetSyncParam put fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('SetSyncParam e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void - -Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. | - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel(function (err,data) { - console.log('getSecurityLevel success'); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -getSecurityLevel(): Promise<SecurityLevel> - -Obtains the security level of this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel().then((data) => { - console.log(' getSecurityLevel success'); - }).catch((err) => { - console.log('getSecurityLevel fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -## DeviceKVStore8+ ## - -Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). - -Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. - -For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. - -Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. - -### get8+ ### - -get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void - -Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| key |string | Yes |Key to match. | -| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try{ - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log('get success'); - }); - }) -}catch(e) { - console.log('get e' + e); -} -``` - - -### get8+ ### - -get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> - -Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| key |string | Yes |Key to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log(' put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success'); - }).catch((err) => { - console.log('get fail ' + JSON.stringify(err)); - }); - }).catch((error) => { - console.log('put error' + error); - }); -} catch (e) { - console.log('Get e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void - -Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> - -Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + err); - }); - const query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.getResultSet(query).then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('GetResultSet putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err)); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResultSet closeResultSet success'); - }).catch((err) => { - console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); - }); - -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query, callback: AsyncCallback<number>): void - -Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query): Promise<number> - -Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; - -Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(deviceId: string, query: Query): Promise<number> - -Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - var query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void - -Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData put success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of the specified device from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('RemoveDeviceData put success'); - }).catch((err) => { - console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('RemoveDeviceData get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### sync8+ ### - -sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - kvStore.sync(devices, mode); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### sync9+ ### - -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| query |[Query](#query8) | Yes | **Query** object to match.| -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback | Yes |Callback used to return the synchronization result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const VALUE_TEST_FLOAT_ELEMENT = 321.12; -try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the synchronization complete events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback9+
### - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); -``` - -## SyncMode - -Enumerates the synchronization modes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| PULL_ONLY |0 |Pull data from the peer end to the local end only.| -| PUSH_ONLY |1 |Push data from the local end to the peer end only.| -| PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| - diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index bad85aee529e6f5b2bff68cd79fd4172c53e7969..5682921badad9367817fd3e421b1afb823970425 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -39,26 +39,60 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** + +Stage model: +```ts +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } } distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("createKVManager err: " + JSON.stringify(err)); - return; - } - console.log("createKVManager success"); - kvManager = manager; + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -84,24 +118,59 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to **Example** +Stage model: +```ts +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("createKVManager success"); - kvManager = manager; - }).catch((err) => { - console.log("createKVManager err: " + JSON.stringify(err)); + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -113,7 +182,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -572,9 +641,9 @@ Provides KV store configuration. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | | kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | @@ -1238,7 +1307,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1273,7 +1342,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1308,7 +1377,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1343,7 +1412,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1378,7 +1447,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1413,7 +1482,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1447,7 +1516,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1483,7 +1552,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1518,7 +1587,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1553,7 +1622,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1588,7 +1657,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1623,7 +1692,7 @@ Creates a **Query** object to match the specified field whose value is similar t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1658,7 +1727,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1752,7 +1821,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1787,7 +1856,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1823,7 +1892,7 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1860,7 +1929,7 @@ Creates a **Query** object to match the specified field whose value is not **nul | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1888,7 +1957,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1918,7 +1987,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1954,7 +2023,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1989,7 +2058,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2025,7 +2094,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2232,7 +2301,7 @@ try { ### delete9+ -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>): void +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. @@ -2242,13 +2311,13 @@ Deletes KV pairs that meet the specified predicates. This API uses an asynchrono | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| | callback | AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2276,7 +2345,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| **Return value** @@ -2288,7 +2357,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2312,7 +2381,7 @@ try { ### on('dataChange') -on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void Subscribes to data change notifications of the specified type. @@ -2324,7 +2393,7 @@ Subscribes to data change notifications of the specified type. | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| **Example** @@ -2362,7 +2431,7 @@ kvStore.on('syncComplete', function (data) { ### off('dataChange')8+ -off(event:'dataChange', observer?: Callback<ChangeNotification>): void +off(event:'dataChange', listener?: Callback<ChangeNotification>): void Unsubscribes from data change notifications. @@ -2373,7 +2442,7 @@ Unsubscribes from data change notifications. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| **Example** @@ -2422,7 +2491,7 @@ try { putBatch(entries: Entry[], callback: AsyncCallback<void>): void -Inserts KV pairs to this KV store in batches. This API uses an asynchronous callback to return the result. +Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2469,7 +2538,7 @@ try { putBatch(entries: Entry[]): Promise<void> -Inserts KV pairs to this KV store in batches. This API uses a promise to return the result. +Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2523,7 +2592,7 @@ try { putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void -Writes values to this KV store. This API uses an asynchronous callback to return the result. +Writes data to this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2531,7 +2600,7 @@ Writes values to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array[<ValuesBucket>]()[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | | callback |Asyncallback<void> |Yes |Callback used to return the result.| **Example** @@ -2562,7 +2631,7 @@ try { putBatch(value: Array<ValuesBucket>): Promise<void> -Writes values of the **valuesbucket** type to this KV store. This API uses a promise to return the result. +Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2570,7 +2639,7 @@ Writes values of the **valuesbucket** type to this KV store. This API uses a pro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket>](#)[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | **Return value** @@ -2607,7 +2676,7 @@ try { deleteBatch(keys: string[], callback: AsyncCallback<void>): void -Deletes KV pairs from this KV store in batches. This API uses an asynchronous callback to return the result. +Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2654,7 +2723,7 @@ try { deleteBatch(keys: string[]): Promise<void> -Deletes KV pairs from this KV store in batches. This API uses a promise to return the result. +Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2797,7 +2866,7 @@ try { commit(callback: AsyncCallback<void>): void -Submits the transaction in this KV store. This API uses an asynchronous callback to return the result. +Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2829,7 +2898,7 @@ try { commit(): Promise<void> -Submits the transaction in this KV store. This API uses a promise to return the result. +Commits the transaction in this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3104,7 +3173,7 @@ Defines the **value** object in a KV store. | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value. | +| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | ## ValueType @@ -3121,7 +3190,6 @@ Enumerates the data types. | BOOLEAN |4 |Boolean. | | DOUBLE |5 |Double (double-precision floating point). | - ## SingleKVStore Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). @@ -3641,7 +3709,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3649,13 +3717,13 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3676,7 +3744,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3684,7 +3752,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates |[Predicates](#) | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | **Return value** @@ -3695,7 +3763,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3704,7 +3772,7 @@ try { kvStore.getResultSet(predicates) .then((result) => { console.log(' GetResultSet success'); resultSet = result; - kvStore.closeResultSet(resultSet, fun ction (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log(' closeResultSet success'); }) }); @@ -3716,7 +3784,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3750,7 +3818,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3988,7 +4056,7 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return the synchronization result. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | **Example** @@ -4045,7 +4113,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4071,7 +4139,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4096,7 +4164,7 @@ kvStore.off('dataChange', function (data) { ### sync7+ -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). @@ -4108,9 +4176,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | +| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -4122,7 +4190,7 @@ kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4140,7 +4208,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -4154,7 +4222,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - kvStore.sync(devices, query, PULL_ONLY , 1000); + kvStore.sync(devices, query, mode , 1000); }); }catch(e) { console.log('Sync e' + e); @@ -5023,7 +5091,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5058,7 +5126,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5391,7 +5459,7 @@ try { ### sync8+ ### -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). @@ -5403,9 +5471,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |IDs of the devices to be synchronized.| +| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -5432,7 +5500,7 @@ try { sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5449,7 +5517,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -5510,7 +5578,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API uses a synchronous callback to return the result. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5540,7 +5608,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5566,7 +5634,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5600,3 +5668,4 @@ Enumerates the synchronization modes. | PULL_ONLY |0 |Pull data from the peer end to the local end only.| | PUSH_ONLY |1 |Push data from the local end to the peer end only.| | PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| + diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 25c0dbf964cc82eaddc85ff1114c440afbd00d2d..1849150107a5922136403a0c01cb24eb1152d675 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -1,57 +1,93 @@ # Enterprise Device Management -> **NOTE**
-> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **enterpriseDeviceManager** module provides enterprise device management capabilities so that devices have the customization capabilities required in enterprise scenarios. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager'; ``` - ## enterpriseDeviceManager.enableAdmin -enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\): void +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -61,126 +97,145 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** - -ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ADMIN -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------------- | ---- | ------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.disableAdmin -disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\): void +disableAdmin(admin: Want, callback: AsyncCallback\): void Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.disableAdmin(wantTemp, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.disableAdmin + +disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | ------------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.disableAdmin disableAdmin(admin: Want, userId?: number): Promise\ Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN -ohos.permission.MANAGE_ADMIN - -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | ------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -190,27 +245,25 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | ------------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | ------------------- | +| bundleName | String | Yes | Bundle name of the device super administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -220,68 +273,93 @@ disableSuperAdmin(bundleName: String): Promise\ Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | String | Yes | Bundle name of the device super administrator application.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.isAdminEnabled -isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\): void +isAdminEnabled(admin: Want, callback: AsyncCallback\): void Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | -------------------------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; -enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` +## enterpriseDeviceManager.isAdminEnabled + +isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void + +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` ## enterpriseDeviceManager.isAdminEnabled @@ -289,34 +367,32 @@ isAdminEnabled(admin: Want, userId?: number): Promise\ Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | -------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -326,62 +402,56 @@ isSuperAdmin(bundleName: String, callback: AsyncCallback\): void Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | -------------------------------- | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | -------------------- | +| bundleName | String | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.isSuperAdmin isSuperAdmin(bundleName: String): Promise\ Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| bundleName | String | Yes | Device super administrator application.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -391,27 +461,25 @@ getDeviceSettingsManager(callback: AsyncCallback<DeviceSettingsManager>): Obtains a **DeviceSettingsManager** object. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback { if (error != null) { console.log("error occurs" + error); - return; + return; } mgr.setDateTime(wantTemp, 1526003846000, (error, value) => { if (error != null) { @@ -423,31 +491,28 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { }); ``` - ## enterpriseDeviceManager.getDeviceSettingsManager getDeviceSettingsManager(): Promise<DeviceSettingsManager> Obtains a **DeviceSettingsManager** object. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Return value** - | Type | Description | - | -------- | -------- | - | Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained. | +| Type | Description | +| ------------------------------------ | ---------------------------------- | +| Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; -mgr.getDeviceSettingsManager().then((mgr) => { +enterpriseDeviceManager.getDeviceSettingsManager().then((mgr) => { mgr.setDateTime(wantTemp, 1526003846000).then((value) => { console.log(value); }).catch((error) => { @@ -464,77 +529,72 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCa Sets the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | callback | AsyncCallback\ { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` - ## enterpriseDeviceManager.setEnterpriseInfo setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise<boolean> Sets the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application.| **Return value** - | Type | Description | - | ------------------ | ----------------------------------- | - | Promise\; | Callback used to return the result. | +| Type | Description | +| ----------------- | --------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.setEnterpriseInfo(wantTemp, enterpriseInfo) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -544,69 +604,64 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v Obtains the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } console.log(result.name); - console.log(result.description); + console.log(result.description); }); ``` - ## enterpriseDeviceManager.getEnterpriseInfo getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> Obtains the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | -------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| **Return value** - | Type | Description | - | ------------------------------------------------ | ------------------------------------------- | - | Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application. | +| Type | Description | +| ---------------------------------------- | ------------------------- | +| Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { - console.log(result.name); - console.log(result.description); + console.log(result.name); + console.log(result.description); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -614,25 +669,20 @@ enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { Describes the enterprise information of a device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager - - | Name | Readable/Writable | Type | Mandatory | Description | - | ----------- | -------- | ------ | ---- | ---------------------------------- | - | name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs. | - | description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs. | +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ----------------- | +| name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs.| +| description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs.| ## AdminType Enumerates the administrator types of the device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager - | Name | Default Value | Description | - | -------- | -------- | -------- | - | ADMIN_TYPE_NORMAL | 0x00 | Common administrator. | - | ADMIN_TYPE_SUPER | 0x01 | Super administrator. | +| Name | Default Value | Description | +| ----------------- | ---- | ----- | +| ADMIN_TYPE_NORMAL | 0x00 | Common administrator.| +| ADMIN_TYPE_SUPER | 0x01 | Super administrator.| diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 0abc724302fcf89b86421b90c0bb507f1894b312..9baa14b8fcc490c92a115d026628c9f4a5613436 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,6 +1,7 @@ # Internationalization – I18N -> **NOTE**
+> **NOTE** +> > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). @@ -115,7 +116,7 @@ Obtains the system language. setSystemLanguage(language: string): boolean -Sets the system language. +Sets the system language. Currently, this API does not support real-time updating of the system language. This is a system API. @@ -673,7 +674,7 @@ Formats a phone number. phonenumberfmt.format("15812312312"); ``` -### getLocationName8+ +### getLocationName9+ static getLocationName(number: string, locale: string): string @@ -753,6 +754,29 @@ Converts one measurement unit into another and formats the unit based on the spe i18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); ``` +### getDateOrder9+ + +static getDateOrder(locale: string): string + +Obtains the sequence of the year, month, and day in the specified locale. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. | + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| string | Sequence of the year, month, and day.| + +**Example** + ``` + i18n.Util.getDateOrder("zh-CN"); + ``` + ## getInstance8+ @@ -1487,10 +1511,10 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. ``` -## TimeZone8+ +## TimeZone -### getID8+ +### getID getID(): string @@ -1510,7 +1534,7 @@ Obtains the ID of the specified **TimeZone** object. ``` -### getDisplayName8+ +### getDisplayName getDisplayName(locale?: string, isDST?: boolean): string @@ -1536,7 +1560,7 @@ Obtains the representation of a **TimeZone** object in the specified locale. ``` -### getRawOffset8+ +### getRawOffset getRawOffset(): number @@ -1556,7 +1580,7 @@ Obtains the offset between the time zone represented by a **TimeZone** object an ``` -### getOffset8+ +### getOffset getOffset(date?: number): number @@ -1706,3 +1730,73 @@ Checks whether the local digit switch is turned on. ``` var status = i18n.getUsingLocalDigit(); ``` + +## Transliterator9+ + + +### getAvailableIDs9+ + +static getAvailableIDs(): string[] + +Obtains a list of IDs supported by the **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------ | ------------ | +| string[] | List of IDs supported by the **Transliterator** object.| + +**Example** + ``` + i18n.Transliterator.getAvailableIDs(); + ``` + + +### getInstance9+ + +static getInstance(id: string): Transliterator + +Creates a **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| id | string | Yes | ID supported by the **Transliterator** object. | + +**Return value** +| Type | Description | +| ------ | ------------- | +| [Transliterator](#transliterator9) | **Transliterator** object.| + +**Example** + ``` + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + ``` + + +### transform9+ + +transform(text: string): string + +Converts the input string from the source format to the target format. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| text | string | Yes | Input string. | + +**Return value** +| Type | Description | +| ------ | ------------- | +| string | Target string.| + +**Example** + ``` + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + transliterator.transform ("China"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 13701cecf67e947c876789d0f1f4acde7f62a601..efd8277b83ac1cbe39a19ebad0fbf49cdf020190 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -16,22 +16,23 @@ import image from '@ohos.multimedia.image'; createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\ -Creates a **PixelMap** object. This API uses a promise to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Image.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | +| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** -| Type | Description | -| -------------------------------- | -------------- | -| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| +| Type | Description | +| -------------------------------- | ----------------------------------------------------------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.
If the size of the created pixel map exceeds that of the original image, the pixel map size of the original image is returned.| + **Example** @@ -48,7 +49,7 @@ image.createPixelMap(color, opts) createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback\): void -Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Image.Core @@ -91,7 +92,7 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i readPixelsToBuffer(dst: ArrayBuffer): Promise\ -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. +Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -122,7 +123,7 @@ pixelmap.readPixelsToBuffer(readBuffer).then(() => { readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. +Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -1008,7 +1009,7 @@ const imageSourceApi = image.createImageSource(fd); createImageSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1029,7 +1030,7 @@ const imageSourceApi = image.createImageSource(buf); createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1057,7 +1058,7 @@ const imageSourceApi = image.createImageSource(data); CreateIncrementalSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1084,7 +1085,7 @@ const imageSourceApi = image.CreateIncrementalSource(buf); CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -2246,7 +2247,7 @@ Describes image properties. ## PropertyKey7+ -Describes the exchangeable image file format (Exif) information of an image. +Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core @@ -2322,7 +2323,7 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. | | ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. | | ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. | -| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image format does not match. | +| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image formats do not match. | | ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. | | ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. | | ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. | @@ -2338,4 +2339,4 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. | | ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. | | ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. | -| ERR_IMAGE_CONFIG_FAILED | 62980259 | The software parameter setting is incorrect. | +| ERR_IMAGE_CONFIG_FAILED | 62980259 | The configuration is incorrect. | diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index dbb47a0d3ad9ee20ee500bc1d51d61ff380f63a5..c7662424d0b5bbde7888fe9dd696b177f532dcd5 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -2,7 +2,7 @@ The Input Consumer module implements listening for key events. -> **NOTE**
+> **NOTE** > > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 0b7fc7a4e6e20b0cbd760c85d4ac3ee120b6a6cf..ed980e7f4eafc6ee00808ac3030b51a9490b2412 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,8 @@ # Input Method Framework -> **NOTE** +The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. + +> **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -8,14 +10,14 @@ ## Modules to Import ``` -import inputMethod from '@ohos.inputMethod'; +import inputMethod from '@ohos.inputmethod'; ``` ## inputMethod8+ Provides the constants. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -26,7 +28,7 @@ Provides the constants. Describes the input method application attributes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -37,15 +39,15 @@ Describes the input method application attributes. getInputMethodController(): InputMethodController -Obtains an [InputMethodController](#InputMethodController) instance. +Obtains an **[InputMethodController](#inputmethodcontroller)** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type| Description| -| -------- | -------- | -| [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.| +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.| **Example** @@ -57,25 +59,74 @@ Obtains an [InputMethodController](#InputMethodController) instance. getInputMethodSetting(): InputMethodSetting -Obtains an [InputMethodSetting](#InputMethodSetting) instance. +Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type | Description | | ----------------------------------------- | ---------------------------- | -| [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.| +| [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.| + **Example** ```js var InputMethodSetting = inputMethod.getInputMethodSetting(); ``` +## inputMethod.switchInputMethod9+ + +switchInputMethod(target: InputmethodProperty, callback: AsyncCallback<boolean>): void; + +Switches to another input method. This API uses an asynchronous callback to return the result. This API can be used only in the stage model. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result. | + + +**Example** + +```js + inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { + prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); + }); +``` +## inputMethod.switchInputMethod9+ +switchInputMethod(target: InputmethodProperty): Promise<boolean> + +Switches to another input method. This API uses a promise to return the result. This API can be used only in the stage model. +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| + +**Return value** +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise used to return the execution result. | + +**Example** + + +```js + inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { + prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); + }); +``` ## InputMethodController -In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. ### stopInput @@ -83,7 +134,7 @@ stopInput(callback: AsyncCallback<boolean>): void Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -105,13 +156,13 @@ stopInput(): Promise<boolean> Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| +| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden. | **Example** @@ -123,7 +174,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ## InputMethodSetting8+ -In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. ### listInputMethod @@ -131,13 +182,12 @@ listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>) Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** - | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.| +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.| **Example** @@ -156,13 +206,12 @@ listInputMethod(): Array<InputMethodProperty> Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** - | Type | Description | | ----------------------------------------------------------- | ---------------------- | -| Promise> | Promise used to return the list of installed input methods.| +| Promise> | Promise used to return the list of installed input methods. | **Example** @@ -180,15 +229,16 @@ displayOptionalInputMethod(callback: AsyncCallback<void>): void Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| **Example** + ```js InputMethodSetting.displayOptionalInputMethod(()=>{ console.info('displayOptionalInputMethod is called'); @@ -201,16 +251,16 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework + **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise used to return the execution result. | **Example** ```js InputMethodSetting.displayOptionalInputMethod(); -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 5589051694d6aa726df14d2c87b5425f314873da..b59e88a401cebca64a2be96b29de92dd375e893d 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -2278,7 +2278,7 @@ Describes options for fetching media files. | Name | Type | Readable| Writable| Mandatory| Description | | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index e1dbb5f4a54b3936dc4b52e76ab5ad0fc0a39265..58d29f74c3196918f08da1b8e12babc71efc5347 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -801,7 +801,7 @@ Obtains the OS account ID based on domain account information. This API uses an | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | -------------------------------------------- | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| **Example** @@ -829,7 +829,7 @@ Obtains the OS account ID based on domain account information. This API uses a p | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ------------ | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| **Return value** @@ -1156,7 +1156,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| **Example** @@ -1187,7 +1187,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ---------------------- | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | **Return value** @@ -1749,7 +1749,7 @@ This is a system API and cannot be called by third-party applications. getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; -Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1760,7 +1760,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | uid | number | Yes | Process UID.| -| callback | AsyncCallback<number> | Yes | Callback used to return the bundle ID obtained. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the bundle ID obtained. | **Example** @@ -1854,7 +1854,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; -Obtains the constraint source information of an OS account. +Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1868,7 +1868,7 @@ This is a system API and cannot be called by third-party applications. | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | localId | number | Yes | ID of the target OS account.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.| -| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback used to return the source information about the specified [constraint] (#constraints). | +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback invoked to return the source information about the specified [constraint](#constraints). | **Example** @@ -1902,7 +1902,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :-------------------- | :----------------------------------------------------------- | -| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint] (#constraints).| +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint](#constraints).| **Example** @@ -1912,6 +1912,1289 @@ This is a system API and cannot be called by third-party applications. console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); ``` +## UserAuth8+ + +Provides APIs for user authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + console.info('====>test for examples constructor success'); + ``` + + +### getVersion8+ + +getVersion(): number; + +Obtains version information. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| :----- | :----------- | +| number | Version information obtained.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + console.info('====>test for examples constructor success'); + var version = userAuth.getVersion(); + console.info('====>test for examples version is : ' + JSON.stringify(version)); + ``` + +### getAvailableStatus8+ + +getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; + +Checks whether the identity authentication function is available. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -----------------------------------------------| ---- | ------------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result.| + +**Return value** + +| Type | Description | +| :----- | :---------------------------------------- | +| number | Result code(#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + console.info('====>test for examples constructor success'); + let availableStatus = userAuth.getAvailableStatus(authType, authTrustLevel); + console.info('====>test for examples AvailabeStatus is : ' + JSON.stringify(availableStatus)); + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProperty>): void; + +Obtains the executor property based on the request. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------------------- | ---- | ---------------------------------- | +| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| +| callback | AsyncCallback<[ExecutorProperty](#ExecutorProperty8+)> | Yes | Callback invoked to return the executor property obtained. | + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let keys = new Array(); + keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; + keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; + keys[2] = osAccount.GetPropertyType.FREEZING_TIME; + let getPropertyRequest = {authType, keys}; + userAuth.getProperty(getPropertyRequest,function (propReq) { + console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); + }) + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest): Promise; + +Obtains the executor property based on the request. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------- | +| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| + +**Return value** + +| Type | Description | +| :---------------------------------------------------------------- | :-------------------------------------------------- | +| Promise<[ExecutorProperty](#ExecutorProperty8+)> | Promise used to return the executor property obtained.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let keys = new Array(); + keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; + keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; + keys[2] = osAccount.GetPropertyType.FREEZING_TIME; + let getPropertyRequest = {authType, keys}; + userAuth.getProperty(getPropertyRequest).then((propReq) => { + console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest, callback: AsyncCallback): void; + +Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | +| request | [SetPropertyRequest](#SetPropertyRequest8+)| Yes | Request information, including the authentication credential type and key value to set. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the [result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let key = osAccount.SetPropertyType.INIT_ALGORITHM; + let setInfo = new Uint8Array(); + let setPropertyRequest = {authType, key, setInfo}; + userAuth.setProperty(setPropertyRequest,function (setProp) { + console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest): Promise; + +Sets the property for the initialization algorithm. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | +| request | [SetPropertyRequest](#SetPropertyRequest8+) | Yes | Request information, including the authentication credential type and the key value to set.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------------------------------------------------------------------------------- | +| Promise<number> | Promise used to return the [result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let key = osAccount.SetPropertyType.INIT_ALGORITHM; + let setInfo = new Uint8Array(); + let setPropertyRequest = {authType, key, setInfo}; + userAuth.setProperty(setPropertyRequest).then((setProp) => { + console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + }); + ``` + +### auth8+ + +auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Performs authentication. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security.| +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result); + onresult.authresult = result; + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### authUser8+ + +authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Perform user authentication. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| userId | number | Yes | User ID. | +| challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security. | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let userID = 100; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.authUser(userID, challenge, authType, authTrustLevel, { + onResult: function(result,extraInfo){ + console.log("====>test for examples authUser result = " + result); + onresult.authresult = result; + console.log("====>test for examples authUser extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples authUser onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### cancelAuth8+ + +cancelAuth(contextID: Uint8Array): number; + +Cancels authentication. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------| ---------- | ---- | ------------------------------------------ | +| contextID | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| number | [Result code](#ResultCode8+).| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let contextID = null; + let cancelAuthresult = null; + cancelAuthresult = userAuth.cancelAuth(contextID); + console.log("====>test for examples cancelAuthresult result = " + JSON.stringify(cancelAuthresult)); + ``` + +## PINAuth8+ + +Provides methods for PIN authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for PIN authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var pinAuth = new osAccount.PINAuth(); + console.info('====>test for examples constructor success'); + ``` + +### registerInputer + +registerInputer(inputer: IInputer): boolean; + +Registers an inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------------------- | --- | ------------------ | +| inputer | [IInputer](#IInputer8+) | Yes | Callback invoked to obtain the PIN.| + +**Return value** + +| Type | Description | +| :------ | :-------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + ```js + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + if (GetAuthSubType == 0) { + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +### unregisterInputer + +unregisterInputer(): void; + +Unregisters the inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Example** + ```js + var pinAuth = new osAccount.PinAuth(); + pinAuth.unregisterInputer(); + ``` + +## UserIdentityManager8+ + +Provides methods for user identity management. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + console.info('====>test for examples constructor success'); + ``` + +### openSession8+ + +openSession(callback: AsyncCallback<Uint8Array>): void; + +Opens a session to start identity management (IDM) so that a challenge value can be obtained. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var challenge; + userIDM.openSession(function(err, data){ + try{ + console.log("====>test for examples before get challenge"); + console.log("====>test for examples + " + data); + challenge = data; + console.log("====>test for examples end "); + console.log("====>test for examples after get challenge"); + } + catch(e) { + console.info('====>test for examples openSession error = ' + JSON.stringify(e)); + } + }); + ``` + +### openSession8+ + +openSession(): Promise<Uint8Array>; + +Opens a session to start IDM so that a challenge value can be obtained. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Return value** + +| Type | Description | +| :------------------------ | :------------------------------------------------------- | +| Promise<Uint8Array> | Promise used to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var challenge; + userIDM.openSession().then((data) => { + try{ + console.log("====>test for examples before get challenge"); + console.log("====>test for examples + " + data); + challenge = data; + console.log("====>test for examples end "); + console.log("====>test for examples after get challenge"); + } + catch(err) { + console.info('====>test for examples faceDemo openSession error1 = ' + JSON.stringify(err)); + } + }) + .catch((err) => { + console.info('====>test for examples faceDemo openSession error2 = ' + JSON.stringify(err)); + }) + ``` + +### addCredential8+ + +addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Adds credential information, which includes the authentication credential type, subtype, and token (if a non-PIN credential is added). This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------ | --- | -------------------------------- | +| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | Credential information to add. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.addCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.info('====>test for examples aaaaaaaaaaaaa'); + console.info("====>test for examples addCredential result = " + result); + console.info("====>test for examples addCredential extraInfo = " + JSON.stringify(extraInfo)); + console.log(result) + onresult.addCredresult= result; + if(extraInfo != undefined) { + onresult.credentialId = extraInfo.credentialId + } else { + onresult.credentialId = null; + } + } + }) + ``` + +### updateCredential8+ + +updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Updates credential information. This API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------- | --- | -------------------------------- | +| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | New credential information. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples faceDemo updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples faceDemo updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + } + }) + ``` + +### closeSession8+ + +closeSession(): void; + +Closes this session to terminate IDM. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + userIDM.closeSession(); + ``` + +### cancel8+ + +cancel(challenge: Uint8Array): number; + +Cancels an entry based on the challenge value. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----- | +| challenge | Uint8Array | Yes | Challenge value.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| number | [Result code](#ResultCode8+).| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let challenge = 1; + let cancelresult = userIDM.cancel(challenge); + ``` + +### delUser8+ + +delUser(token: Uint8Array, callback: IIdmCallback): void; + +Deletes a user based on the authentication token. The API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | --- | ------------------------- | +| token | Uint8Array | Yes | Authentication token. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let onresult = { + delUserresult: null, + CredentialId: null, + } + let token = null; + userIDM.delUser(token, { + onResult: function(result,extraInfo){ + console.log("====>test for examples delUser result = " + result) + onresult.delUserresult = result + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicdelUser delUser = ' + JSON.stringify(onresult)); + } + }) + ``` + +### delCred8+ + +delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): void; + +Deletes user credential information. The API uses a callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------------------- | --- | ---------------------------| +| credentialId | Uint8Array | Yes | Credential ID. | +| token | Uint8Array | Yes | Authentication token. | +| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let onresult = { + delUserresult: null, + CredentialId: null, + } + let credentialId = 1; + let token = null; + userIDM.delCred(credentialId, token,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples delCred result = " + result) + onresult.delCredresult = result + console.log("====>test for examples delCred extraInfo = " + extraInfo) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.log("====>test for examples delCred onresult = " + JSON.stringify(onresult)); + } + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>, authType?: AuthType): void; + +Obtains authentication information. This API uses asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | +| callback | AsyncCallback<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Yes | Callback invoked to return information about all enrolled credentials of the specified type of the user.| +| authType | [AuthType](#AuthType8+) | No | Authentication credential type. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var authType = osAccount.AuthType.PIN; + userIDM.getAuthInfo(authType, function (authInfo) { + console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; + +Obtains authentication information. This API uses a promise to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------- | +| authType | [AuthType](#AuthType8+) | No | Authentication credential type.| + +**Return value** + +| Type | Description | +| :------------------------------------------- | :------------------------------------------------------------------------ | +| Promise<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Promise used to return information about all enrolled credentials of the specified type of the user.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + var authType = osAccount.AuthType.PIN; + userIDM.getAuthInfo(authType).then((authInfo) => { + console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) + }) + ``` + +## IInputData8+ + +Provides callbacks for PIN operations. + +### onSetData8+ + +onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; + +Called to set data. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | +| pinSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| data | Uint8Array | Yes | Data (credential) to set. The data is used for authentication and operations for adding and modifying credentials.| + +**Example** + ```js + console.log("====>test for examples onCreate start "); + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + console.log("====>test for examples GetAuthSubType " + GetAuthSubType); + console.log("====>test for examples AuthSubType " + AuthSubType); + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); + if (GetAuthSubType == 0) { + console.log("====>test for examples GetAuthSubType == 0 "); + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + console.log("====>test for examples GetAuthSubType == 1 "); + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +## IInputer8+ + +Provides callbacks for the PIN input box. + +### onGetData8+ + +onGetData: (callback: IInputData) => void; + +Called to obtain data. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------------- | ---- | --------------- | +| callback | [IInputData](#IInputData8+) | Yes | Called to input the PIN.| + +**Example** + ```js + console.log("====>test for examples onCreate start "); + var pinAuth = new osAccount.PINAuth(); + var GetAuthSubType = 0; + var AuthSubType = osAccount.AuthSubType.PIN_SIX; + console.log("====>test for examples GetAuthSubType " + GetAuthSubType); + console.log("====>test for examples AuthSubType " + AuthSubType); + var Inputerdata = [0,1,3]; + var registerresult = pinAuth.registerInputer({ + onGetData: (GetAuthSubType, IInputData) => { + console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); + if (GetAuthSubType == 0) { + console.log("====>test for examples GetAuthSubType == 0 "); + IInputData.onSetData(AuthSubType, Inputerdata) + } else { + console.log("====>test for examples GetAuthSubType == 1 "); + IInputData.onSetData(GetAuthSubType, Inputerdata); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +## IUserAuthCallback8+ + +Provides callbacks for user authentication. + +### onResult8+ + +onResult: (result: number, extraInfo: AuthResult) => void; + +Called to return the authentication result code. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------- | ---- | ------------------- | +| result | number | Yes | Authentication result code.| +| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific authentication result information. If the authentication is successful, the authentication token is returned in **extrainfo**. If the authentication fails, the remaining authentication time is returned. If the authentication executor is locked, the freezing time is returned.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result); + onresult.authresult = result; + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + } + }); + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let onresult = { + authresult: null, + authextr: null, + } + let onacquireinfo = { + authmodule : null, + authacquire : null, + authextr : null + } + userAuth.auth(challenge, authType,authTrustLevel,{ + onResult: function(result,extraInfo){ + console.log("====>test for examples auth result = " + result) + onresult.authresult = result + console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); + onresult.authextr = extraInfo; + console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); + }, + onAcquireInfo:function (modulea,acquire,extr){ + console.info('====>test for examples publicauth auth onAcquireInfo in'); + onacquireinfo.authmodule = modulea; + onacquireinfo.authacquire = acquire; + onacquireinfo.authextr = extr; + console.log("====>test for examples auth module = " + JSON.stringify(modulea)); + console.info('====>test for examples publicauth auth onAcquireInfo = ' + JSON.stringify(onacquireinfo)); + } + }); + ``` + +## IIdmCallback8+ + +Provides callbacks for IDM. + +### onResult8+ + +onResult: (result: number, extraInfo: AuthResult) => void; + +Called to return the authentication result code. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------- | ---- | ----------------------- | +| result | number | Yes | Authentication result code. | +| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific information to be transferred.| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + } + }) + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let CredentialInfo = null; + let onresult = { + addCredresult: null, + credentialId: null, + } + let onacquireinfo = { + updateCredmodule : null, + updateCredacquire : null, + updateCredextr : null + } + userIDM.updateCredential(CredentialInfo, { + onResult: function(result,extraInfo){ + console.log("====>test for examples updateCredential result = " + result) + onresult.updateCredresult = result + console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) + if(extraInfo != undefined) { + onresult.CredentialId = extraInfo.credentialId + } else { + onresult.CredentialId = null; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + }, + onAcquireInfo:function (modulea,acquire,extr){ + console.info('====>test for examples publicupdateCred updateCredential onAcquireInfo in '); + onacquireinfo.updateCredmodule = modulea + onacquireinfo.updateCredacquire = acquire + onacquireinfo.updateCredextr = extr + console.info('====>test for examples updateCredential onacquireinfo = ' + JSON.stringify(onacquireinfo)); + console.log("====>test for examples updateCredential module = " + modulea) + } + }) + ``` + +## GetPropertyRequest8+ + +Defines the request for obtaining property information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------- | ----- | ----------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| keys | Array<[GetPropertyType](#GetPropertyType8+)> | Yes | An array of the types of the properties to obtain.| + +## SetPropertyRequest8+ + +Defines the request for setting property information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------ | ----- | -------------------- | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| keys | [SetPropertyType](#SetPropertyType8+) | Yes | Type of the property to be set.| +| setInfo | Uint8Array | Yes | Information to set. | + +## ExecutorProperty8+ + +Defines the executor property. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| result | number | Yes | Result. | +| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Authentication credential subtype.| +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## AuthResult8+ + +Defines the authentication result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| token | Uint8Array | No | Authentication token. | +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## CredentialInfo8+ + +Defines the credential information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| credType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| credSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| token | Uint8Array | Yes | Authentication token. | + +## RequestResult8+ + +Defines the request result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| credentialId | Uint8Array | No | Credential ID. | + +## EnrolledCredInfo8+ + +Defines enrolled credential information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ------------------- | +| credentialId | Uint8Array | Yes | Credential ID. | +| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype.| +| templateId | Uint8Array | Yes | Credential template ID. | + +## GetPropertyType8+ + +Enumerates the types of the properties to obtain. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ------------- | ------ | --------- | +| AUTH_SUB_TYPE | 1 | Authentication subtype.| +| REMAIN_TIMES | 2 | Remaining time. | +| FREEZING_TIME | 3 | Freezing time. | + +## SetPropertyType8+ + +Enumerates the types of the properties to set. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| -------------- | ----- | ----------- | +| INIT_ALGORITHM | 1 | Initialization algorithm.| + +## AuthType8+ + +Enumerates the credential types. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----- | ----- | ---------------- | +| PIN | 1 | PIN authentication.| +| FACE | 2 | Facial authentication.| + +## AuthSubType8+ + +Enumerates the credential subtypes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---------- | ----- | ------------------ | +| PIN_SIX | 10000 | Six-digit PIN. | +| PIN_NUMBER | 10001 | Custom PIN.| +| PIN_MIXED | 10002 | Custom mixed credential.| +| FACE_2D | 20000 | 2D face credential. | +| FACE_3D | 20001 | 3D face credential. | + +## AuthTrustLevel8+ + +Enumerates the trust levels of the authentication result. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---- | ------ | ----------- | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| + +## Module8+ + +Enumerates the modules from which information is obtained. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| --------- | ------ | ------------------------ | +| FACE_AUTH | 1 | Information obtained from the face authentication module.| + +## ResultCode8+ + +Enumerates the authentication result codes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------- | ----- | ---------------------------------------- | +| SUCCESS | 0 | The authentication is successful or the authentication function is supported. | +| FAIL | 1 | The authentication executor failed to identify the user. | +| GENERAL_ERROR | 2 | Other errors. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | +| TYPE_NOT_SUPPORT | 5 | The authentication credential type is not supported. | +| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | +| BUSY | 7 | The authentication task is not available. Try again after a few seconds.| +| INVALID_PARAMETERS | 8 | Incorrect parameters are detected. | +| LOCKED | 9 | The authentication executor is locked. | +| NOT_ENROLLED | 10 | The authentication executor is not enrolled. | + +## FaceTipsCode8+ + +Enumerates the tip codes for facial authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------------- | ----- | ---------------------------------------- | +| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained face image is too bright. | +| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained face image is too dark. | +| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. | +| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. | +| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. | +| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | +| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is angled too much to the right.| +| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is angled too much to the left.| +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. | +| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the device. | +| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | + +## ingerprintTips8+ + +Enumerates the tip codes for fingerprint authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------------- | ----- | ----------------------------------------------- | +| FINGERPRINT_TIP_GOOD | 0 | The captured image is clear. | +| FINGERPRINT_TIP_IMAGER_DIRTY | 1 | The fingerprint image has big noise due to dirt on the sensor.| +| FINGERPRINT_TIP_INSUFFICIENT | 2 | Failed to process the fingerprint image due to big noise. | +| FINGERPRINT_TIP_PARTIAL | 3 | Only part of the fingerprint image is detected. | +| FINGERPRINT_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to quick motion. | +| FINGERPRINT_TIP_TOO_SLOW | 5 | Failed to read the fingerprint image due to lack of motion. | + ## OsAccountInfo Defines information about an OS account. @@ -1932,7 +3215,7 @@ Defines information about an OS account. | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | | distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | -| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | +| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. | ## DomainAccountInfo8+ @@ -2017,6 +3300,8 @@ Domain account information. Defines information about the source of a constraint. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory| Description | @@ -2028,6 +3313,8 @@ Defines information about the source of a constraint. Enumerates the constraint sources. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 3facc0146ebe2484672cffb3c9a45d0ac7d9f164..971b3408c9a9fdd616fe1133ca3cab3844ee7fd1 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,22 +1,22 @@ # Prompt +The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + > **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import prompt from '@ohos.prompt' ``` -## Required Permissions - -None. ## prompt.showToast showToast(options: ShowToastOptions): void -Shows the toast. +Shows a toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -26,15 +26,11 @@ Shows the toast. | options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| **Example** - ``` - export default { - showToast() { - prompt.showToast({ - message: 'Message Info', - duration: 2000, - }); - } - } + ```js +prompt.showToast({ + message: 'Message Info', + duration: 2000, +}); ``` ## ShowToastOptions @@ -42,11 +38,11 @@ Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | -------------- | ---- | ---------------------------------------- | -| message | string | Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom | <length> | No | Distance between the toast border and the bottom of the screen. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ------ | ---------------------------------------- | +| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | ## prompt.showDialog @@ -69,38 +65,34 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Example** - ``` - export default { - showDialog() { - prompt.showDialog({ - title: 'Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ], - }) - .then(data => { - console.info('showDialog success, click button: ' + data.index); - }) - .catch(err => { - console.info('showDialog error: ' + err); - }) + ```js +prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', } - } + ], +}) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) ``` ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void -Shows a dialog box. This API uses a callback to return the result asynchronously. +Shows a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -112,32 +104,27 @@ Shows a dialog box. This API uses a callback to return the result asynchronously | callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showDialog err: ' + err); - return; - } - console.info('showDialog success callback, click button: ' + data.index); + ```js +prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', }, - showDialog() { - prompt.showDialog({ - title: 'showDialog Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ] - }, this.callback); + { + text: 'button2', + color: '#000000', } + ] +}, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; } + console.info('showDialog success callback, click button: ' + data.index); +}); ``` ## ShowDialogOptions @@ -146,11 +133,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| message | string | No | Text body. | -| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | +| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -160,7 +147,7 @@ Describes the dialog box response result. | Name | Type | Description | | ----- | ------ | ------------------- | -| index | number | Index of the selected button in the array.| +| index | number | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -179,36 +166,31 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showActionMenu err: ' + err); - return; - } - console.info('showActionMenu success callback, click button: ' + data.index); + ```js +prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', }, - showActionMenu() { - prompt.showActionMenu({ - title: 'Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }, this.callback) - } + { + text: 'item2', + color: '#000000', + }, + ] +}, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; } + console.info('showActionMenu success callback, click button: ' + data.index); +}) ``` ## prompt.showActionMenu -showActionMenu(options: ActionMenuOptions): Promise\ +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> Shows an action menu. This API uses a promise to return the result synchronously. @@ -225,30 +207,26 @@ Shows an action menu. This API uses a promise to return the result synchronously | Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Example** - ``` - export default { - showActionMenu() { - prompt.showActionMenu({ - title: 'showActionMenu Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }) - .then(data => { - console.info('showActionMenu success, click button: ' + data.index); - }) - .catch(err => { - console.info('showActionMenu error: ' + err); - }) - } - } + ```js +prompt.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] +}) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) ``` ## ActionMenuOptions @@ -256,10 +234,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| buttons | Array | Yes | Array of menu items. The array structure is **{text:'button', color: '\#666666'}**. One to six items are supported. If there are more than six items, extra items will not be displayed.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -269,4 +247,15 @@ Describes the action menu response result. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------------------ | -| index | number | No | Index of the selected button in the array, starting from **0**.| +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Button text.| +| color | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 5b371ea07267732eb69de7676cab7f6057954275..16da2e93685e99d26b9af2040af3f294ce68bd08 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -899,9 +899,698 @@ promise.then(data => { }); ``` +## radio.sendUpdateCellLocationRequest8+ + +sendUpdateCellLocationRequest\(callback: AsyncCallback\): void + +Sends a cell location update request. This API uses an asynchronous callback to return the result. + + + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.sendUpdateCellLocationRequest((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.sendUpdateCellLocationRequest8+ + +sendUpdateCellLocationRequest\(\): Promise + +Sends a cell location update request. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = radio.sendUpdateCellLocationRequest(); +promise.then(data => { + console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendUpdateCellLocationRequest fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getCellInformation8+ + +getCellInformation(callback: AsyncCallback>): void + +Obtains cell information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------ | +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getCellInformation((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getCellInformation8+ + +getCellInformation(slotId: number, callback: AsyncCallback\>): void + +Obtains cell information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\\> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getCellInformation(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getCellInformation8+ + +getCellInformation(slotId?: number): Promise\> + +Obtains cell information. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ----------------------- | +| Promise\\> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.getCellInformation(slotId); +promise.then(data => { + console.log(`getCellInformation success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCellInformation fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.setNetworkSelectionMode + +setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCallback\): void + +Sets the network selection mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------ | +| options | [NetworkSelectionModeOptions](#networkselectionmodeoptions) | Yes | Network selection mode.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let networkInformation={ + operatorName: "China Mobile", + operatorNumeric: "898600", + state: 1, + radioTech: "CS" +} +let networkSelectionModeOptions={ + slotid: 0, + selectMode: 1, + networkInformation: networkInformation, + resumeSelection: true +} +radio.setNetworkSelectionMode(networkSelectionModeOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.setNetworkSelectionMode + +setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise + +Sets the network selection mode. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------------------- | ---- | ------------------ | +| options | [NetworkSelectionModeOptions](#networkselectionmodeoptions) | Yes | Network selection mode.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let networkInformation={ + operatorName: "China Mobile", + operatorNumeric: "898600", + state: 1, + radioTech: "CS" +} +let networkSelectionModeOptions={ + slotid: 0, + selectMode: 1, + networkInformation: networkInformation, + resumeSelection: true +} +let promise = radio.setNetworkSelectionMode(networkSelectionModeOptions); +promise.then(data => { + console.log(`setNetworkSelectionMode success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setNetworkSelectionMode fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getNetworkSearchInformation + +getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\): void + +Obtains network search information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[NetworkSearchResult](#networksearchresult)\> | Yes | Callback used to return the result. | + +**Example** + +```js +radio.getNetworkSearchInformation(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.getNetworkSearchInformation + +getNetworkSearchInformation\(slotId: number\): Promise + +Obtains network search information. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ----------------------- | +| Promise\<[NetworkSearchResult](#networksearchresult)\> | Promise used to return the result.| + +**Example** + +```js +let promise = radio.getNetworkSearchInformation(0); +promise.then(data => { + console.log(`getNetworkSearchInformation success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getNetworkSearchInformation fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getNrOptionMode8+ + +getNrOptionMode(callback: AsyncCallback): void + +Obtains the NR option mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[NrOptionMode](#nroptionmode8)\> | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getNrOptionMode((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getNrOptionMode8+ + +getNrOptionMode(slotId: number, callback: AsyncCallback): void + +Obtains the NR option mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[NrOptionMode](#nroptionmode8)\> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getNrOptionMode(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getNrOptionMode8+ + +getNrOptionMode(slotId?: number): Promise + +Obtains the NR option mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------------------------------- | ----------------------- | +| Promise\<[NrOptionMode](#nroptionmode8)\> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.getNrOptionMode(slotId); +promise.then(data => { + console.log(`getNrOptionMode success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getNrOptionMode fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.turnOnRadio7+ + +turnOnRadio(callback: AsyncCallback): void + +Turns on the radio function. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.turnOnRadio((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOnRadio7+ + +turnOnRadio(slotId: number, callback: AsyncCallback): void + +Turns on the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.turnOnRadio(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOnRadio7+ + +turnOnRadio(slotId?: number): Promise + +Turns on the radio function for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.turnOnRadio(slotId); +promise.then(data => { + console.log(`turnOnRadio success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`turnOnRadio fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.turnOffRadio7+ + +turnOffRadio(callback: AsyncCallback): void + +Turns off the radio function. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.turnOffRadio((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOffRadio7+ + +turnOffRadio(slotId: number, callback: AsyncCallback): void + +Turns off the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.turnOffRadio(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOffRadio7+ + +turnOffRadio(slotId?: number): Promise + +Turns off the radio function for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = radio.turnOffRadio(slotId); +promise.then(data => { + console.log(`turnOffRadio success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`turnOffRadio fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.setPreferredNetwork8+ + +setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\): void + +Sets the preferred network. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| networkMode | [PreferredNetworkMode](#preferrednetworkmode8) | Yes | Preferred network mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +radio.setPreferredNetwork(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.setPreferredNetwork8+ + +setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise + +Sets the preferred network. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| networkMode | [PreferredNetworkMode](#preferrednetworkmode8) | Yes | Preferred network mode. | + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = radio.setPreferredNetwork(0, 1); +promise.then(data => { + console.log(`setPreferredNetwork success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setPreferredNetwork fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getPreferredNetwork8+ + +getPreferredNetwork\(slotId: number, callback: AsyncCallback\): void + +Obtains the preferred network. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[PreferredNetworkMode](#preferrednetworkmode8)\> | Yes | Callback used to return the result. | + +**Example** + +```js +radio.getPreferredNetwork(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.getPreferredNetwork8+ + +getPreferredNetwork(slotId: number): Promise + +Obtains the preferred network. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = radio.getPreferredNetwork(0); +promise.then(data => { + console.log(`getPreferredNetwork success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getPreferredNetwork fail, promise: err->${JSON.stringify(err)}`); +}); +``` + ## RadioTechnology -Enumerates the RAT. +Enumerates radio access technologies. **System capability**: SystemCapability.Telephony.CoreService @@ -1010,3 +1699,238 @@ Enumerates network selection modes. | NETWORK_SELECTION_UNKNOWN | 0 | Unknown network selection mode.| | NETWORK_SELECTION_AUTOMATIC | 1 | Automatic network selection mode.| | NETWORK_SELECTION_MANUAL | 2 | Manual network selection mode.| + +## PreferredNetworkMode8+ + +Enumerates preferred network modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| --------------------------------------------------------- | ---- | --------------------------------------------- | +| PREFERRED_NETWORK_MODE_GSM | 1 | GSM network mode. | +| PREFERRED_NETWORK_MODE_WCDMA | 2 | WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE | 3 | LTE network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA | 4 | LTE+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA_GSM | 5 | LTE+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_WCDMA_GSM | 6 | WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_CDMA | 7 | CDMA network mode. | +| PREFERRED_NETWORK_MODE_EVDO | 8 | EVDO network mode. | +| PREFERRED_NETWORK_MODE_EVDO_CDMA | 9 | EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_WCDMA_GSM_EVDO_CDMA | 10 | WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_EVDO_CDMA | 11 | LTE+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA_GSM_EVDO_CDMA | 12 | LTE+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA | 13 | TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_GSM | 14 | TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA | 15 | TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA_GSM | 16 | TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA | 17 | LTE+TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_GSM | 18 | LTE+TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA | 19 | LTE+TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA_GSM | 20 | LTE+TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 21 | TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 22 | LTE+TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode.| +| PREFERRED_NETWORK_MODE_NR | 31 | NR network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE | 32 | NR+LTE network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA | 33 | NR+LTE+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA_GSM | 34 | NR+LTE+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_EVDO_CDMA | 35 | NR+LTE+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA_GSM_EVDO_CDMA | 36 | NR+LTE+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA | 37 | NR+LTE+TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_GSM | 38 | NR+LTE+TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA | 39 | NR+LTE+TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM | 40 | NR+LTE+TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 41 | NR+LTE+TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_MAX_VALUE | 99 | Maximum value of the preferred network mode. | + +## CellInformation8+ + +Defines the cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| networkType | [NetworkType](#networkType) | Network type of the cell. | +| isCamped | boolean | Status of the cell. | +| timeStamp | number | Timestamp when cell information is obtained. | +| signalInformation | [SignalInformation](#signalinformation) | Signal information. | +| data | [CdmaCellInformation](#cdmacellinformation) \| [GsmCellInformation](#gsmcellinformation) \| [LteCellInformation](#ltecellinformation) \| [NrCellInformation](#nrcellinformation) \| [TdscdmaCellInformation](#tdscdmacellinformation) | CDMA cell information \| GSM cell information \| LTE cell information \| NR cell information \| TD-SCDMA cell information | + +## CdmaCellInformation8+ + +Defines the CDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------- | ------ | ------------ | +| baseId | number | Base station ID. | +| latitude | number | Longitude. | +| longitude | number | Latitude. | +| nid | number | Network ID.| +| sid | number | System ID.| + +## GsmCellInformation8+ + +Defines the GSM cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | -------------------- | +| lac | number | Location area code. | +| cellId | number | Cell ID. | +| arfcn | number | Absolute radio frequency channel number.| +| bsic | number | Base station ID. | +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | + +## LteCellInformation8+ + +Defines the LTE cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------- | ------- | ----------------------- | +| cgi | number | Cell global identification. | +| pci | number | Physical cell ID. | +| tac | number | Tracking area code. | +| earfcn | number | Absolute radio frequency channel number. | +| bandwidth | number | Bandwidth. | +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | +| isSupportEndc | boolean | Support New Radio_Dual Connectivity| + +## NrCellInformation8+ + +Defines the NR cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------- | ------ | ---------------- | +| nrArfcn | number | 5G frequency number. | +| pci | number | Physical cell ID. | +| tac | number | Tracking area code. | +| nci | number | 5G network cell ID.| +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | + +## TdscdmaCellInformation8+ + +Defines the TD-SCDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | ------------ | +| lac | number | Location area code.| +| cellId | number | Cell ID. | +| cpid | number | Cell parameter ID.| +| uarfcn | number | Absolute radio frequency number.| +| mcc | string | Mobile country code.| +| mnc | string | Mobile network code. | + +## WcdmaCellInformation8+ + +Defines the WCDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | ------------ | +| lac | number | Location area code.| +| cellId | number | Cell ID. | +| psc | number | Primary scrambling code. | +| uarfcn | number | Absolute radio frequency number.| +| mcc | string | Mobile country code.| +| mnc | string | Mobile network code. | + +## NrOptionMode8+ + +Enumerates NR selection modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------------------- | ---- | ---------------------------------- | +| NR_OPTION_UNKNOWN | 0 | Unknown NR selection mode. | +| NR_OPTION_NSA_ONLY | 1 | NR selection mode in 5G non-standalone networking. | +| NR_OPTION_SA_ONLY | 2 | NR selection mode in 5G standalone networking. | +| NR_OPTION_NSA_AND_SA | 3 | NR selection mode in non-standalone and standalone networking.| + +## NetworkSearchResult + +Defines the network search result. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ---------------------- | ------------------------------------------------- | -------------- | +| isNetworkSearchSuccess | boolean | Successful network search.| +| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.| + +## NetworkInformation + +Defines the network information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------------- | ----------------------------------------- | -------------- | +| operatorName | string | Carrier name.| +| operatorNumeric | string | Carrier number. | +| state | [NetworkInformation](#networkinformationstate) | Network information status.| +| radioTech | string | Radio technology. | + +## NetworkInformationState + +Enumerates network information states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ----------------- | ---- | ---------------- | +| NETWORK_UNKNOWN | 0 | Unknown state. | +| NETWORK_AVAILABLE | 1 | Available for registration.| +| NETWORK_CURRENT | 2 | Registered state.| +| NETWORK_FORBIDDEN | 3 | Unavailable for registration. | + +## NetworkSelectionModeOptions + +Defines the network selection mode. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------------ | --------------------------------------------- | -------------------------------------- | +| slotId | number | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. | +| networkInformation | [NetworkInformation](#networkinformation) | Network information. | +| resumeSelection | boolean | Whether to resume selection. | diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 50c50f574bbcad706077725e3b4c6f69f3334b1c..4f6da3208d7bef31f14e626a8fc09c57b5cb0423 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -17,9 +17,9 @@ import request from '@ohos.request'; ## Constraints -HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. +HTTPS is supported by default in the FA model. To support HTTP, add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. -``` +```js var config = { "deviceConfig": { "default": { @@ -32,6 +32,9 @@ var config = { } ``` +The **cleartextTraffic** attribute is not involved during the development of applications in the stage model. + + ## Constants @@ -39,28 +42,28 @@ var config = { **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| NETWORK_MOBILE | number | Yes | No | Whether download is allowed when the cellular network is used. | -| NETWORK_WIFI | number | Yes | No | Whether download is allowed on a WLAN. | -| ERROR_CANNOT_RESUME7+ | number | Yes | No | Failure to resume the download due to an error. | -| ERROR_DEVICE_NOT_FOUND7+ | number | Yes | No | Failure to find a storage device such as a memory card. | -| ERROR_FILE_ALREADY_EXISTS7+ | number | Yes | No | Failure to download the file because it already exists. | -| ERROR_FILE_ERROR7+ | number | Yes | No | File operation failure. | -| ERROR_HTTP_DATA_ERROR7+ | number | Yes | No | HTTP transmission failure. | -| ERROR_INSUFFICIENT_SPACE7+ | number | Yes | No | Insufficient storage space. | -| ERROR_TOO_MANY_REDIRECTS7+ | number | Yes | No | Error caused by too many network redirections. | -| ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes | No | Unidentified HTTP code. | -| ERROR_UNKNOWN7+ | number | Yes | No | Unknown error. | -| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes | No | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a cellular network session. | -| PAUSED_UNKNOWN7+ | number | Yes | No | Download paused due to unknown reasons. | -| PAUSED_WAITING_FOR_NETWORK7+ | number | Yes | No | Download paused due to a network connection problem, for example, network disconnection. | -| PAUSED_WAITING_TO_RETRY7+ | number | Yes | No | Download paused and then retried. | -| SESSION_FAILED7+ | number | Yes | No | Download failure without retry. | -| SESSION_PAUSED7+ | number | Yes | No | Download paused. | -| SESSION_PENDING7+ | number | Yes | No | Download pending. | -| SESSION_RUNNING7+ | number | Yes | No | Download in progress. | -| SESSION_SUCCESSFUL7+ | number | Yes | No | Successful download. | +| NETWORK_MOBILE | number | Yes| No| Whether download is allowed on a mobile network.| +| NETWORK_WIFI | number | Yes| No| Whether download is allowed on a WLAN.| +| ERROR_CANNOT_RESUME7+ | number | Yes| No| Failure to resume the download due to an error.| +| ERROR_DEVICE_NOT_FOUND7+ | number | Yes| No| Failure to find a storage device such as a memory card.| +| ERROR_FILE_ALREADY_EXISTS7+ | number | Yes| No| Failure to download the file because it already exists.| +| ERROR_FILE_ERROR7+ | number | Yes| No| File operation failure.| +| ERROR_HTTP_DATA_ERROR7+ | number | Yes| No| HTTP transmission failure.| +| ERROR_INSUFFICIENT_SPACE7+ | number | Yes| No| Insufficient storage space.| +| ERROR_TOO_MANY_REDIRECTS7+ | number | Yes| No| Error caused by too many network redirections.| +| ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes| No| Unidentified HTTP code.| +| ERROR_UNKNOWN7+ | number | Yes| No| Unknown error.| +| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes| No| Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| +| PAUSED_UNKNOWN7+ | number | Yes| No| Download paused due to unknown reasons.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | Yes| No| Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_TO_RETRY7+ | number | Yes| No| Download paused and then retried.| +| SESSION_FAILED7+ | number | Yes| No| Download failure without retry.| +| SESSION_PAUSED7+ | number | Yes| No| Download paused.| +| SESSION_PENDING7+ | number | Yes| No| Download pending.| +| SESSION_RUNNING7+ | number | Yes| No| Download in progress.| +| SESSION_SUCCESSFUL7+ | number | Yes| No| Successful download.| ## request.upload @@ -69,30 +72,36 @@ upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object. | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** ```js - let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; - let data = { name: "name123", value: "123" }; - let header = { key1: "value1", key2: "value2" }; let uploadTask; - request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -106,25 +115,31 @@ upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | -| callback | AsyncCallback<[UploadTask](#uploadtask)> | No | Callback used to return the **UploadTask** object. | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | No| Callback used to return the **UploadTask** object.| **Example** ```js - let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; - let data = { name: "name123", value: "123" }; - let header = { key1: "value1", key2: "value2" }; let uploadTask; - request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -132,8 +147,87 @@ Uploads files. This API uses an asynchronous callback to return the result. uploadTask = data; }); ``` +## request.upload9+ + +upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +Uploads files. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }, + data: { name: "name123", value: "123" }, + }; + request.upload(globalThis.abilityContext, uploadConfig).then((data) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + ``` +## request.upload9+ + +upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void + +Uploads files. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | No| Callback used to return the **UploadTask** object.| + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); + ``` + ## UploadTask Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. @@ -143,7 +237,7 @@ Implements file uploads. Before using any APIs of this class, you must obtain an on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void -Subscribes to the upload progress event. This API uses an asynchronous callback to return the result. +Subscribes to an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -151,17 +245,17 @@ Subscribes to the upload progress event. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **progress** (upload progress). | -| callback | function | Yes | Callback for the upload progress event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes | Size of the uploaded files, in KB. | -| totalSize | number | Yes | Total size of the files to upload, in KB. | +| uploadedSize | number | Yes| Size of the uploaded files, in KB.| +| totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** @@ -177,7 +271,7 @@ Subscribes to the upload progress event. This API uses an asynchronous callback on(type: 'headerReceive', callback: (header: object) => void): void -Subscribes to the **headerReceive** event, which is triggered when an HTTP response header is received. This API uses an asynchronous callback to return the result. +Subscribes to an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -185,16 +279,16 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **'headerReceive'** (response header). | -| callback | function | Yes | Callback for the HTTP Response Header event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| header | object | Yes | HTTP Response Header. | +| header | object | Yes| HTTP Response Header.| **Example** @@ -210,7 +304,7 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void -Unsubscribes from the upload progress event. This API uses an asynchronous callback to return the result. +Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -218,17 +312,17 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (upload progress). | -| callback | function | No | Callback for the upload progress event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback for the upload progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes | Size of the uploaded files, in KB. | -| totalSize | number | Yes | Total size of the files to upload, in KB. | +| uploadedSize | number | Yes| Size of the uploaded files, in KB.| +| totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** @@ -244,7 +338,7 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb off(type: 'headerReceive', callback?: (header: object) => void): void -Unsubscribes from the **headerReceive** event. This API uses an asynchronous callback to return the result. +Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -252,16 +346,16 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'headerReceive'** (response header). | -| callback | function | No | Callback for the HTTP Response Header event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback for the HTTP Response Header event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| header | object | Yes | HTTP Response Header. | +| header | object | Yes| HTTP Response Header.| **Example** @@ -277,7 +371,7 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal remove(): Promise<boolean> -Removes this upload task. This API uses a promise to return the result. +Removes this upload task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -285,9 +379,9 @@ Removes this upload task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed. | +| Promise<boolean> | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed.| **Example** @@ -308,7 +402,7 @@ Removes this upload task. This API uses a promise to return the result. remove(callback: AsyncCallback<boolean>): void -Removes this upload task. This API uses an asynchronous callback to return the result. +Removes this upload task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -316,9 +410,9 @@ Removes this upload task. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** @@ -339,37 +433,42 @@ Removes this upload task. This API uses an asynchronous callback to return the r ## UploadConfig +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Upload -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| url | string | Yes | Resource URL. | -| header | object | Yes | HTTP or HTTPS header added to an upload request. | -| method | string | Yes | Request method, which can be **POST** or **PUT**. The default value is **POST**. | -| files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | +| url | string | Yes| Resource URL.| +| header | object | Yes| HTTP or HTTPS header added to an upload request.| +| method | string | Yes| Request method, which can be **'POST'** or **'PUT'**. The default value is **'POST'**.| +| files | Array<[File](#file)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| +| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| ## File -**System capability**: SystemCapability.MiscServices.Upload +**Required permissions**: ohos.permission.INTERNET -| Name | Type | Mandatory | Description | +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| filename | string | No | File name in the header when **multipart** is used. | -| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | -| type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | +| filename | string | No| File name in the header when **multipart** is used.| +| name | string | No| Name of a form item when **multipart** is used. The default value is **file**.| +| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | +| type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| ## RequestData -**System capability**: SystemCapability.MiscServices.Upload +**Required permissions**: ohos.permission.INTERNET -| Name | Type | Mandatory | Description | +**System capability**: SystemCapability.MiscServices.Download +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes | Name of a form element. | -| value | string | Yes | Value of a form element. | +| name | string | Yes| Name of a form element.| +| value | string | Yes| Value of a form element.| ## request.download @@ -378,21 +477,23 @@ download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result. | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** @@ -412,16 +513,18 @@ download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): v Downloads files. This API uses an asynchronous callback to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | -| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No | Callback used to return the result. | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No| Callback used to return the result.| **Example** @@ -437,7 +540,72 @@ Downloads files. This API uses an asynchronous callback to return the result. }); ``` +## request.download9+ + +download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> + +Downloads files. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Example** + + ```js + let downloadTask; + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + ``` + + +## request.download9+ +download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; + +Downloads files. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No| Callback used to return the result.| + +**Example** + + ```js + let downloadTask; + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); + ``` ## DownloadTask Implements file downloads. @@ -447,7 +615,7 @@ Implements file downloads. on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void -Subscribes to the download progress event. This API uses an asynchronous callback to return the result. +Subscribes to a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -455,17 +623,17 @@ Subscribes to the download progress event. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **'progress'** (download progress). | -| callback | function | Yes | Callback for the download progress event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback for the download progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes | Size of the downloaded files, in KB. | -| totalSize | number | Yes | Total size of the files to download, in KB. | +| receivedSize | number | Yes| Size of the downloaded files, in KB.| +| totalSize | number | Yes| Total size of the files to download, in KB.| **Example** @@ -481,7 +649,7 @@ Subscribes to the download progress event. This API uses an asynchronous callbac off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void -Unsubscribes from the download progress event. This API uses an asynchronous callback to return the result. +Unsubscribes from a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -489,17 +657,17 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (download progress). | -| callback | function | No | Callback for the download progress event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback for the download progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes | Size of the downloaded files, in KB. | -| totalSize | number | Yes | Total size of the files to download, in KB. | +| receivedSize | number | Yes| Size of the downloaded files.| +| totalSize | number | Yes| Total size of the files to download.| **Example** @@ -523,10 +691,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | -| callback | function | Yes | Callback used to return the result. | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| **Example** @@ -542,7 +710,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return off(type: 'complete'|'pause'|'remove', callback?:() => void): void -Unsubscribes from the download event. This API uses an asynchronous callback to return the result. +Unsubscribes from a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -550,10 +718,10 @@ Unsubscribes from the download event. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | -| callback | function | No | Callback used to return the result. | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| **Example** @@ -577,16 +745,16 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the subscribed event. The value is **'fail'** (download failure). | -| callback | function | Yes | Callback for the download task failure event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** @@ -602,7 +770,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal off(type: 'fail', callback?: (err: number) => void): void -Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. +Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -610,16 +778,16 @@ Unsubscribes from the download task failure event. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'fail'** (download failure). | -| callback | function | No | Callback for the download task failure event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback for the download task failure event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** @@ -643,9 +811,9 @@ Removes this download task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return the task removal result. | +| Promise<boolean> | Promise used to return the task removal result.| **Example** @@ -674,9 +842,9 @@ Removes this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the task removal result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** @@ -706,10 +874,9 @@ Queries this download task. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Download **Parameters** - -| Type | Description | -| -------- | -------- | -| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information. | + | Type| Description| + | -------- | -------- | + | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| **Example** @@ -734,9 +901,9 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes | Callback used to return the download task information. | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** @@ -755,7 +922,7 @@ Queries this download task. This API uses an asynchronous callback to return the queryMimeType(): Promise<string> -Queries **MimeType** of this download task. This API uses a promise to return the result. +Queries the **MimeType** of this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -763,9 +930,9 @@ Queries **MimeType** of this download task. This API uses a promise to return th **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return **MimeType** of the download task. | +| Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** @@ -782,7 +949,7 @@ Queries **MimeType** of this download task. This API uses a promise to return th queryMimeType(callback: AsyncCallback<string>): void; -Queries **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -790,9 +957,9 @@ Queries **MimeType** of this download task. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes | Callback used to return **MimeType** of the download task. | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** @@ -819,9 +986,9 @@ Pauses this download task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the download task pause result. | +| Promise<void> | Promise used to return the download task pause result.| **Example** @@ -850,9 +1017,9 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -883,9 +1050,9 @@ Resumes this download task. This API uses a promise to return the result. **Parameters** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise used to return the result.| **Example** @@ -915,9 +1082,9 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -938,34 +1105,39 @@ Resumes this download task. This API uses an asynchronous callback to return the ## DownloadConfig +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| url | string | Yes | Resource URL. | -| header | object | No | HTTP or HTTPS header added to a download request. | -| enableMetered | boolean | No | Download allowed in metered connections. | -| enableRoaming | boolean | No | Download allowed on a roaming network. | -| description | string | No | Description of the download session. | -| filePath7+ | string | No | Download path. (The default path is **'internal://cache/'**.
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | -| networkType | number | No | Network type allowed for download. | -| title | string | No | Title of the download session. | +| url | string | Yes| Resource URL.| +| header | object | No| HTTP or HTTPS header added to a download request.| +| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: yes
**false**: no| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: yes
**false**: no| +| description | string | No| Description of the download session.| +| filePath7+ | string | No| Download path. (The default path is **'internal://cache/'**.)
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files.| +| networkType | number | No| Network type allowed for download.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| title | string | No| Title of the download session.| +| background | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.| ## DownloadInfo7+ +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| downloadId | number | Yes | ID of the downloaded file. | -| failedReason | number | No | Download failure cause, which can be any constant of [ERROR_*](#constants). | -| fileName | string | Yes | Name of the downloaded file. | -| filePath | string | Yes | URI of the saved file. | -| pausedReason | number | No | Reason for session pause, which can be any constant of [PAUSED_*](#constants). | -| status | number | Yes | Download status code, which can be any constant of [SESSION_*](#constants). | -| targetURI | string | Yes | URI of the downloaded file. | -| downloadTitle | string | Yes | Title of the downloaded file. | -| downloadTotalBytes | number | Yes | Total size of the downloaded file (int bytes). | -| description | string | Yes | Description of the file to download. | -| downloadedBytes | number | Yes | Size of the files downloaded (int bytes). | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| downloadId | number | Yes| ID of the downloaded file.| +| failedReason | number | No| Download failure cause, which can be any constant of [ERROR_*](#constants).| +| fileName | string | Yes| Name of the downloaded file.| +| filePath | string | Yes| URI of the saved file.| +| pausedReason | number | No| Reason for session pause, which can be any constant of [PAUSED_*](#constants).| +| status | number | Yes| Download status code, which can be any constant of [SESSION_*](#constants).| +| targetURI | string | Yes| URI of the downloaded file.| +| downloadTitle | string | Yes| Title of the downloaded file.| +| downloadTotalBytes | number | Yes| Total size of the files to download (int bytes).| +| description | string | Yes| Description of the file to download.| +| downloadedBytes | number | Yes| Size of the files downloaded (int bytes).| diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index a546ee0cc3fc95d286b1f2a835998426372c874a..9371381ea8d39f48410d925bd0b28b441f6a9be6 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,6 +1,6 @@ # Settings -This module provides APIs for setting data items. +The **Settings** module provides APIs for setting data items. > **NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 41a4cfc71c77ff92c77b4b16ed19de9af6395bd3..958de3d7d1bb9d7295bedac1c844867160d687ca 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -144,7 +144,7 @@ sim.hasOperatorPrivileges(0, (err, data) => { hasOperatorPrivileges(slotId: number): Promise -Checks whether the application (caller) has been granted the operator permission. This API uses a promise to return the result. +Checks whether the application (caller) has been granted the carrier permission. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -158,7 +158,7 @@ Checks whether the application (caller) has been granted the operator permission | Type | Description | | :----------------- | :---------------------------------------------------------- | -| Promise\ | Promise used to return the result. The value **true** indicates that the application (caller) has been granted the operator permission, and the value **false** indicates the opposite.| +| Promise\ | Promise used to return the result. The value **true** indicates that the application (caller) has been granted the carrier permission, and the value **false** indicates the opposite.| **Example** @@ -184,7 +184,7 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ---------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an ISO country code, for example, **CN** (China).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. which is an ISO country code, for example, **CN** (China).| **Example** @@ -467,7 +467,7 @@ Checks whether the SIM card in the specified slot is installed. This API uses an **Example** -```jsjs +```js sim.hasSimCard(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -522,7 +522,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[IccAccountInfo](#iccaccountinfo7)\> | Yes | Callback used to return the result. | **Example** @@ -555,7 +555,7 @@ This is a system API. | Type | Description | | -------------------------------------------- | ------------------------------------------ | -| Promise<[IccAccountInfo](#IccAccountInfo7)\> | Promise used to return the result.| +| Promise<[IccAccountInfo](#iccaccountinfo7)\> | Promise used to return the result.| **Example** @@ -584,7 +584,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| **Example** @@ -611,7 +611,7 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | ---------------------------------------------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** @@ -646,7 +646,7 @@ This is a system API. **Example** ```js -sim.setDefaultVoiceSlotId(0,(err, data) => { +sim.setDefaultVoiceSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -672,9 +672,9 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -711,7 +711,7 @@ This is a system API. ```js const name='China Mobile'; -sim.setShowName(0, name,(err, data) => { +sim.setShowName(0, name, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -737,15 +737,15 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js const name='China Mobile'; -let promise = sim.setShowName(0,name); +let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -839,8 +839,8 @@ This is a system API. **Example** ```js -let number='+861xxxxxxxxxx'; -sim.setShowNumber(0, number,(err, data) => { +let number = '+861xxxxxxxxxx'; +sim.setShowNumber(0, number, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -869,13 +869,13 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Promise | Promise used to return the result.| **Example** ```js -let number='+861xxxxxxxxxx'; -let promise = sim.setShowNumber(0,number); +let number = '+861xxxxxxxxxx'; +let promise = sim.setShowNumber(0, number); promise.then(data => { console.log(`setShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -994,9 +994,9 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -1057,8 +1057,8 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | +| Type | Description | +| --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -1089,16 +1089,18 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | -| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
- **password**: string
- **state**: [LockState](#LockState8) | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | **Example** ```js -LockInfo.lockType = 1; -LockInfo.password = "1234"; -LockInfo.state = 0; -sim.setLockState(0, LockInfo, (err, data) => { +let lockInfo = { + lockType = 1, + password = "1234", + state = 0 +}; +sim.setLockState(0, lockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1121,21 +1123,23 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
**password**: string
**state**: [LockState](#LockState8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | **Return value** | Type | Description | | ---------------------------------------------------- | -------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -LockInfo.lockType = 1; -LockInfo.password = "1234"; -LockInfo.state = 0; -let promise = sim.setLockState(0, LockInfo); +let lockInfo = { + lockType = 1, + password = "1234", + state = 0 +}; +let promise = sim.setLockState(0, lockInfo); promise.then(data => { console.log(`setLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1158,8 +1162,8 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | --------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\<[LockState](#LockState8)\> | Yes | Callback used to return the result. | -| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| +| callback | AsyncCallback\<[LockState](#lockstate8)\> | Yes | Callback used to return the result. | +| options | [LockType](#locktype8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN 2 lock| **Example** @@ -1185,13 +1189,13 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | --------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| +| options | [LockType](#locktype8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN 2 lock| **Return value** | Type | Description | | ---------------------------------- | -------------------------------------------- | -| Promise<[LockState](#LockState8)\> | Promise used to return the result.| +| Promise<[LockState](#lockstate8)\> | Promise used to return the result.| **Example** @@ -1208,7 +1212,7 @@ promise.then(data => { alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback): void -Changes the PIN. This API uses an asynchronous callback to return the result. +Changes the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1221,14 +1225,14 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | | newPin | string | Yes | New PIN. | | oldPin | string | Yes | Old PIN. | **Example** ```js -sim.alterPin(0, "1234", "0000"(err, data) => { +sim.alterPin(0, "1234", "0000", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1238,7 +1242,7 @@ sim.alterPin(0, "1234", "0000"(err, data) => { alterPin(slotId: number, newPin: string, oldPin: string): Promise; -Changes the PIN. This API uses a promise to return the result. +Changes the PIN of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1258,7 +1262,7 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | --------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** @@ -1275,7 +1279,7 @@ promise.then(data => { alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallback): void -Changes PIN 2. This API uses an asynchronous callback to return the result. +Changes PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1288,7 +1292,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | | newPin2 | string | Yes | New PIN. | | oldPin2 | string | Yes | Old PIN. | @@ -1305,7 +1309,7 @@ sim.alterPin2(0, "1234", "0000", (err, data) => { alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise -Changes PIN 2. This API uses a promise to return the result. +Changes PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1325,12 +1329,12 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | --------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let promise = sim.alterPin2(0, "1234","0000"); +let promise = sim.alterPin2(0, "1234", "0000"); promise.then(data => { console.log(`alterPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1342,7 +1346,7 @@ promise.then(data => { unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void -Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1356,13 +1360,13 @@ This is a system API. | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | pin | string | Yes | PIN of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let pin='1234'; -sim.unlockPin(0, pin,(err, data) => { +let pin = '1234'; +sim.unlockPin(0, pin, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1391,13 +1395,13 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let pin='1234'; -let promise = sim.unlockPin(0,pin); +let pin = '1234'; +let promise = sim.unlockPin(0, pin); promise.then(data => { console.log(`unlockPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1424,14 +1428,14 @@ This is a system API. | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | newPin | string | Yes | New PIN. | | puk | string | Yes | PUK of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let puk='1xxxxxxx'; -let newPin='1235'; -sim.unlockPuk(0, newPin,puk,(err, data) => { +let puk = '1xxxxxxx'; +let newPin = '1235'; +sim.unlockPuk(0, newPin, puk, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1461,14 +1465,14 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let puk='1xxxxxxx'; -let newPin='1235'; -let promise = sim.unlockPuk(0,newPin,puk); +let puk = '1xxxxxxx'; +let newPin = '1235'; +let promise = sim.unlockPuk(0, newPin, puk); promise.then(data => { console.log(`unlockPuk success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1493,14 +1497,14 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| pin2 | string | Yes | PIN 2 of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let pin2='1234'; -sim.unlockPin2(0, pin2,(err, data) => { +let pin2 = '1234'; +sim.unlockPin2(0, pin2, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1523,13 +1527,13 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN of the SIM card. | +| pin2 | string | Yes | PIN 2 of the SIM card. | **Return value** | Type | Description | | ----------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** @@ -1560,16 +1564,16 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| newPin2 | string | Yes | New PIN. | -| puk2 | string | Yes | PUK of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| newPin2 | string | Yes | New PIN 2. | +| puk2 | string | Yes | PUK 2 of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let puk2='1xxxxxxx'; -let newPin2='1235'; -sim.unlockPuk2(0, newPin2,puk2,(err, data) => { +let puk2 = '1xxxxxxx'; +let newPin2 = '1235'; +sim.unlockPuk2(0, newPin2, puk2, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1592,21 +1596,21 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| newPin2 | string | Yes | New PIN. | -| puk2 | string | Yes | PUK of the SIM card. | +| newPin2 | string | Yes | New PIN 2. | +| puk2 | string | Yes | PUK 2 of the SIM card. | **Return value** | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let puk2='1xxxxxxx'; -let newPin2='1235'; -let promise = sim.unlockPuk2(0,newPin2,puk2); +let puk2 = '1xxxxxxx'; +let newPin2 = '1235'; +let promise = sim.unlockPuk2(0, newPin2, puk2); promise.then(data => { console.log(`unlockPuk2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1634,142 +1638,1313 @@ Obtains the number of card slots. console.log("Result: "+ sim.getMaxSimCount()) ``` +## sim.getSimIccId7+ -## SimState +getSimIccId(slotId: number, callback: AsyncCallback): void -Enumerates SIM card states. +Obtains the IC card identity (ICCID) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| --------------------- | ---- | ---------------------------------------------------------- | -| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | -| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the card slot. | -| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | -| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card has been installed but cannot work properly. | -| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card has been installed and is working properly. | -| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| +**Parameters** -## CardType7+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimIccId(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimIccId7+ + +getSimIccId(slotId: number): Promise + +Obtains the ICCID of the SIM card in the specified slot. This API uses a promise to return the result. -Enumerates card types. +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name| Value| Description| -| ----- | ----- | ----- | -|UNKNOWN_CARD | -1 | Unknown| -|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| -|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| -|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| -|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| -|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| -|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| -|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| -|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| -|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| +**Parameters** -## LockType8+ +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -Enumerates lock types. +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimIccId(0); +promise.then(data => { + console.log(`getSimIccId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimIccId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getVoiceMailIdentifier8+ + +getVoiceMailIdentifier(slotId: number, callback: AsyncCallback): void + +Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| -------- | ---- | ----------- | -| PIN_LOCK | 1 | SIM card password lock| -| FDN_LOCK | 2 | Fixed dialing lock | +**Parameters** -## LockState8+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getVoiceMailIdentifier(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` -Enumerates lock states. + +## sim.getVoiceMailIdentifier8+ + +getVoiceMailIdentifier(slotId: number): Promise + +Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| -------- | ---- | ---------- | -| LOCK_OFF | 0 | The lock is off.| -| LOCK_ON | 1 | The lock is on.| +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -## **PersoLockType**8+ +**Return value** -Enumerates personalized lock types. +| Type | Description | +| ---------------- | ------------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getVoiceMailIdentifier(0); +promise.then(data => { + console.log(`getVoiceMailIdentifier success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getVoiceMailIdentifier fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getVoiceMailNumber8+ + +getVoiceMailNumber(slotId: number, callback: AsyncCallback): void + +Obtains the voice mailbox number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| ------------ | ---- | ----------------------------------------------- | -| PN_PIN_LOCK | 0 | Personalized network PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PN_PUK_LOCK | 1 | Personalized network PUK lock. | -| PU_PIN_LOCK | 2 | Personalized network subset PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PU_PUK_LOCK | 3 | Personalized network subset PUK lock. | -| PP_PIN_LOCK | 4 | Personalized service provider PIN lock. For details, see *3GPP TS 22.022 [33]*.| -| PP_PUK_LOCK | 5 | Personalized service provider PUK lock. | -| PC_PIN_LOCK | 6 | Personalized corporate PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PC_PUK_LOCK | 7 | Personalized corporate PUK lock. | -| SIM_PIN_LOCK | 8 | Personalized SIM card PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| SIM_PUK_LOCK | 9 | Personalized SIM card PUK lock. | +**Parameters** -## **LockStatusResponse**7+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | -Defines the lock status response. +**Example** + +```js +sim.getVoiceMailNumber(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getVoiceMailNumber8+ + +getVoiceMailNumber(slotId: number): Promise + +Obtains the voice mailbox number of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ------ | ------------------ | -| result | number | Operation result. | -| remain?: number | number | Remaining attempts (can be null).| +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------ | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getVoiceMailNumber(0); +promise.then(data => { + console.log(`getVoiceMailNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getVoiceMailNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.setVoiceMailInfo8+ -## **LockInfo**8+ +setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: AsyncCallback): void -Defines the personalized lock status response. +Sets voice mailbox information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | --------- | ------ | -| lockType | LockType | Lock type.| -| password | string | Password. | -| state | LockState | Lock state.| +**Parameters** -## **PersoLockInfo**8+ +| Name | Type | Mandatory| Description | +| ---------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| mailName | string | Yes | Voice mailbox name. | +| mailNumber | string | Yes | Voice mailbox number. | +| callback | AsyncCallback | Yes | Callback used to return the result. | -Defines the personalized lock information. +**Example** + +```js +sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.setVoiceMailInfo8+ + +setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string): Promise + +Sets voice mailbox information for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | ------------- | ------------ | -| lockType | PersoLockType | Personalized lock type.| -| password | string | Password. | +**Parameters** -## **IccAccountInfo**7+ +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| mailName | string | Yes | Voice mailbox name. | +| mailNumber | string | Yes | Voice mailbox number. | -Defines the ICC account information. +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com"); +promise.then(data => { + console.log(`setVoiceMailInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setVoiceMailInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getSimTelephoneNumber8+ + +getSimTelephoneNumber(slotId: number, callback: AsyncCallback): void + +Obtains the mobile subscriber ISDN number (MSISDN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------- | ------- | ---------------- | -| simId | number | SIM card ID. | -| slotIndex | number | Card slot ID. | -| isEsim | boolean | Whether the SIM card is an eSim card.| -| isActive | boolean | Whether the card is activated. | -| iccId | string | ICCID number. | -| showName | string | SIM card display name. | -| showNumber | string | SIM card display number. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimTelephoneNumber(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimTelephoneNumber8+ + +getSimTelephoneNumber(slotId: number): Promise + +Obtains the MSISDN of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | -------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimTelephoneNumber(0); +promise.then(data => { + console.log(`getSimTelephoneNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimTelephoneNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getSimGid17+ + +getSimGid1(slotId: number, callback: AsyncCallback): void + +Obtains the group identifier level 1 (GID1) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimGid1(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimGid17+ + +getSimGid1(slotId: number): Promise + +Obtains the GID1 of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimGid1(0); +promise.then(data => { + console.log(`getSimGid1 success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimGid1 fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getIMSI + +getIMSI(slotId: number, callback: AsyncCallback): void + +Obtains the international mobile subscriber identity (IMSI) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getIMSI(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getIMSI + +getIMSI(slotId: number): Promise + +Obtains the IMSI of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getIMSI(0); +promise.then(data => { + console.log(`getIMSI success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getIMSI fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOperatorConfigs8+ + +getOperatorConfigs(slotId: number, callback: AsyncCallback>): void + +Obtains the carrier configuration of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOperatorConfigs(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOperatorConfigs8+ + +getOperatorConfigs(slotId: number): Promise> + +Obtains the carrier configuration of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------------------------------------------- | ----------------------------- | +| Promise> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOperatorConfigs(0); +promise.then(data => { + console.log(`getOperatorConfigs success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOperatorConfigs fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.queryIccDiallingNumbers8+ + +queryIccDiallingNumbers(slotId: number, type: ContactType, callback: AsyncCallback>): void + +Queries contact numbers of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.READ_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.queryIccDiallingNumbers(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.queryIccDiallingNumbers8+ + +queryIccDiallingNumbers(slotId: number, type: ContactType): Promise> + +Queries contact numbers of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.READ_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------ | +| Promise> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.queryIccDiallingNumbers(0, 1); +promise.then(data => { + console.log(`queryIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`queryIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.addIccDiallingNumbers8+ + +addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Adds contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.addIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.addIccDiallingNumbers8+ + +addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Adds contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`addIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.delIccDiallingNumbers8+ + +delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Deletes contact numbers from the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.delIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.delIccDiallingNumbers8+ + +delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Deletes contact numbers from the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`delIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.updateIccDiallingNumbers8+ + +updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Updates contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.updateIccDiallingNumbers8+ + +updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Updates contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`updateIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.sendEnvelopeCmd8+ + +sendEnvelopeCmd(slotId: number, cmd: string, callback: AsyncCallback): void + +Sends an envelope command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Envelope command. | +| callback | AsyncCallback | Yes | Yes | + +**Example** + +```js +sim.sendEnvelopeCmd(0, "ls", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.sendEnvelopeCmd8+ + +sendEnvelopeCmd(slotId: number, cmd: string): Promise + +Sends an envelope command to the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Envelope command. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.sendEnvelopeCmd(0, "ls"); +promise.then(data => { + console.log(`sendEnvelopeCmd success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendEnvelopeCmd fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.sendTerminalResponseCmd8+ + +sendTerminalResponseCmd(slotId: number, cmd: string, callback: AsyncCallback): void + +Sends a terminal response command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Command | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.sendTerminalResponseCmd(0, "ls", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.sendTerminalResponseCmd8+ + +sendTerminalResponseCmd(slotId: number, cmd: string): Promise + +Sends a terminal response command to the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Command | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.sendTerminalResponseCmd(0, "ls"); +promise.then(data => { + console.log(`sendTerminalResponseCmd success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendTerminalResponseCmd fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.unlockSimLock8+ + +unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback): void + +Unlocks the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| lockInfo | [PersoLockInfo](#persolockinfo8) | Yes | Personalized lock information. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | + +**Example** + +```js +let persoLockInfo = { + lockType = 0, + password = "1234" +}; +sim.unlockSimLock(0, persoLockInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.unlockSimLock8+ + +unlockSimLock(slotId: number, lockInfo: PersoLockInfo): Promise + +Unlocks the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| lockInfo | [PersoLockInfo](#persolockinfo8) | Yes | Personalized lock information. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| + +**Example** + +```js +let persoLockInfo = { + lockType = 0, + password = "1234" +}; +let promise = sim.unlockSimLock(0, persoLockInfo); +promise.then(data => { + console.log(`unlockSimLock success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockSimLock fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOpKey9+ + +getOpKey(slotId: number, callback: AsyncCallback): void + +Obtains the opkey of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOpKey(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOpKey9+ + +getOpKey(slotId: number): Promise + +Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOpKey(0); +promise.then(data => { + console.log(`getOpKey success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOpKey fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOpName9+ + +getOpName(slotId: number, callback: AsyncCallback): void + +Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOpName(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOpName9+ + +getOpName(slotId: number): Promise + +Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------ | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOpName(0); +promise.then(data => { + console.log(`getOpName success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOpName fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## SimState + +Enumerates SIM card states. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| --------------------- | ---- | ---------------------------------------------------------- | +| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | +| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the card slot. | +| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | +| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card has been installed but cannot work properly. | +| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card has been installed and is working properly. | +| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| + +## CardType7+ + +Enumerates SIM card types. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name| Value| Description| +| ----- | ----- | ----- | +|UNKNOWN_CARD | -1 | Unknown| +|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| +|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| +|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| +|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| +|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| +|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| +|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| +|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| +|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| + +## LockType8+ + +Enumerates lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ----------- | +| PIN_LOCK | 1 | SIM card password lock.| +| FDN_LOCK | 2 | Fixed dialing lock. | + +## LockState8+ + +Enumerates lock states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ---------- | +| LOCK_OFF | 0 | The lock is off.| +| LOCK_ON | 1 | The lock is on.| + +## PersoLockType8+ + +Enumerates personalized lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ------------ | ---- | ----------------------------------------------- | +| PN_PIN_LOCK | 0 | Personalized network PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PN_PUK_LOCK | 1 | Personalized network PUK lock. | +| PU_PIN_LOCK | 2 | Personalized network subset PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PU_PUK_LOCK | 3 | Personalized network subset PUK lock. | +| PP_PIN_LOCK | 4 | Personalized service provider PIN lock. For details, see *3GPP TS 22.022 [33]*.| +| PP_PUK_LOCK | 5 | Personalized service provider PUK lock. | +| PC_PIN_LOCK | 6 | Personalized corporate PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PC_PUK_LOCK | 7 | Personalized corporate PUK lock. | +| SIM_PIN_LOCK | 8 | Personalized SIM card PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| SIM_PUK_LOCK | 9 | Personalized SIM card PUK lock. | + +## LockStatusResponse7+ + +Defines the lock status response. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------------- | ------ | ------------------ | +| result | number | Operation result. | +| remain?: number | number | Remaining attempts (can be null).| + +## LockInfo8+ + +Defines the lock information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | ------------------------ | ------ | +| lockType | [LockType](#locktype8) | Lock type.| +| password | string | Password. | +| state | [LockState](#lockstate8) | Lock state.| + +## PersoLockInfo8+ + +Defines the personalized lock information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | -------------------------------- | ------------ | +| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.| +| password | string | Password. | + +## IccAccountInfo7+ + +Defines the ICC account information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ---------- | ------- | ---------------- | +| simId | number | SIM card ID. | +| slotIndex | number | Card slot ID. | +| isEsim | boolean | Whether the SIM card is an eSim card.| +| isActive | boolean | Whether the card is activated. | +| iccId | string | ICCID number. | +| showName | string | SIM card display name. | +| showNumber | string | SIM card display number. | + +## OperatorConfig8+ + +Defines the carrier configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description| +| ----- | ------ | ---- | +| field | string | Field| +| value | string | Value | + +## DiallingNumbersInfo8+ + +Defines the contact number information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------ | ------ | -------- | +| alphaTag | string | Alpha tag. | +| number | string | Contact number. | +| recordNumber | number | Record number.| +| pin2 | string | PIN 2.| + +## ContactType8+ + +Enumerates contact types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| :-------------- | ---- | ---------- | +| GENERAL_CONTACT | 1 | Common contact number.| +| FIXED_DIALING | 2 | Fixed dialing number. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 25069b318add375d68d97084e45b08c1f69f3804..fa226f072e2a1c4aa568937455e7ee78e3513469 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -174,7 +174,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -202,7 +202,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| **Return value** @@ -360,7 +360,7 @@ promise.then(data => { hasSmsCapability(): boolean -Checks whether the current device can send and receive SMS messages. This API works in synchronous mode. +Checks whether the current device can send and receive SMS messages. This API returns the result synchronously. **System capability**: SystemCapability.Telephony.SmsMms @@ -375,6 +375,739 @@ let result = sms.hasSmsCapability(); console.log(`hasSmsCapability: ${JSON.stringify(result)}`); ``` +## sms.splitMessage8+ + +splitMessage(content: string, callback: AsyncCallback>): void + +Splits an SMS message into multiple segments. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------------------- | +| content | string | Yes | SMS message content. The value cannot be null.| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +string content= "long message"; +sms.splitMessage(content, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.splitMessage8+ + +splitMessage(content: string): Promise> + +Splits an SMS message into multiple segments. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| content | string | Yes | SMS message content. The value cannot be null.| + +**Return value** + +| Type | Description | +| ----------------------- | ----------------------------------- | +| Promise> | Promise used to return the result.| + +**Example** + +```js +string content = "long message"; +let promise = sms.splitMessage(content); +promise.then(data => { + console.log(`splitMessage success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`splitMessage fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.addSimMessage7+ + +addSimMessage(options: SimMessageOptions, callback: AsyncCallback): void + +Adds a SIM message. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | --------------- | +| options | [SimMessageOptions](#simmessageoptions7) | Yes | SIM message options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let simMessageOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxx", + status = 0 +}; +sms.addSimMessage(simMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.addSimMessage7+ + +addSimMessage(options: SimMessageOptions): Promise + +Adds a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | --------------- | +| options | [SimMessageOptions](#simmessageoptions7) | Yes | SIM message options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let simMessageOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxx", + status = 0 +}; +let promise = sms.addSimMessage(simMessageOptions); +promise.then(data => { + console.log(`addSimMessage success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`addSimMessage fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.delSimMessage7+ + +delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback): void + +Deletes a SIM message. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| msgIndex | number | Yes | Message index. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +let msgIndex = 1; +sms.delSimMessage(slotId, msgIndex, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.delSimMessage7+ + +delSimMessage(slotId: number, msgIndex: number): Promise + +Deletes a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| msgIndex | number | Yes | Message index. | + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let msgIndex = 1; +let promise = sms.delSimMessage(slotId, msgIndex); +promise.then(data => { + console.log(`delSimMessage success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`delSimMessage fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.updateSimMessage7+ + +updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback): void + +Updates a SIM message. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------- | +| options | [UpdateSimMessageOptions](#updatesimmessageoptions7) | Yes | SIM message updating options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let updateSimMessageOptions = { + slotId = 0, + msgIndex = 1, + newStatus = 0, + pdu = "xxxxxxx", + smsc = "test" +}; +sms.updateSimMessage(updateSimMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.updateSimMessage7+ + +updateSimMessage(options: UpdateSimMessageOptions): Promise + +Updates a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------------- | ---- | ------------------- | +| options | [UpdateSimMessageOptions](#updatesimmessageoptions7) | Yes | SIM message updating options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let updateSimMessageOptions = { + slotId = 0, + msgIndex = 1, + newStatus = 0, + pdu = "xxxxxxx", + smsc = "test" +}; +let promise = sms.updateSimMessage(updateSimMessageOptions); +promise.then(data => { + console.log(`updateSimMessage success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`updateSimMessage fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.getAllSimMessages7+ + +getAllSimMessages(slotId: number, callback: AsyncCallback>): void + +Obtains all SIM card messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +sms.getAllSimMessages(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getAllSimMessages7+ + +getAllSimMessages(slotId: number): Promise> + +Obtains all SIM card messages. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ---------------------------------- | +| PromiseArray<[SimShortMessage](#simshortmessage8)\>> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let promise = sms.getAllSimMessages(slotId); +promise.then(data => { + console.log(`getAllSimMessages success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getAllSimMessages fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.setCBConfig7+ + +setCBConfig(options: CBConfigOptions, callback: AsyncCallback): void + +Sets the cell broadcast configuration. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------ | +| options | [CBConfigOptions](#cbconfigoptions8) | Yes | Cell broadcast configuration options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let cbConfigOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxxxx", + status = 0 +}; +sms.setCBConfig(cbConfigOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.setCBConfig7+ + +setCBConfig(options: CBConfigOptions): Promise + +Sets the cell broadcast configuration. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------ | ---- | ------------ | +| options | [CBConfigOptions](#cbconfigoptions8) | Yes | Cell broadcast configuration options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let cbConfigOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxxxx", + status = 0 +}; +let promise = sms.setCBConfig(cbConfigOptions); +promise.then(data => + console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCBConfig fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.getSmsSegmentsInfo8+ + +getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback: AsyncCallback): void + +Obtains SMS message segment information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| message | string | Yes | SMS message. | +| force7bit | boolean | Yes | Whether to use 7-bit coding. | +| callback | AsyncCallback<[SmsSegmentsInfo](# { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getSmsSegmentsInfo8+ + +getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise + +Obtains SMS message segment information. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| message | string | Yes | Message | +| force7bit | boolean | Yes | Whether to use 7-bit coding. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ----------------------------- | +| Promise<[SmsSegmentsInfo](# + console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getSmsSegmentsInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.isImsSmsSupported8+ + +isImsSmsSupported(callback: AsyncCallback): void + +Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +sms.isImsSmsSupported((err, data) => { + console.log(`callback: err->${JSON.(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.isImsSmsSupported8+ + +isImsSmsSupported(): Promise + +Checks whether SMS is supported on IMS. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Return value** + +| Type | Description | +| ---------------------- | ----------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = sms.isImsSmsSupported(); +promise.then(data => { + console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isImsSmsSupported fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.getImsShortMessageFormat8+ + +getImsShortMessageFormat(callback: AsyncCallback): void + +Obtains the SMS format supported by the IMS. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------- | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Example** + +```js +sms.getImsShortMessageFormat((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getImsShortMessageFormat8+ + +getImsShortMessageFormat(): Promise + +Obtains the SMS format supported by the IMS. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Return value** + +| Type | Description | +| --------------------- | -------------------------- | +| Promise<string> | Promise used to return the result. | + +**Example** + +```js +let promise = sms.getImsShortMessageFormat(); +promise.then(data => { + console.log(`getImsShortMessageFormat success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getImsShortMessageFormat fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.decodeMms8+ + +decodeMms(mmsFilePathName: string | Array, callback: AsyncCallback): void + +Decodes MMS messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------- | ---- | -------------- | +| mmsFilePathName | string \|Array | Yes | MMS message file path.| +| callback | AsyncCallback<[MmsInformation](#mmsinformation8)> | Yes | Callback used to return the result. | + +**Example** + +```js +let mmsFilePathName = "filename"; +sms.decodeMms(mmsFilePathName, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.decodeMms8+ + +decodeMms(mmsFilePathName: string | Array): Promise + +Decodes MMS messages. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------- | ---- | -------------- | +| mmsFilePathName | string \|Array | Yes | MMS message file path.| + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | --------------------------- | +| Promise<<[MmsInformation](#mmsinformation8)>> | Promise used to return the result.| + +**Example** + +```js +let mmsFilePathName = "filename"; +let promise = sms.getSmscAddr(mmsFilePathName); +promise.then(data => { + console.log(`decodeMms success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`decodeMms fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.encodeMms8+ + +encodeMms(mms: MmsInformation, callback: AsyncCallback>): void + +Encodes MMS messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ---------- | +| mms | [MmsInformation](#mmsinformation8) | Yes | MMS message information.| +| callback | AsyncCallback<Array> | Yes | Callback used to return the result.| + +**Example** + +```js +let mmsAcknowledgeInd = { + transactionId = "100", + version = 0x10, + reportAllowed = 128 +}; +let mmsInformation = { + messageType = 133, + mmsType = mmsAcknowledgeInd +}; +sms.encodeMms(mmsInformation, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.encodeMms8+ + +encodeMms(mms: MmsInformation): Promise> + +Encodes MMS messages. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------- | ---- | ---------- | +| mms | [MmsInformation](#mmsinformation8) | Yes | MMS message information.| + +**Return value** + +| Type | Description | +| ----------------------------- | ----------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let mmsAcknowledgeInd = { + transactionId = "100", + version = 0x10, + reportAllowed = 128 +}; +let mmsInformation = { + messageType = 133, + mmsType = mmsAcknowledgeInd +}; +let promise = sms.encodeMms(mmsInformation); +promise.then(data => { + console.log(`encodeMms success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`encodeMms fail, promise: err->${JSON.stringify(err)}`); +}); +``` + ## ShortMessage Defines an SMS message instance. @@ -383,7 +1116,7 @@ Defines an SMS message instance. | Name | Type | Description | | ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
TP-Reply-Path: The device returns a response based on the SMSC that sends the SMS message.| +| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| | isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| | isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| | messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. | @@ -464,3 +1197,422 @@ Enumerates SMS message sending results. | SEND_SMS_FAILURE_UNKNOWN | 1 | Failed to send the SMS message due to an unknown reason. | | SEND_SMS_FAILURE_RADIO_OFF | 2 | Failed to send the SMS message because the modem is shut down. | | SEND_SMS_FAILURE_SERVICE_UNAVAILABLE | 3 | Failed to send the SMS message because the network is unavailable or SMS message sending or receiving is not supported.| + + +## MmsInformation8+ + +Defines the MMS message information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | --------- | +| messageType | [MessageType](#messagetype8) | Yes | Message type. | +| mmsType | [MmsSendReq](#mmssendreq8) \|[MmsSendConf](#mmssendconf8) \|[MmsNotificationInd](#mmsnotificationind8) \|[MmsRespInd](#mmsrespind8) \|[MmsRetrieveConf](#mmsretrieveconf8)\|[MmsAcknowledgeInd](#mmsacknowledgeind8)\|[MmsDeliveryInd](#mmsdeliveryind8)\|[MmsReadOrigInd](#mmsreadorigind8)\|[MmsReadRecInd](#mmsreadrecind8)| Yes | PDU header type.| +| attachment | Array<[MmsAttachment](#mmsattachment8)\> | No | Attachment. | + +## MmsSendReq8+ + +Defines an MMS message sending request. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------ | ---- | ------------ | +| from | [MmsAddress](#mmsaddress8) | Yes | MMS message source. | +| transactionId | string | Yes | Transaction ID. | +| contentType | string | Yes | Content type. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| to | Array<[MmsAddress](#mmsaddress8)\> | No | Address to which the message is sent. | +| date | number | No | Date. | +| cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | +| bcc | Array<[MmsAddress](#mmsaddress8)\> | No | Blind carbon copy. | +| subject | string | No | Subject. | +| messageClass | number | No | Message class. | +| expiry | number | No | Expiration. | +| priority | [MmsPriorityType](#mmsprioritytype8) | No | Priority. | +| senderVisibility | number | No | Sender visibility.| +| deliveryReport | number | No | Delivery report. | +| readReport | number | No | Read report. | + +## MmsSendConf8+ + +Defines the MMS message sending configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| responseState | number | Yes | Response status.| +| transactionId | string | Yes | Transaction ID. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| messageId | string | No | Message ID. | + +## MmsNotificationInd8+ + +Defines an MMS notification index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| messageClass | number | Yes | Message class. | +| messageSize | number | Yes | Message size.| +| expiry | number | Yes | Expiration. | +| contentLocation | string | Yes | Content location.| +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| from | [MmsAddress](#mmsaddress8) | No | Source. | +| subject | string | No | Subject. | +| deliveryReport | number | No | Status report.| +| contentClass | number | No | Content class. | + +## MmsAcknowledgeInd8+ + +Defines an MMS confirmation index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| reportAllowed | [ReportType](#reporttype8) | No | Report allowed.| + +## MmsRetrieveConf8+ + +Defines the MMS message retrieval configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| messageId | string | Yes | Message ID. | +| date | number | Yes | Date. | +| contentType | string | Yes | Content type.| +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version | +| from | [MmsAddress](#mmsaddress8) | No | Source. | +| cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | +| subject | string | No | Subject. | +| priority | [MmsPriorityType](#mmsprioritytype8) | No | Priority. | +| deliveryReport | number | No | Status report.| +| readReport | number | No | Read report.| +| retrieveStatus | number | No | Retrieval status.| +| retrieveText | string | No | Retrieval text.| + +## MmsReadOrigInd8+ + +Defines the original MMS message reading index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------- | ---- | -------- | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| messageId | string | Yes | Message ID. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | +| from | [MmsAddress](#mmsaddress8) | Yes | Source. | +| date | number | Yes | Date. | +| readStatus | number | Yes | Read status.| + +## MmsAttachment8+ + +Defines the attachment of an MMS message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------------------------ | ---- | ------------------ | +| contentId | string | Yes | Content ID. | +| contentLocation | string | Yes | Content location. | +| contentDisposition | [DispositionType](#dispositiontype8) | Yes | Content disposition. | +| contentTransferEncoding | string | Yes | Encoding for content transfer. | +| contentType | string | Yes | Content type. | +| isSmil | boolean | Yes | Whether the synchronized multimedia integration language is used.| +| path | string | No | Path. | +| inBuff | Array | No | In the buffer | +| fileName | string | No | File name. | +| charset | [MmsCharSets](#mmscharsets8) | No | Character set. | + +## MmsAddress8+ + +Defines an MMSC address. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------- | ---- | ------ | +| address | string | Yes | MMSC address. | +| charset | [MmsCharSets](#mmscharsets8) | Yes | Character set.| + +## MessageType8+ + +Enumerates message types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ------------------------- | ---- | -------------------- | +| TYPE_MMS_SEND_REQ | 128 | MMS message sending request. | +| TYPE_MMS_SEND_CONF | 129 | MMS message sending configuration. | +| TYPE_MMS_NOTIFICATION_IND | 130 | MMS notification index. | +| TYPE_MMS_RESP_IND | 131 | MMS message response index. | +| TYPE_MMS_RETRIEVE_CONF | 132 | MMS message retrieval configuration. | +| TYPE_MMS_ACKNOWLEDGE_IND | 133 | MMS message acknowledgement index. | +| TYPE_MMS_DELIVERY_IND | 134 | MMS message delivery index. | +| TYPE_MMS_READ_REC_IND | 135 | MMS message reading and receiving index.| +| TYPE_MMS_READ_ORIG_IND | 136 | Original MMS message reading index.| + +## MmsPriorityType8+ + +Enumerates MMS message priorities. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ---------- | ---- | -------------- | +| MMS_LOW | 128 | Low priority. | +| MMS_NORMAL | 129 | Normal priority.| +| MMS_HIGH | 130 | High priority. | + +## MmsVersionType8+ + +Enumerates MMS versions. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| --------------- | ---- | ----------- | +| MMS_VERSION_1_0 | 0x10 | MMS version 1_0.| +| MMS_VERSION_1_1 | 0x11 | MMS version 1_1.| +| MMS_VERSION_1_2 | 0x12 | MMS version 1_2.| +| MMS_VERSION_1_3 | 0x13 | MMS version 1_3.| + +## MmsCharSets8+ + +Enumerates MMS character sets. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| --------------- | ------ | ------------------- | +| BIG5 | 0X07EA | BIG5 format. | +| ISO_10646_UCS_2 | 0X03E8 | ISO_10646_UCS_2 format.| +| ISO_8859_1 | 0X04 | ISO_8859_1 format. | +| ISO_8859_2 | 0X05 | ISO_8859_2 format. | +| ISO_8859_3 | 0X06 | ISO_8859_3 format. | +| ISO_8859_4 | 0X07 | ISO_8859_4 format. | +| ISO_8859_5 | 0X08 | ISO_8859_5 format. | +| ISO_8859_6 | 0X09 | ISO_8859_6 format. | +| ISO_8859_7 | 0X0A | ISO_8859_7 format. | +| ISO_8859_8 | 0X0B | ISO_8859_8 format. | +| ISO_8859_9 | 0X0C | ISO_8859_9 format. | +| SHIFT_JIS | 0X11 | SHIFT_JIS format. | +| US_ASCII | 0X03 | US_ASCII format. | +| UTF_8 | 0X6A | UTF_8 format. | + +## DispositionType8+ + +Enumerates disposition types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ---------- | ---- | -------- | +| FROM_DATA | 0 | Data source.| +| ATTACHMENT | 1 | Attachment. | +| INLINE | 2 | Inlining. | + +## ReportType8+ + +Enumerates report types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description| +| ------- | ---- | ---- | +| MMS_YES | 128 | YES | +| MMS_NO | 129 | NO | + +## CBConfigOptions8+ + +Defines the cell broadcast configuration options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------- | -------------------- | ---- | ------------ | +| slotId | number | Yes | Card slot ID. | +| enable | boolean | Yes | Whether to enable cell broadcast. | +| startMessageId | number | Yes | Start message ID. | +| endMessageId | number | Yes | End message ID. | +| ranType | [RanType](#rantype7) | Yes | RAN type.| + +## SimMessageStatus7+ + +Defines the SIM message status. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ------------------------- | ---- | --------------------------- | +| SIM_MESSAGE_STATUS_FREE | 0 | Free state. | +| SIM_MESSAGE_STATUS_READ | 1 | Read state. | +| SIM_MESSAGE_STATUS_UNREAD | 3 | Unread state. | +| SIM_MESSAGE_STATUS_SENT | 5 | Storage of sent messages (applicable only to SMS).| +| SIM_MESSAGE_STATUS_UNSENT | 7 | Storage of unsent messages (applicable only to SMS).| + +## RanType7+ + +Enumerates RAN types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description| +| --------- | ---- | ---- | +| TYPE_GSM | 1 | GSM | +| TYPE_CDMA | 2 | CMDA | + +## SmsEncodingScheme8+ + +Enumerates SMS encoding schemes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| SMS_ENCODING_UNKNOWN | 0 | Unknown code.| +| SMS_ENCODING_7BIT | 1 | 7-digit code. | +| SMS_ENCODING_8BIT | 2 | 8-digit code. | +| SMS_ENCODING_16BIT | 3 | 16-digit code.| + +## SimMessageOptions7+ + +Defines the SIM message options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | -------------- | +| slotId | number | Yes | Card slot ID. | +| smsc | string | Yes | Short message service center.| +| pdu | string | Yes | Protocol data unit. | +| status | [SimMessageStatus](#simmessagestatus7) | Yes | Message status. | + +## UpdateSimMessageOptions7+ + +Defines the updating SIM message options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | -------------- | +| slotId | number | Yes | Card slot ID. | +| msgIndex | number | Yes | Message index. | +| newStatus | [SimMessageStatus](#simmessagestatus7) | Yes | New status. | +| pdu | string | Yes | Protocol data unit. | +| smsc | string | Yes | Short message service center.| + +## SimShortMessage8+ + +Defines a SIM message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------- | ---- | ------------- | +| shortMessage | [ShortMessage](#shortmessage) | Yes | SMS message. | +| simMessageStatus | [SimMessageStatus](#simmessagestatus7) | Yes | SIM message status.| +| indexOnSim | number | Yes | SIM card index. | + +## MmsDeliveryInd8+ + +Defines an MMS message delivery index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------- | ---- | ------ | +| messageId | string | Yes | Message ID.| +| date | number | Yes | Date. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent.| +| status | number | Yes | Status. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | + +## MmsRespInd8+ + +Defines an MMS response index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Event ID. | +| status | number | Yes | Status. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| reportAllowed | [ReportType](#reporttype8) | No | Report allowed.| + +## SmsSegmentsInfo8+ + +Defines the SMS message segment information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------------- | ---------------------------------------- | ---- | ------------ | +| splitCount | number | Yes | Split count. | +| encodeCount | number | Yes | Encoding count. | +| encodeCountRemaining | number | Yes | Remaining encoding count.| +| scheme | [SmsEncodingScheme](#smsencodingscheme8) | Yes | Encoding scheme.| diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 4a711c1f7cbf0defdbcd9ea0c28a08e981c594a9..7d8018a4e82916df0c218a10ca7d5e8fdb9e6364 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -79,7 +79,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -106,7 +106,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| **Return value** @@ -274,7 +274,7 @@ promise.then((data) => { isCellularDataRoamingEnabled(slotId: number, callback: AsyncCallback\): void -Checks whether roaming is enabled for the cellular data service. This API uses an asynchronous callback to return the result. +Checks whether the cellular data roaming service is enabled. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -285,7 +285,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled. | **Example** @@ -299,7 +299,7 @@ data.isCellularDataRoamingEnabled(0,(err, data) => { isCellularDataRoamingEnabled(slotId: number): Promise\ -Checks whether roaming is enabled for the cellular data service. This API uses a promise to return the result. +Checks whether the cellular data roaming service is enabled. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -315,7 +315,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| +| Promise\ | Promise used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled.| **Example** @@ -328,6 +328,241 @@ promise.then((data) => { }); ``` +## data.enableCellularData + +enableCellularData(callback: AsyncCallback): void + +Enables the cellular data service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +data.enableCellularData((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.enableCellularData + +enableCellularData(): Promise + +Enables the cellular data service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.enableCellularData(); +promise.then((data) => { + console.log(`enableCellularData success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`enableCellularData fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.disableCellularData + +disableCellularData(callback: AsyncCallback): void + +Disables the cellular data service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +data.disableCellularData((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.disableCellularData + +disableCellularData(): Promise + +Disables the cellular data service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| --------------- | --------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.disableCellularData(); +promise.then((data) => { + console.log(`disableCellularData success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`disableCellularData fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.enableCellularDataRoaming + +enableCellularDataRoaming(slotId: number, callback: AsyncCallback): void + +Enables the cellular data roaming service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +data.enableCellularDataRoaming(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.enableCellularDataRoaming + +enableCellularDataRoaming(slotId: number): Promise + +Enables the cellular data roaming service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.enableCellularDataRoaming(0); +promise.then((data) => { + console.log(`enableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`enableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.disableCellularDataRoaming + +disableCellularDataRoaming(slotId: number, callback: AsyncCallback): void + +Disables the cellular data roaming service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +data.disableCellularDataRoaming(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.disableCellularDataRoaming + +disableCellularDataRoaming(slotId: number): Promise + +Disables the cellular data roaming service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.disableCellularDataRoaming(0); +promise.then((data) => { + console.log(`disableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`disableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## DataFlowType Defines the cellular data flow type. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 71b0490ea8c610dc0169222042ec7770c19d0a83..82932c99be0a0c8c39ab989d656cb6b0fcde99f5 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -26,6 +26,7 @@ Obtains the USB device list. | Array<Readonly<[USBDevice](#usbdevice)>> | Device information list. | - **Example** + ```js let devicesList = usb.getDevices(); console.log(`devicesList = ${JSON.stringify(devicesList)}`); @@ -93,16 +94,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | device | [USBDevice](#usbdevice) | Yes| USB device information. | - **Return value** + | Type| Description| | -------- | -------- | | Readonly<[USBDevicePipe](#usbdevicepipe)> | USB device pipe for data transfer. | - **Example** + ```js let devicepipe= usb.connectDevice(device); console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); @@ -118,16 +122,19 @@ Checks whether the application has the permission to access the device. **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name. | - **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise. | - **Example** + ```js let devicesName="1-1"; let bool = usb.hasRight(devicesName); @@ -144,16 +151,19 @@ Requests the temporary permission for the application to access the USB device. **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<boolean> | Returns **true** if the temporary device access permissions are granted; returns **false** otherwise. | - **Example** + ```js let devicesName="1-1"; usb.requestRight(devicesName).then((ret) => { @@ -172,6 +182,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | @@ -179,11 +190,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise. | - **Example** + ```js let ret = usb.claimInterface(devicepipe, interfaces); console.log(`claimInterface = ${ret}`); @@ -201,17 +214,20 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully released; returns an error code otherwise. | - **Example** + ```js let ret = usb.releaseInterface(devicepipe, interfaces); console.log(`releaseInterface = ${ret}`); @@ -229,17 +245,20 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | config | [USBConfig](#usbconfig) | Yes| USB configuration to set. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise. | - **Example** + ```js let ret = usb.setConfiguration(devicepipe, config); console.log(`setConfiguration = ${ret}`); @@ -256,17 +275,20 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | iface | [USBInterface](#usbinterface) | Yes| USB interface to set. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully set; returns an error code otherwise. | - **Example** + ```js let ret = usb.setInterface(devicepipe, interfaces); console.log(`setInterface = ${ret}`); @@ -284,16 +306,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | - **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Raw descriptor data. The value **undefined** indicates that the operation has failed. | - **Example** + ```js let ret = usb.getRawDescriptor(devicepipe); ``` @@ -310,16 +335,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | - **Return value** + | Type| Description| | -------- | -------- | | number | File descriptor of the USB device. The value **-1** indicates that the operation has failed. | - **Example** + ```js let ret = usb.getFileDescriptor(devicepipe); ``` @@ -336,6 +364,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device. | @@ -343,11 +372,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs. | - **Example** + ```js usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { console.log(`controlTransfer = ${JSON.stringify(ret)}`); @@ -366,6 +397,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device. | @@ -374,11 +406,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs. | - **Example** + ```js // Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. @@ -400,16 +434,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise. | - **Example** + ```js let ret = usb.closePipe(devicepipe); console.log(`closePipe = ${ret}`); @@ -556,3 +593,68 @@ Enumerates request directions. | -------- | -------- | -------- | | USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device. | | USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host. | + +## FunctionType9+ + +Enumerates function types for the USB device. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------------ | ---- | ---------- | +| NONE | 0 | No function.| +| ACM | 1 | ACM function. | +| ECM | 2 | ECM function. | +| HDC | 4 | HDC function. | +| MTP | 8 | Not supported currently.| +| PTP | 16 | Not supported currently.| +| RNDIS | 32 | Not supported currently.| +| MIDI | 64 | Not supported currently.| +| AUDIO_SOURCE | 128 | Not supported currently.| +| NCM | 256 | Not supported currently.| + +## PortModeType9+ + +Enumerates USB port mode types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| --------- | ---- | ---------------------------------------------------- | +| NONE | 0 | None. | +| UFP | 1 | Upstream facing port, which functions as the sink of power supply. | +| DFP | 2 | Downstream facing port, which functions as the source of power supply. | +| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| +| NUM_MODES | 4 | Not supported currently. | + +## PowerRoleType9+ + +Enumerates power role types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ---------- | +| NONE | 0 | None. | +| SOURCE | 1 | External power supply.| +| SINK | 2 | Internal power supply.| + +## DataRoleType9+ + +Enumerates data role types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ------------ | +| NONE | 0 | None. | +| HOST | 1 | USB host.| +| DEVICE | 2 | USB device.| diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index a4f2af80b8fcd1c922fd021adef5cff0d8eb409d..b02f86a0da6ad041fac054cd5faf003c98755bbb 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -1,722 +1,169 @@ -# picker +# picker -The **** component supports common, date, time, data and time, and multi-column text selectors. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component supports common, date, time, data and time, and multi-column text selectors. -None -## Child Component +## Required Permissions None -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

-

-

No

-

Dynamic modification is not supported. Available values include:

-
  • text: text selector
  • data: date selector
  • time: time selector
  • datetime: date and time selector
  • multi-text: multi-column text selector
-
- -### Text Selector - -When **type** is set to **text**, a text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

range

-

Array

-

-

-

No

-

Value range of the common selector, for example, ["15", "20", "25"].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: ["15", "20", "25"] in the JavaScript.

-
-

selected

-

string

-

0

-

No

-

Default value of the common selector. The value should be the index of range.

-

value

-

string

-

-

-

No

-

Value of the common selector.

-
- -### Date Selector - -When **type** is set to **date**, a date selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

start

-

<time>

-

1970-1-1

-

No

-

Start date of the date selector, in the format of YYYY-MM-DD.

-

end

-

<time>

-

2100-12-31

-

No

-

End date of the date selector, in the format of YYYY-MM-DD.

-

selected

-

string

-

Current date

-

No

-

Default value of the date selector, in format of YYYY-MM-DD.

-

value

-

string

-

-

-

Yes

-

Value of the date selector.

-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Time Selector - -When **type** is set to **time**, a time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

containsecond

-

boolean

-

false

-

No

-

Whether seconds are contained.

-

selected

-

string

-

Current time

-

No

-

Default value of the time selector, in the format of HH:mm. If seconds are contained, the format is HH:mm:ss.

-

value

-

string

-

-

-

No

-

Value of the time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-
- -### Date and Time Selector - -When **type** is set to **datetime**, a date and time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

selected

-

string

-

Current date and time

-

No

-

Default value of the date and time selector. The value can be in either of the following formats:

-
  • MM-DD-HH-mm
  • YYYY-MM-DD-HH-mm
-

If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.

-

value

-

string

-

-

-

Yes

-

Value of the date and time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the date and time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Multi-Column Text Selector - -When **type** is set to **multi-text**, a multi-column text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

columns

-

number

-

-

-

Yes

-

Number of columns in the multi-column text selector.

-

range

-

Two-dimensional array

-

-

-

No

-

Items of the multi-column text selector. range is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, [["a","b"], ["c","d"]].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: [["a","b"], ["c","d"]] in the JavaScript.

-
-

selected

-

Array

-

0,0,0,...

-

No

-

Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.

-

value

-

Array

-

-

-

No

-

Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column.

-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

text-color

-

<color>

-

-

-

No

-

Text color of the selector.

-

font-size

-

<length>

-

-

-

No

-

Font size of the selector.

-

allow-scale

-

boolean

-

true

-

No

-

Whether the font size changes with the system's font size settings.

-
NOTE:

If the config-changes tag of fontSize is configured for abilities in the config.json file, the setting takes effect without application restart.

-
-

letter-spacing

-

<length>

-

0

-

No

-

Letter spacing of the selector. For details, see letter-spacing of the text component.

-

text-decoration

-

string

-

-

-

No

-

Text decoration of the selector. For details, see text-decoration of the text component.

-

font-style

-

string

-

normal

-

No

-

Font style of the selector. For details, see font-style of the text component.

-

font-weight

-

number | string

-

normal

-

No

-

Font weight of the selector. For details, see font-weight of the text component.

-

font-family

-

string

-

sans-serif

-

No

-

Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by Custom Font Styles in the family is selected as the font for the text.

-

line-height

-

<length>

-

0px

-

No

-

Text line height of the selector.

-

column-height5+

-

<length>

-

-

-

No

-

Height of the selector option list.

-
NOTE:

-
-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - -### Common Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: newValue, newSelected: newSelected }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. newSelected is the index.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-
NOTE:

The value of month ranges from 0 (January) to 11 (December). 5+

-
-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date and Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day, hour: hour, minute: minute}

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ hour: hour, minute: minute, [second: second] }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. If containsecond is set to true, value contains seconds.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Multi-Column Text Selector - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] }

-

Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.

-
  • newValue is an array consisting of the values of the selected items.
  • newSelected is an array consisting of the indexes of the selected items. The lengths of newValue and newSelected are the same as the length of range.
-

columnchange

-

{ column: column, newValue: newValue, newSelected: newSelected }

-

Triggered when the value of a column in the multi-column selector changes.

-
  • column indicates the column whose value has changed.
  • newValue indicates the selected value.
  • newSelected indicates the index of the selected value.
-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -## Methods - -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

show

-

-

-

Displays the picker.

-
- -## Example Code -``` +## Child Components + +Not supported + + +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | - | No | Picker type. Dynamic modification is not supported. The options are as follows:
- **text**: text selector.
- **date**: date selector.
- **time**: time selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| + + +### Common Selector + +When **type** is set to **text**, a common selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------ | ---- | ---- | ---------------------------------------- | +| range | Array | - | No | Value range of the common selector, for example, **["15", "20", "25"]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | string | 0 | No | Default value of the common selector. The value should be the index of **range**.| +| value | string | - | No | Value of the common selector. | + + +### Date Selector + +When **type** is set to **date**, a date selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | +| start | <time> | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. | +| end | <time> | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. | +| selected | string | Current date | No | Default value of the date selector, in format of YYYY-MM-DD.| +| value | string | - | Yes | Value of the date selector. | +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Time Selector + +When **type** is set to **time**, a time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| containsecond | boolean | false | No | Whether seconds are contained. | +| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. | +| value | string | - | No | Value of the time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| + + +### Date and Time Selector + +When **type** is set to **datetime**, a date and time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in either of the following formats:
- MM-DD-HH-mm
- YYYY-MM-DD-HH-mm
If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| +| value | string | - | Yes | Value of the date and time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Multi-Column Text Selector + +When **type** is set to **multi-text**, a multi-column text selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | --------- | ---- | ---------------------------------------- | +| columns | number | - | Yes | Number of columns in the multi-column text selector. | +| range | Two-dimensional array| - | No | Items of the multi-column text selector. **range** is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a", "b"], ["c", "d"]]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | Array | [0,0,0, ...]| No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.| +| value | Array | - | No | Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column. | + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| -------------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| text-color | <color> | - | No | Text color of the selector. | +| font-size | <length> | - | No | Font size of the selector. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| letter-spacing | <length> | 0 | No | Letter spacing of the selector. For details, see **letter-spacing** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| text-decoration | string | - | No | Text decoration of the selector. For details, see **text-decoration** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-style | string | normal | No | Font style of the selector. For details, see **font-style** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-weight | number \| string | normal | No | Font weight of the selector. For details, see **font-weight** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| line-height | <length> | 0px | No | Text line height of the selector. | +| column-height5+ | <length> | - | No | Height of the selector option list. | + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + + +### Common Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: newValue, newSelected: newSelected } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. **newSelected** is the index.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { year: year, month: month, day: day } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
The value of **month** ranges from **0** (January) to **11** (December) since API version 5.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date and Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------- | +| change | { year: year, month: month, day: day, hour: hour, minute: minute} | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { hour: hour, minute: minute, [second: second] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. If **containsecond** is set to true, value contains seconds.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Multi-Column Text Selector + +| Name | Parameter | Description | +| ------------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
- **newValue** is an array consisting of the values of the selected items.
- **newSelected** is an array consisting of the indexes of the selected items. The lengths of **newValue** and **newSelected** are the same as the length of **range**.| +| columnchange | { column: column, newValue: newValue, newSelected: newSelected } | Triggered when the value of a column in the multi-column selector changes.
- **column**: column whose value has changed.
- **newValue**: selected value.
- **newSelected**: index of the selected value.| +| cancel | - | Triggered when the cancel button is clicked. | + + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ---- | ---- | --------------- | +| show | - | Shows the picker.| + + +## Example + +```html
+ + +
+``` + + +```css +/* xxx.css */ +.content{ + width: 100%; + height: 200px; + justify-content: center; + align-items: center; +} +``` + + +```json +{ + "actions": { + "onRadioChange":{ + "action": "message", + "params": { + "checkedRadio": "$event.checkedItem" + } + } + } +} +``` +**4*4卡片** + +![卡片input](figures/input.gif) + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-progress.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-progress.md new file mode 100644 index 0000000000000000000000000000000000000000..dab0e8bb88655c52cf542e08721b78c66c8fcc6a --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-progress.md @@ -0,0 +1,122 @@ +# progress + + +进度条,用于显示内容加载或操作的处理进度。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +不支持。 + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| type | string | horizontal | 否 | 设置进度条的类型,该属性不支持动态修改,可选值为:
- horizontal:线性进度条。
- circular:loading样式进度条。
- ring:圆环形进度条。
- scale-ring:带刻度圆环形进度条。
- arc:弧形进度条。
- eclipse:圆形进度条,展现类似月圆月缺的进度展示效果。 | + +不同类型的进度条还支持不同的属性: + +- 类型为horizontal、ring、scale-ring时,支持如下属性: + | 名称 | 类型 | 默认值 | 必填 | 描述 | + | -------- | -------- | -------- | -------- | -------- | + | percent | number | 0 | 否 | 当前进度。取值范围为0-100。 | + | secondarypercent(Rich) | number | 0 | 否 | 次级进度。取值范围为0-100。 | + +- 类型为ring、scale-ring时,支持如下属性: + | 名称 | 类型 | 默认值 | 必填 | 描述 | + | -------- | -------- | -------- | -------- | -------- | + | clockwise | boolean | true | 否 | 圆环形进度条是否采用顺时针。 | + +- 类型为arc、eclipse时,支持如下属性: + | 名称 | 类型 | 默认值 | 必填 | 描述 | + | -------- | -------- | -------- | -------- | -------- | + | percent | number | 0 | 否 | 当前进度。取值范围为0-100。 | + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +type=horizontal + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> | \#ff007dff | 否 | 设置进度条的颜色。 | +| stroke-width | <length> | 4px | 否 | 设置进度条的宽度。 | +| background-color | <color> | - | 否 | 设置进度条的背景色。 | +| secondary-color | <color> | - | 否 | 设置次级进度条的颜色。 | + +type=circular + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> | - | 否 | loading进度条上的圆点颜色。 | + +type=ring, scale-ring + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> \| <linear-gradient> | - | 否 | 环形进度条的颜色,ring类型支持线性渐变色设置。
线性渐变色仅支持两个颜色参数设置格式,如color = linear-gradient(\#ff0000, \#00ff00)。 | +| background-color | <color> | - | 否 | 环形进度条的背景色。 | +| secondary-color | <color> | - | 否 | 环形次级进度条的颜色。 | +| stroke-width | <length> | 10px | 否 | 环形进度条的宽度。 | +| scale-width | <length> | - | 否 | 带刻度的环形进度条的刻度粗细,类型为scale-ring生效。 | +| scale-number | number | 120 | 否 | 带刻度的环形进度条的刻度数量,类型为scale-ring生效。 | + +type=arc + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> | - | 否 | 弧形进度条的颜色。 | +| background-color | <color> | - | 否 | 弧形进度条的背景色。 | +| stroke-width | <length> | - | 否 | 弧形进度条的宽度。
进度条宽度越大,进度条越靠近圆心。即进度条始终在半径区域内。 | +| start-angle | <deg> | 240 | 否 | 弧形进度条起始角度,以时钟0点为基线。范围为0到360(顺时针)。 | +| total-angle | <deg> | 240 | 否 | 弧形进度条总长度,范围为-360到360,负数标识起点到终点为逆时针。 | +| center-x | <length> | - | 否 | 弧形进度条中心位置,(坐标原点为组件左上角顶点)。该样式需要和center-y和radius一起。 | +| center-y | <length> | - | 否 | 弧形进度条中心位置,(坐标原点为组件左上角顶点)。该样式需要和center-x和radius一起。 | +| radius | <length> | - | 否 | 弧形进度条半径,该样式需要和center-x和center-y一起。 | + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + +```html + +
+ + + + +
+``` + + +```css +/* xxx.css */ +.container { + flex-direction: column; + height: 100%; + width: 100%; + align-items: center; +} +.min-progress { + width: 300px; + height: 300px; +} +``` +**4*4卡片** + +![progress](figures/progress.png) + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-span.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-span.md new file mode 100644 index 0000000000000000000000000000000000000000..cd221afedbcecb0f1858dc4945c18039b23f4f81 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-span.md @@ -0,0 +1,41 @@ +# span + + +作为<[text](js-service-widget-basic-text.md)>子组件提供文本修饰能力。 + + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + + +## 子组件 + +支持子组件[\](js-service-widget-basic-span.md)。 + + +## 属性 + +支持[通用属性](js-service-widget-common-attributes.md)。 + + +## 样式 + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> | - | 否 | 设置文本段落的文本颜色。 | +| font-size | <length> | 30px | 否 | 设置文本段落的文本尺寸。 | +| font-style | string | normal | 否 | 设置文本段落的字体样式,见[text组件font-style的样式属性](js-service-widget-basic-text.md#样式)。 | +| font-weight | number \| string | normal | 否 | 设置文本段落的字体粗细,见[text组件font-weight的样式属性](js-service-widget-basic-text.md#样式)。 | +| text-decoration | string | none | 否 | 设置文本段落的文本修饰,见[text组件text-decoration样式属性](js-service-widget-basic-text.md#样式)。 | +| font-family | string | sans-serif | 否 | 设置文本段落的字体列表,用逗号分隔,每个字体用字体名或者字体族名设置。列表中第一个系统中存在的或者通过[自定义字体](js-service-widget-common-customizing-font.md)指定的字体,会被选中作为文本的字体。 | + + +## 事件 + +不支持。 + +## 示例 + +详见[text示例](js-service-widget-basic-text.md#示例)。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-text.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-text.md new file mode 100644 index 0000000000000000000000000000000000000000..f96d625c8a3f7c98fdbaeb6ef25b43de3f442de4 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-text.md @@ -0,0 +1,111 @@ +# text + + +文本,用于呈现一段信息。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +支持<[span](js-service-widget-basic-span.md)>。 + + +## 属性 + +支持[通用属性](js-service-widget-common-attributes.md)。 + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| color | <color> | - | 否 | 设置文本的颜色。 | +| font-size | <length> | 30px | 否 | 设置文本的尺寸。 | +| letter-spacing | <length> | 0px | 否 | 设置文本的字符间距。 | +| font-style | string | normal | 否 | 设置文本的字体样式,可选值为:
- normal:标准的字体样式;
- italic:斜体的字体样式。 | +| font-weight | number \| string | normal | 否 | 设置文本的字体粗细,number类型取值[100, 900],默认为400,取值越大,字体越粗。
- number取值必须为100的整数倍。
- string类型取值支持如下四个值:lighter、normal、bold、bolder。 | +| text-decoration | string | none | 否 | 设置文本的文本修饰,可选值为:
- underline:文字下划线修饰;
- line-through:穿过文本的修饰线n
- none:标准文本。 | +| text-align | string | start | 否 | 设置文本的文本对齐方式,可选值为:
- left:文本左对齐;
- center:文本居中对齐;
- right:文本右对齐;
- start:根据文字书写相同的方向对齐;
- end:根据文字书写相反的方向对齐。
 如文本宽度未指定大小,文本的宽度和父容器的宽度大小相等的情况下,对齐效果可能会不明显。 | +| line-height | <length> | 0px | 否 | 设置文本的文本行高,设置为0px时,不限制文本行高,自适应字体大小。 | +| text-overflow | string | clip | 否 | 在设置了最大行数的情况下生效,可选值为:
- clip:将文本根据父容器大小进行裁剪显示;
- ellipsis:根据父容器大小显示,显示不下的文本用省略号代替。需配合max-lines使用。 | +| font-family | string | sans-serif

| 否 | 设置文本的字体列表,用逗号分隔,每个字体用字体名或者字体族名设置。列表中第一个系统中存在的或者通过[自定义字体](js-service-widget-common-customizing-font.md)指定的字体,会被选中作为文本的字体。 | +| max-lines | number | - | 否 | 设置文本的最大行数。 | +| min-font-size | <length> | - | 否 | 文本最小字号,需要和文本最大字号同时设置,支持文本字号动态变化。设置最大最小字体样式后,font-size不生效。 | +| max-font-size | <length> | - | 否 | 文本最大字号,需要和文本最小字号同时设置,支持文本字号动态变化。设置最大最小字体样式后,font-size不生效。 | +| font-size-step | <length> | 1px | 否 | 文本动态调整字号时的步长,需要设置最小,最大字号样式生效。 | +| prefer-font-sizes | <array> | - | 否 | 预设的字号集合,在动态尺寸调整时,优先使用预设字号集合中的字号匹配设置的最大行数,如果预设字号集合未设置,则使用最大最小和步长调整字号。针对仍然无法满足最大行数要求的情况,使用text-overflow设置项进行截断,设置预设尺寸集后,font-size、max-font-size、min-font-size和font-size-step不生效。
如:prefer-font-sizes: 12px,14px,16px | +| word-break | string | normal | 否 | 设置文本折行模式,可选值为:
- normal:默认换行规则,依据各自语言的规则,允许在字间发生换行。
- break-all:对于非中文/日文/韩文的文本,可在任意字符间断行。
- break-word:与break-all相同,不同的地方在于它要求一个没有断行破发点的词必须保持为一个整体单位。 | + +> **说明:** +> - 字体动态缩放:预设尺寸集合和最小最大字号调节基于是否满足最大行数要求,预设尺寸集合会按照从左到右顺序查看是否满足最大行数要求,最小最大字号调节则基于从大到小顺序查看是否满足最大行数要求。 +> +> - 文本换行:文本可以通过转义字符\r\n进行换行。 +> +> - 文本标签内支持以下转义字符:\a,\b,\f,\n,\r,\t,\v,\',\",\0。 +> +> - 当使用子组件span组成文本段落时,如果span属性样式异常,将导致text段落无法显示。 +> +> - letter-spacing、text-align、line-height、text-overflow和max-lines样式作用于text及其子组件(span)组成的文本内容。 +> +> - text组件说明:不支持text内同时存在文本内容和span子组件。(如果同时存在,只显示span内的内容) + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + +## 示例 + +```html +
+ + 这是设置了行高的文本。 + + 这是设置了字符间距的文本。 + 这是设置为斜体的文本。 + 这是添加了下划线的文本。 + 文本过长可省略,省略文本。 +
+``` + +```css +.container{ + flex-direction: column; + width: 100%; + height: 100%; + margin-top: 10px; + margin-left: 30px; +} +.line_height{ + font-size: 20px; + line-height: 40px; +} +.letter_spacing{ + font-size: 20px; + letter-spacing: 5px; +} +.font_style{ + font-size: 20px; + font-style: italic; +} +.text_decoration_style{ + font-size: 20px; + text-decoration: underline; + text-decoration-color: red; +} +.text_over_flow{ + font-size: 20px; + width: 40%; + max-lines: 1; + text-overflow: ellipsis; +} +``` + +**4*4卡片** + +![progress](figures/text.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-accessibility.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-accessibility.md new file mode 100644 index 0000000000000000000000000000000000000000..19c0e92894a0255bf28a7adf39acfcadc0423be7 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-accessibility.md @@ -0,0 +1,61 @@ +# 无障碍 + +组件可以设置相应的无障碍属性和事件来更好地使用无障碍能力。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 无障碍属性 + +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| accessibilitygroup | boolean | false | 无障碍组,设置为true时表示该组件及其所有子组件为一整个可以选中的组件,无障碍服务将不再关注其子组件内容。 | +| accessibilitytext | string | - | 无障碍文本,当组件不包含文本属性时,屏幕朗读选中此组件时不播报,使用者无法清楚地知道当前选中了什么组件。为了解决此场景,开发人员可为不包含文字信息的组件设置无障碍文本,当屏幕朗读选中此组件时播报无障碍文本的内容,帮助屏幕朗读的使用者清楚地知道自己选中了什么组件。若组件既拥有文本属性,又拥有无障碍文本属性,则组件被选中时,仅播报无障碍文本内容。 | +| accessibilitydescription | string | - | 无障碍说明,用于为用户进一步说明当前组件,如帮助用户理解将要执行的操作可能导致什么后果,尤其是当这些后果无法从组件本身属性与无障碍文本中了解到时。开发人员可为组件的该属性设置相对较详细的解释文本,帮助用户理解将要执行的操作。若组件既拥有文本属性又拥有无障碍说明属性,则组件被选中时,先播报组件的文本属性,再播报无障碍说明属性的内容。 | +| accessibilityimportance | string | auto | 无障碍重要性,用于控制某个组件是否可被无障碍辅助服务所识别。具体值可以设置为auto,yes,no和no-hide-descendants(最后一个值会使屏幕朗读忽略当前组件及其所有子组件)。若设置为yes,当前组件对无障碍辅助服务而言可选中;若设置为no,则当前组件对无障碍辅助服务来说是不可选中的。 | + +- accessibilitygroup + + ```html +
+ text1 + text2 +
+ ``` + +- accessibilitytext + + ```html + + ``` + +- accessibilitydescription + + ```html + + ``` + +- accessibilityimportance + 此情况下,div和text都不会被无障碍框选中。若想让某些默认不会被无障碍框选中的组件可以被选中,则给该组件增加一个accessibilityimportance="yes"即可。 + + + ```html +
+ text +
+ ``` + + +## 无障碍事件 + +| 名称 | 参数 | 描述 | +| -------- | -------- | -------- | +| accessibility | AbilityEvent | 无障碍服务下发的事件。 | + + **表1**AbilityEvent属性列表 + +| 属性 | 类型 | 说明 | +| -------- | -------- | -------- | +| eventType | number | 事件类型:
- 0:custom event
- 1:accessibility focus
- 2:clear accessibility focus
无障碍系统下发的非焦点相关的事件为0,无障碍系统下发的获焦事件为1,无障碍系统下发的失焦事件为2。 | +| param | Object | 无障碍辅助应用发送自定义事件时需传入对应参数。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-atomic-layout.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-atomic-layout.md new file mode 100644 index 0000000000000000000000000000000000000000..81d672704b3ea750ae1e07e67f8baa9903e0c996 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-atomic-layout.md @@ -0,0 +1,35 @@ +# 原子布局 + +在屏幕形态和规格不同等情况下,布局效果需要实现自适应,因此系统提供了面向不同屏幕尺寸界面自适应适配的布局能力,称为原子布局。设计师可以考虑使用原子能力,定义元素在不同形态的尺寸界面上体现的自适应规则。开发者可以使用原子布局能力,快速实现让应用在多形态屏幕上有与设计效果相匹配的自适应效果。 + + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 隐藏能力 + +在非折行flex布局基础上,增加了显示优先级标记,可以调整组件内元素水平/垂直方向的显示优先级,根据当前组件容器的可用空间来显示内容。 + +| 样式 | 类型 | 默认值 | 说明 | +| -------- | -------- | -------- | -------- | +| display-index | number | 0 | 适用于div等支持flex布局的容器组件中的子组件上,当容器组件在flex主轴上尺寸不足以显示全部内容时,按照display-index值从小到大的顺序进行隐藏,具有相同display-index值的组件同时隐藏,默认值为0,表示隐藏。 | + + +## 占比能力 + +在非折行的flex布局中,定义了占比能力的组件,保证指定元素始终在容器的某一个比例空间中进行布局。 + +| 样式 | 类型 | 默认值 | 说明 | +| -------- | -------- | -------- | -------- | +| flex-weight | number | - | 指明当前元素在flex主轴方向上尺寸权值,当且仅当容器组件中所有节点均设置此属性时生效,当前元素尺寸为: 容器主轴尺寸 \* 当前权值 / 所有子元素权值和。 | + + +## 固定比例 + +定义了组件固定比例调整尺寸的能力。 + +| 样式 | 类型 | 默认值 | 说明 | +| -------- | -------- | -------- | -------- | +| aspect-ratio | number | - |  接受任意大于0的浮点值,定义为该节点的宽度与高度比,设置该属性后,该元素尺寸宽高比按照此属性值进行调整。
 遵守最大值与最小值的限制。
 在flex布局中,主轴尺寸先进行调整,后根据该尺寸调整交叉轴。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-attributes.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-attributes.md new file mode 100644 index 0000000000000000000000000000000000000000..c611597c309f7d757ffe6b2bb694078bd46d7d69 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-attributes.md @@ -0,0 +1,32 @@ +# 通用属性 + +> **说明:** +> +>从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 常规属性 + +常规属性指的是组件普遍支持的用来设置组件基本标识和外观显示特征的属性。 + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| id | string | - | 否 | 组件的唯一标识。 | +| style | string | - | 否 | 组件的样式声明。 | +| class | string | - | 否 | 组件的样式类,用于引用样式表。 | +| ref | string | - | 否 | 用来指定指向子元素或子组件的引用信息,该引用将注册到父组件的$refs 属性对象上。 | +| disabled | boolean | false | 否 | 当前组件是否被禁用,在禁用场景下,组件将无法响应用户交互。 | +| dir | string | auto | 否 | 设置元素布局模式,支持设置rtl、ltr和auto三种属性值:
- "rtl":使用从右往左布局模式。
- "ltr":使用从左往右布局模式。
- "auto":跟随系统语言环境。 | + + +## 渲染属性 + +组件普遍支持的用来设置组件是否渲染的属性。 + +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| for | Array | - | 根据设置的数据列表,展开当前元素。 | +| if | boolean | - | 根据设置的boolean值,添加或移除当前元素。 | +| show | boolean | - | 根据设置的boolean值,显示或隐藏当前元素。 | + +> **说明:** +> 属性和样式不能混用,不能在属性字段中进行样式设置。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-customizing-font.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-customizing-font.md new file mode 100644 index 0000000000000000000000000000000000000000..3293ef9f812c022be7769541776a370a5de5476f --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-customizing-font.md @@ -0,0 +1,59 @@ +# 自定义字体样式 + + +font-face用于定义字体样式。应用可以在style中定义font-face来指定相应的字体名和字体资源,然后在font-family样式中引用该字体。 + + +自定义字体可以是从项目中的字体文件或网络字体文件中加载的字体。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 字体格式支持ttf和otf。 + + +## 定义font-face + + +```css +@font-face { + font-family: HWfont; + src: url('/common/HWfont.ttf'); +} +``` + +**font-family:** 自定义字体的名称。 + +**src:** 自定义字体的来源,支持如下类别。 + +- 项目中的字体文件:通过url指定项目中的字体文件路径(只支持绝对路径,详见[文件组织](js-service-widget-file.md))。 + +- 网络字体文件:通过url指定网络字体的地址。 + +- 不支持设置多个src。 + + +## 使用font-face + +可以在style中定义font-face,然后在font-family样式中指定该font-face的名称,从而应用font-face定义的字体。示例如下: + +- 页面布局 + + ```html +
+ 测试自定义字体 +
+ ``` + +- 页面样式 + + ```css + @font-face { + font-family: HWfont; + src: url("/common/HWfont.ttf"); + } + .demo-text { + font-family: HWfont; + } + ``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-events.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-events.md new file mode 100644 index 0000000000000000000000000000000000000000..14824bcf39a1e6f91a9d24ea5ca1359355f399c4 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-events.md @@ -0,0 +1,12 @@ +# 通用事件 + + +相对于私有事件,大部分组件都可以绑定如下事件。(如果需要响应键盘的回车和空格发生Key Up事件,需要在最外层的控件上添加click事件) + +> **说明:** +> +>从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +| 名称 | 参数 | 描述 | +| -------- | -------- | -------- | +| click | - | 点击动作触发该事件。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md new file mode 100644 index 0000000000000000000000000000000000000000..66c7d73703a3ed5afdb4cffe5ab27bd49e8db131 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-gradient.md @@ -0,0 +1,85 @@ +# 渐变样式 + +组件普遍支持的在style或css中设置的 可以平稳过渡两个或多个指定的颜色。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +开发框架支持线性渐变 (linear-gradient)和重复线性渐变 (repeating-linear-gradient)两种渐变效果。 + + +## 线性渐变/重复线性渐变 + +使用渐变样式,需要定义过渡方向和过渡颜色。 + + +### 过渡方向 + + 通过direction或者angle指定过渡方向。 + +- direction:进行方向渐变。 + +- angle:进行角度渐变。 + + +```css +background: linear-gradient(direction/angle, color, color, ...); +background: repeating-linear-gradient(direction/angle, color, color, ...); +``` + + +### 过渡颜色 + +支持以下四种方式:\#ff0000、\#ffff0000、rgb(255, 0, 0)、rgba(255, 0, 0, 1),需要指定至少两种颜色。 + +- 参数 + + | 名称 | 类型 | 默认值 | 必填 | 描述 | + | --------- | ---------------------------------------- | ---------------------------- | ---- | ---------------------------------------- | + | direction | to <side-or-corner>  <side-or-corner> = [left \| right] \|\| [top \| bottom] | to bottom (由上到下渐变) | 否 | 指定过渡方向,如:to left (从右向左渐变)  ,或者to bottom right (从左上角到右下角)。 | + | angle | <deg> | 180deg | 否 | 指定过渡方向,以元素几何中心为坐标原点,水平方向为X轴,angle指定了渐变线与Y轴的夹角(顺时针方向)。 | + | color | <color> [<length>\|<percentage>] | - | 是 | 定义使用渐变样式区域内颜色的渐变效果。 | + +- 示例 + + 1. 默认渐变方向为从上向下渐变。 + + ```css + #gradient { + height: 300px; + width: 600px; + /* 从顶部开始向底部由红色向绿色渐变 */ + background: linear-gradient(red, #00ff00); + } + ``` + + ![111](figures/111.PNG) + + 2. 45度夹角渐变。 + + + ```css + /* 45度夹角,从红色渐变到绿色 */ + background: linear-gradient(45deg, rgb(255,0,0),rgb(0, 255, 0)); + ``` + + ![222](figures/222.PNG) + + 3. 设置方向从左向右渐变。 + + ```css + /* 从左向右渐变,在距离左边90px和距离左边360px (600*0.6) 之间270px宽度形成渐变 */ + background: linear-gradient(to right, rgb(255,0,0) 90px, rgb(0, 255, 0) 60%); + ``` + + + ![333](figures/333.PNG) + + 4. 重复渐变。 + + ```css + /* 从左向右重复渐变,重复渐变区域30px(60-30)透明度0.5 */ + background: repeating-linear-gradient(to right, rgba(255, 255, 0, 1) 30px,rgba(0, 0, 255, .5) 60px); + ``` + ![444](figures/444.PNG) diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md new file mode 100644 index 0000000000000000000000000000000000000000..6fa60061f6d0f4f29a2ecf1180b9b65ec94cdabc --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-mediaquery.md @@ -0,0 +1,179 @@ +# 媒体查询 + + +媒体查询(Media Query)在移动设备上应用十分广泛,开发者经常需要根据设备的大致类型或者特定的特征和设备参数(例如屏幕分辨率)来修改应用的样式。为此媒体查询提供了如下功能: + +1. 针对设备和应用的属性信息,可以设计出相匹配的布局样式。 + +2. 当屏幕发生动态改变时(比如分屏、横竖屏切换),应用页面布局同步更新。 + + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> media属性值默认为设备的真实尺寸大小、物理像素和真实的屏幕分辨率。请勿与以720px为基准的项目配置宽度px混淆。 + + +## CSS语法规则 + +使用\@media来引入查询语句,具体规则如下: + + +```css +@media [media-type] [and|not|only] [(media-feature)] { + CSS-Code; +} +``` + +例子: + +\@media screen and (round-screen: true) { … } // 当设备屏幕是圆形时条件成立 + +\@media (max-height: 800) { … } // 范围查询,CSS level 3 写法 + +\@media (height <= 800) { … } // 范围查询,CSS level 4 写法,与CSS level3写法等价 + +\@media screen and (device-type: tv) or (resolution < 2) { … } // 同时包含媒体类型和多个媒体特征的多条件复杂语句查询 + + +## 页面中引用资源 + +通过\@import方式引入媒体查询,具体使用方法如下: + + +``` +@import url [media-type] [and|not|only] [(media-feature)]; +``` + +例如: + + +``` +@import '../common/style.css' screen and (min-width: 600) and (max-width: 1200); +``` + + +## 媒体类型 + +| 类型 | 说明 | +| -------- | -------- | +| screen | 按屏幕相关参数进行媒体查询。 | + + +## 媒体逻辑操作 + +媒体逻辑操作符:and、or、not、only用于构成复杂媒体查询,也可以通过comma(,)将其组合起来,详细解释说明如下表。 + + **表1** 媒体逻辑操作符 + +| 类型 | 说明 | +| -------- | -------- | +| and | 将多个媒体特征(Media Feature)以“与”的方式连接成一个媒体查询,只有当所有媒体特征都为true,查询条件成立。另外,它还可以将媒体类型和媒体功能结合起来。
例如:screen and (device-type: wearable) and (max-height: 600) 表示当设备类型是智能穿戴同时应用的最大高度小于等于600个像素单位时成立。 | +| not | 取反媒体查询结果,媒体查询结果不成立时返回true,否则返回false。在媒体查询列表中应用not,则not仅取反应用它的媒体查询。
例如:not screen and (min-height: 50) and (max-height: 600) 表示当应用高度小于50个像素单位或者大于600个像素单位时成立。
使用not运算符时必须指定媒体类型。 | +| only | 当整个表达式都匹配时,才会应用选择的样式,可以应用在防止某些较早的版本的浏览器上产生歧义的场景。一些较早版本的浏览器对于同时包含了媒体类型和媒体特征的语句会产生歧义,比如:
screen and (min-height: 50)
老版本浏览器会将这句话理解成screen,从而导致仅仅匹配到媒体类型(screen),就应用了指定样式,使用only可以很好地规避这种情况。
使用only时必须指定媒体类型。 | +| ,(comma) | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。其效果等同于or运算符。
例如:screen and (min-height: 1000),  (round-screen:true) 表示当应用高度大于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | +| or | 将多个媒体特征以“或”的方式连接成一个媒体查询,如果存在结果为true的媒体特征,则查询条件成立。
例如:screen and (max-height: 1000) or  (round-screen:true)表示当应用高度小于等于1000个像素单位或者设备屏幕是圆形时,条件成立。 | + +在MediaQuery Level 4中引入了范围查询,使其能够使用max-,min-的同时,也支持了<=,>=,<,>操作符。 + + **表2** 媒体逻辑范围操作符 + +| 类型 | 说明 | +| -------- | -------- | +| <= | 小于等于,例如:screen and (height <= 50)。 | +| >= | 大于等于,例如:screen and (height >= 600)。 | +| < | 小于,例如:screen and (height < 50)。 | +| > | 大于,例如:screen and (height > 600)。 | + + +## 媒体特征 + +| 类型 | 说明 | +| -------- | -------- | +| height | 应用页面显示区域的高度。 | +| min-height | 应用页面显示区域的最小高度。 | +| max-height | 应用页面显示区域的最大高度。 | +| width | 应用页面显示区域的宽度。 | +| min-width | 应用页面显示区域的最小宽度。 | +| max-width | 应用页面显示区域的最大宽度。 | +| resolution | 设备的分辨率,支持dpi,dppx和dpcm单位。其中:
- dpi表示每英寸中物理像素个数,1dpi≈0.39dpcm;
- dpcm表示每厘米上的物理像素个数,1dpcm ≈ 2.54dpi;
- dppx表示每个px中的物理像素数(此单位按96px=1英寸为基准,与页面中的px单位计算方式不同),1dppx = 96dpi。 | +| min-resolution | 设备的最小分辨率。 | +| max-resolution | 设备的最大分辨率。 | +| orientation | 屏幕的方向。
可选值:
- orientation: portrait(设备竖屏)
- orientation: landscape(设备横屏) | +| aspect-ratio | 应用页面显示区域的宽度与高度的比值。
例如:aspect-ratio:1/2 | +| min-aspect-ratio | 应用页面显示区域的宽度与高度的最小比值。 | +| max-aspect-ratio | 应用页面显示区域的宽度与高度的最大比值。 | +| device-height | 设备的高度。 | +| min-device-height | 设备的最小高度。 | +| max-device-height | 设备的最大高度。 | +| device-width | 设备的宽度。 | +| min-device-width | 设备的最小宽度。 | +| max-device-width | 设备的最大宽度。 | +| round-screen | 屏幕类型,圆形屏幕为true, 非圆形屏幕为 false。 | +| dark-mode6+ | 系统为深色模式时为true,否则为false。 | + + +## 示例代码 + + +```html + +
+
+ Hello World +
+
+``` + + +```css +/* xxx.css */ +.container { + width: 300px; + height: 600px; + background-color: #008000; +} + +@media (device-type: wearable) { + .container-inner { + justify-content: center; + align-items: center; + padding: 40px 26px; + } + + .title { + text-align: center; + } + + .detail_text { + max-lines: 2; + text-align: center; + } +} + +@media (device-type: tv) { + .title { + font-size: 16px; + } + + .detail_text { + font-size: 12px; + } +} + +@media (device-type: car) { + .title { + font-size: 12px; + color: #FFFFFF; + font-family: @id_text_font_family_medium; + } + + .detail_text { + font-size: 12px; + margin-top: 2px; + font-family: @id_text_font_family_regular; + color: #FFFFFF; + } +} +``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md new file mode 100644 index 0000000000000000000000000000000000000000..6b2f2dce0c207642614621dafe327244cb8db36f --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-common-styles.md @@ -0,0 +1,59 @@ +# 通用样式 + +组件普遍支持的可以在style或css中设置组件外观样式,均不是必填项。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +| 名称 | 类型 | 默认值 | 描述 | +| -------- | -------- | -------- | -------- | +| width | <length> \| <percentage> | - | 设置组件自身的宽度。
缺省时使用元素自身内容需要的宽度。
未设置时组件宽度默认为0。 | +| height | <length> \| <percentage> | - | 设置组件自身的高度。
缺省时使用元素自身内容需要的高度。
未设置时组件高度默认为0。 | +| min-width | <length> \| <percentage> | 0 | 设置元素的最小宽度。 | +| min-height | <length> \| <percentage> | 0 | 设置元素的最小高度。 | +| max-width | <length> \| <percentage> | - | 设置元素的最大宽度。默认无限制。 | +| max-height | <length> \| <percentage> | - | 设置元素的最大高度。默认无限制。 | +| padding | <length> \| <percentage> | 0 | 使用简写属性设置所有的内边距属性。
  该属性可以有1到4个值:
- 指定一个值时,该值指定四个边的内边距。
- 指定两个值时,第一个值指定上下两边的内边距,第二个指定左右两边的内边距。
- 指定三个值时,第一个指定上边的内边距,第二个指定左右两边的内边距,第三个指定下边的内边距。
- 指定四个值时分别为上、右、下、左边的内边距(顺时针顺序)。 | +| padding-[left\|top\|right\|bottom] | <length> \| <percentage> | 0 | 设置左、上、右、下内边距属性。 | +| padding-[start\|end] | <length> \| <percentage> | 0 | 设置起始和末端内边距属性。 | +| margin | <length> \| <percentage> | 0 | 使用简写属性设置所有的外边距属性,该属性可以有1到4个值。
- 只有一个值时,这个值会被指定给全部的四个边。
- 两个值时,第一个值被匹配给上和下,第二个值被匹配给左和右。
- 三个值时,第一个值被匹配给上, 第二个值被匹配给左和右,第三个值被匹配给下。
- 四个值时,会依次按上、右、下、左的顺序匹配 (即顺时针顺序)。 | +| margin-[left\|top\|right\|bottom] | <length> \| <percentage> | 0 | 设置左、上、右、下外边距属性。 | +| margin-[start\|end] | <length> \| <percentage> | 0 | 设置起始和末端外边距属性。 | +| border | - | 0 | 使用简写属性设置所有的边框属性,包含边框的宽度,样式,颜色属性,顺序设置为border-width、border-style、border-color,不设置时,各属性值为默认值。 | +| border-style | string | solid | 使用简写属性设置所有边框的样式,可选值为:
- dotted:显示为一系列圆点,圆点半径为border-width的一半。
- dashed:显示为一系列短的方形虚线。
- solid:显示为一条实线。 | +| border-[left\|top\|right\|bottom]-style | string | solid | 分别设置左、上、右、下四个边框的样式,可选值为dotted、dashed、solid。 | +| border-[left\|top\|right\|bottom] | - | - | 使用简写属性设置对应位置的边框属性,包含边框的宽度,样式,颜色属性,顺序设置为border-width、border-style、border-color,不设置的值为默认值。 | +| border-width | <length> | 0 | 使用简写属性设置元素的所有边框宽度,或者单独为各边边框设置宽度。 | +| border-[left\|top\|right\|bottom]-width | <length> | 0 | 分别设置左、上、右、下四个边框的宽度。 | +| border-color | <color> | black | 使用简写属性设置元素的所有边框颜色,或者单独为各边边框设置颜色。 | +| border-[left\|top\|right\|bottom]-color | <color> | black | 分别设置左、上、右、下四个边框的颜色。 | +| border-radius | <length> | - | border-radius属性设置元素的外边框圆角半径。设置border-radius时不能单独设置某一个方向的border-[left\|top\|right\|bottom]-width,border-[left\|top\|right\|bottom]-color ,border-[left\|top\|right\|bottom]-style,如果要设置color、width和style,需要将四个方向一起设置(border-width、border-color、border-style)。 | +| border-[top\|bottom]-[left\|right]-radius | <length> | - | 分别设置左上,右上,右下和左下四个角的圆角半径。 | +| background | <linear-gradient> | - | 仅支持设置[渐变样式](js-service-widget-common-gradient.md),与background-color、background-image不兼容。 | +| background-color | <color> | - | 设置背景颜色。 | +| background-image | string | - | 设置背景图片。与background-color、background不兼容,支持本地图片资源地址。
示例:
- background-image: url("/common/background.png")
不支持svg格式图片。 | +| background-size | - string
- <length> <length>
- <percentage> <percentage> | auto | 设置背景图片的大小。
- string可选值:
  - contain:把图片扩展至最大尺寸,以使其高度和宽度完全适用内容区域。
  - cover:把背景图片扩展至足够大,以使背景图片完全覆盖背景区域;背景图片的某些部分也许无法显示在背景定位区域中。
  - auto:保持原图的比例不变。
- length值参数方式:
  设置背景图片的高度和宽度。第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。
- 百分比参数方式:
  以父元素的百分比来设置背景图片的宽度和高度。第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。 | +| background-repeat | string | repeat | 针对重复背景图片样式进行设置,背景图片默认在水平和垂直方向上重复。
- repeat:在水平轴和竖直轴上同时重复绘制图片。
- repeat-x:只在水平轴上重复绘制图片。
- repeat-y:只在竖直轴上重复绘制图片。
- no-repeat:不会重复绘制图片。 | +| background-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | - 关键词方式:如果仅规定了一个关键词,那么第二个值为"center"。两个值分别定义水平方向位置和竖直方向位置。
  - left:水平方向上最左侧。
  - right:水平方向上最右侧。
  - top:竖直方向上最顶部。
  - bottom:竖直方向上最底部。
  - center:水平方向或竖直方向上中间位置。
- length值参数方式:第一个值是水平位置,第二个值是垂直位置。 左上角是 0 0。单位是像素 (0px 0px)  。如果仅规定了一个值,另外一个值将是50%。
- 百分比参数方式:第一个值是水平位置,第二个值是垂直位置。左上角是 0% 0%。右下角是 100% 100%。如果仅规定了一个值,另外一个值为50%。
- 可以混合使用<percentage>和<length>。 | +| box-shadow | string | 0 | 语法:box-shadow: h-shadow v-shadow blur spread color
通过这个样式可以设置当前组件的阴影样式,包括水平位置(必填)、垂直位置(必填)、模糊半径(可选,默认值为0)、阴影延展距离(可选,默认值为0)、阴影颜色(可选,默认值为黑色)。
示例:
- box-shadow :10px 20px 5px 10px \#888888
- box-shadow :100px 100px 30px red
- box-shadow :-100px -100px 0px 40px | +| filter | string | - | 语法:filter: blur(px)
通过这个样式可以设置当前组件布局范围的内容模糊,参数用于指定模糊半径,如果没有设置值,则默认是0(不模糊),不支持百分比。
示例:filter: blur(10px) | +| backdrop-filter | string | - | 语法:backdrop-filter: blur(px)
通过这个样式可以设置当前组件布局范围的背景模糊,参数用于指定模糊半径,如果没有设置值,则默认是0(不模糊),不支持百分比。
示例:backdrop-filter: blur(10px) | +| opacity | number | 1 | 元素的透明度,取值范围为0到1,1表示为不透明,0表示为完全透明。 | +| display | string | flex | 确定一个元素所产生的框的类型,可选值为:
- flex:弹性布局。
- none:不渲染此元素。 | +| visibility | string | visible | 是否显示元素所产生的框。不可见的框会占用布局(将'display'属性设置为'none'来完全去除框),可选值为:
- visible:元素正常显示。
- hidden:隐藏元素,但是其他元素的布局不改变,相当于此元素变成透明
visibility和display样式都设置时,仅display生效。 | +| flex | number \| string | - | 规定当前组件如何适应父组件中的可用空间。
flex可以指定1个、2个或3个值。
单值语法:
- 一个无单位数:用来设置组件的flex-grow。
- 一个有效的宽度值:用来设置组件的flex-basis。
双值语法:
第一个值必须是无单位数,用来设置组件的flex-grow。第二个值是以下之一:
- 一个无单位数:用来设置组件的flex-shrink。
- 一个有效的宽度值:用来设置组件的flex-basis。
三值语法:
第一个值必须是无单位数,用来设置组件的flex-grow;第二个值必须是无单位数,用来设置组件的flex-shrink;第三个值必须是一个有效的宽度值,用来设置组件的flex-basis。
仅父容器为<div>、<list-item>时生效。 | +| flex-grow | number | 0 | 设置组件的拉伸样式,指定父组件容器主轴方向上剩余空间(容器本身大小减去所有flex子元素占用的大小)的分配权重。0为不伸展。
仅父容器为<div>、<list-item>时生效。 | +| flex-shrink | number | 1 | 设置组件的收缩样式,元素仅在默认宽度之和大于容器的时候才会发生收缩,0为不收缩。
仅父容器为<div>、<list-item>时生效。 | +| flex-basis | <length> | - | 设置组件在主轴方向上的初始大小。
仅父容器为<div>、<list-item>时生效。 | +| align-self | string | - | 设置自身在父元素交叉轴上的对齐方式,该样式会覆盖父元素的align-items样式,仅在父容器为div、list。可选值为:
- stretch 弹性元素被在交叉轴方向被拉伸到与容器相同的高度或宽度。
- flex-start 元素向交叉轴起点对齐。
- flex-end 元素向交叉轴终点对齐。
- center 元素在交叉轴居中。
- baseline 元素在交叉轴基线对齐。 | +| position | string | relative | 设置元素的定位类型,不支持动态变更。
- fixed:相对与整个界面进行定位。
- absolute:相对于父元素进行定位。
- relative:相对于其正常位置进行定位。
absolute属性仅在父容器为<div>时生效。 | +| [left\|top\|right\|bottom | <length> \| <percentage> | - | left\|top\|right\|bottom需要配合position样式使用,来确定元素的偏移位置。
- left属性规定元素的左边缘。该属性定义了定位元素左外边距边界与其包含块左边界之间的偏移。
- top属性规定元素的顶部边缘。该属性定义了一个定位元素的上外边距边界与其包含块上边界之间的偏移。
- right属性规定元素的右边缘。该属性定义了定位元素右外边距边界与其包含块右边界之间的偏移。
- bottom属性规定元素的底部边缘。该属性定义了一个定位元素的下外边距边界与其包含块下边界之间的偏移。 | +| [start \| end] | <length> \| <percentage> | - | start \| end需要配合position样式使用,来确定元素的偏移位置。
- start属性规定元素的起始边缘。该属性定义了定位元素起始外边距边界与其包含块起始边界之间的偏移。
- end属性规定元素的结尾边缘。该属性定义了一个定位元素的结尾边距边界与其包含块结尾边界之间的偏移。 | +| z-index | number | - | 表示对于同一父节点其子节点的渲染顺序。数值越大,渲染数据越靠后。
z-index不支持auto,并且opacity等其他样式不会影响z-index的渲染顺序。 | +| image-fill | <color> | - | 为svg图片填充颜色,支持组件范围(与设置图片资源的属性):button(icon属性)、image(src属性)。
svg图片文件内的fill属性颜色值在渲染时将被替换为image-fill所配的颜色值,且仅对svg图片内显示声明的fill属性生效。 | +| clip-path | [ <geometry-box> \|<basic-shape> ] \| none | - | 设置组件的裁剪区域。区域内的部分显示,区域外的不显示。
<geometry-box>:表示裁剪区域的作用范围,默认为border-box。可选值为:
- margin-box:margin计算入长宽尺寸内。
- border-box:border计算入长宽尺寸内。
- padding-box:padding计算入长宽尺寸内。
- content-box:margin/border/padding不计算入长宽尺寸内。
<basic-shape>:表示裁剪的形状。包含以下类型:
- inset,格式为:inset( <percentage>{1,4} [ round <'border-radius'> ]? )。
- circle,格式为:circle( [ <percentage> ]? [ at <percentage> <percentage> ]? )。
- ellipse,格式为:ellipse( [ <percentage>{2} ]? [ at <percentage> <percentage> ]? )。
- polygon,格式为:polygon( [ <percentage> <percentage> ]\# )。
- path,格式为:path( <string> )。 | +| mask-image | - <linear-gradient>
- string | - | 设置渐变色遮罩或本地图片设置。
设置渐变色遮罩,示例:linear-gradient(to left, black, white)
设置纯色遮罩,示例:linear-gradient(to right, grey , grey)
设置本地svg图片为遮罩,示例:url(common/mask.svg) | +| mask-size | - string
- <length><length>
- <percentage> <percentage> | auto | 设置遮罩图片显示大小,仅当mask-image为图片资源时有效。
string可选值:
- contain:把图像扩展至最大尺寸,以使其高度和宽度完全适用内容区域。
- cover:把图像扩展至足够大,以使背景图像完全覆盖背景区域;背景图像的某些部分也许无法显示在背景定位区域中。
- auto:保持原图的比例不变。
length值参数方式:设置图像的高度和宽度。第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。
百分比参数方式:以原图宽高的百分比来设置图像的宽度和高度。第一个值设置宽度,第二个值设置高度。如果只设置一个值,则第二个值会被设置为 "auto"。 | +| mask-position | - string string
- <length> <length>
- <percentage> <percentage> | 0px 0px | 设置遮罩图片显示位置,仅当mask-image为图片资源时有效。关键词方式:如果仅规定了一个关键词,那么第二个值为"center"。两个值分别定义水平方向位置和竖直方向位置。
string可选值:
- left:水平方向上最左侧。
- right:水平方向上最右侧。
- top:竖直方向上最顶部。
- bottom:竖直方向上最底部。
- center:水平方向或竖直方向上中间位置。
length值参数方式:第一个值是水平位置,第二个值是垂直位置。 左上角是 0 0。单位是像素 (0px 0px)  。如果仅规定了一个值,另外一个值将是50%。
百分比参数方式:第一个值是水平位置,第二个值是垂直位置。左上角是 0% 0%。右下角是 100% 100%。如果仅规定了一个值,另外一个值为50%。
可以混合使用<percentage>和<length>。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-config-file.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-config-file.md new file mode 100644 index 0000000000000000000000000000000000000000..82867f64408b16b9a82a1d43a786ace97e4f12fa --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-config-file.md @@ -0,0 +1,91 @@ +# 配置文件 + + +js标签中包含了实例名称、窗口样式和卡片页面信息。 + + +| 标签 | 类型 | 默认值 | 必填 | 描述 | +| ------ | ------ | ------- | ---- | --------------------------- | +| name | String | default | 是 | 标识JS实例的名字。 | +| pages | Array | - | 是 | 路由信息,详见“[pages](#pages)”。 | +| window | Object | - | 否 | 窗口信息,详见“[window](#window)”。 | + +> **说明:** +> name、pages、window等标签配置需在[配置文件]()中的“js”标签中完成设置。 + + +## pages + +定义卡片页面信息,由卡片页面路径和卡片页面名组成,卡片仅包含一个页面。比如: + + +``` +{ + ... + "src": "./js/widget/pages/index/index" //卡片仅包含一个页面 + ... +} +``` + + +> **说明:** +> - pages列表中仅包含一个页面。 +> +> - 页面文件名不能使用组件名称,比如:text.hml、button.hml等。 + + +## window + +window用于定义与显示窗口相关的配置。对于卡片尺寸适配问题,有2种配置方法,建议使用autoDesignWidth: + +- 指定卡片designWidth 150px(2×2),所有与大小相关的样式(例如width、font-size)均以designWidth和实际卡片宽度的比例进行缩放,例如在designWidth为150时,如果设置width为100px时,在卡片实际宽度为300物理像素时,width实际渲染像素为200物理像素。 + +- 设置autoDesignWidth为true,此时designWidth字段将会被忽略,渲染组件和布局时按屏幕密度进行缩放。屏幕逻辑宽度由设备宽度和屏幕密度自动计算得出,在不同设备上可能不同,请使用相对布局来适配多种设备。例如:在466\*466分辨率,320dpi的设备上,屏幕密度为2(以160dpi为基准),1px等于渲染出的2物理像素。 + > **说明:** + > - 组件样式中<length>类型的默认值,按屏幕密度进行计算和绘制,如:在屏幕密度为2(以160dpi为基准)的设备上,默认<length>为1px时,设备上实际渲染出2物理像素。 + > + > - autoDesignWidth、designWidth的设置不影响默认值计算方式和绘制结果。 + +| 属性 | 类型 | 必填 | 默认值 | 描述 | +| --------------- | ------- | ---- | ----- | ---------------------------------------- | +| designWidth | number | 否 | 150px | 页面显示设计时的参考值,实际显示效果基于设备宽度与参考值之间的比例进行缩放。 | +| autoDesignWidth | boolean | 否 | false | 页面设计基准宽度是否自动计算,当设为true时,designWidth将会被忽略,设计基准宽度由设备宽度与屏幕密度计算得出。 | + + 示例如下: + { + ... + "window": { + "autoDesignWidth": true + } + ... + } + + +## 示例 + + +```json +{ + "forms": [ + { + "name": "widget", + "description": "This is a service widget.", + "src": "./js/widget/pages/index/index", + "window": { + "designWidth": 720, + "autoDesignWidth": true + }, + "colorMode": "auto", + "isDefault": true, + "updateEnabled": true, + "scheduledUpdateTime": "10:30", + "updateDuration": 1, + "defaultDimension": "2*2", + "supportDimensions": [ + "1*2","2*2","2*4","4*4" + ], + "formConfigAbility": "ability://xxxxx" + } + ] +} +``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..3681e765caced63b2f98e917cf6a7cf92725aa56 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-configuration.md @@ -0,0 +1,34 @@ +# 配置数据和事件 + + +卡片使用json文件配置卡片使用的变量和事件,变量的声明在data字段下,事件的声明在actions字段下。 + + +示例: + + + +```json +{ + "data": { + "temperature": "35°C", + "city": "hangzhou" + }, + "actions": { + "routerEventName": { + "action": "router", + "abilityName": "com.example.myapplication.FormAbility", + "params": { + "message": "weather", + "temperature": "{{temperature}}" + } + }, + "messageEventName": { + "action": "message", + "params": { + "message": "weather update" + } + } + } +} +``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-div.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-div.md new file mode 100644 index 0000000000000000000000000000000000000000..70e3ace007e8c2268a9a2ce7748ba456c3978dee --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-div.md @@ -0,0 +1,145 @@ +# div + + +基础容器,用作页面结构的根节点或将内容进行分组。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + +## 子组件 + +支持。 + + +## 属性 + +支持[通用属性](js-service-widget-common-attributes.md)。 + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| flex-direction | string | row | 否 | flex容器主轴方向。可选项有:
- column:垂直方向从上到下。
- row:水平方向从左到右。 | +| flex-wrap | string | nowrap | 否 | flex容器是单行还是多行显示,该值暂不支持动态修改。可选项有:
- nowrap:不换行,单行显示。
- wrap:换行,多行显示。 | +| justify-content | string | flex-start | 否 | flex容器当前行的主轴对齐格式。可选项有:
- flex-start:项目位于容器的开头。
- flex-end:项目位于容器的结尾。
- center:项目位于容器的中心。
- space-between:项目位于各行之间留有空白的容器内。
- space-around:项目位于各行之前、之间、之后都留有空白的容器内。
- space-evenly5+:  均匀排列每个元素,每个元素之间的间隔相等。 | +| align-items | string | stretch | 否 | flex容器当前行的交叉轴对齐格式,可选值为:
- stretch:弹性元素在交叉轴方向被拉伸到与容器相同的高度或宽度。
- flex-start:元素向交叉轴起点对齐。
- flex-end:元素向交叉轴终点对齐。
- center:元素在交叉轴居中。 | +| align-content | string | flex-start | 否 | 交叉轴中有额外的空间时,多行内容对齐格式,可选值为:
- flex-start:所有行从交叉轴起点开始填充。第一行的交叉轴起点边和容器的交叉轴起点边对齐。接下来的每一行紧跟前一行。
- flex-end:所有行从交叉轴末尾开始填充。最后一行的交叉轴终点和容器的交叉轴终点对齐。同时所有后续行与前一个对齐。
- center:所有行朝向容器的中心填充。每行互相紧挨,相对于容器居中对齐。容器的交叉轴起点边和第一行的距离相等于容器的交叉轴终点边和最后一行的距离。
- space-between:所有行在容器中平均分布。相邻两行间距相等。容器的交叉轴起点边和终点边分别与第一行和最后一行的边对齐。
- space-around:所有行在容器中平均分布,相邻两行间距相等。容器的交叉轴起点边和终点边分别与第一行和最后一行的距离是相邻两行间距的一半。 | +| display | string | flex | 否 | 确定该元素视图框的类型,该值暂不支持动态修改。可选值为:
- flex:弹性布局
- none:不渲染此元素 | +| grid-template-[columns\|rows] | string | 1行1列 | 否 | 用于设置当前网格布局行和列的数量,不设置时默认1行1列,仅当display为grid时生效。
示例:如设置grid-template-columns为:
- 50px 100px 60px:分三列,第一列50px,第二列100px,第三列60px。
- 1fr 1fr 2fr:分三列,将父组件允许的宽分为4等份,第一列占1份,第二列占一份,第三列占2份。
- 30% 20% 50%:分三列,将父组件允许的宽为基准,第一列占30%,第二列占20%,第三列占50%。
- repeat(2,100px):分两列,第一列100px,第二列100px。
- repeat(auto-fill,100px)5+:按照每列100px的大小和交叉轴大小计算最大正整数重复次数,按照该重复次数布满交叉轴。
- auto 1fr 1fr:分三列,第一列自适应内部子组件所需宽度,剩余空间分为两等份,第二列占一份,第三列占一份。 | +| grid-[columns\|rows]-gap | <length> | 0 | 否 | 用于设置行与行的间距或者列与列的间距,也可以支持通过grid-gap设置相同的行列间距,仅当display为grid时生效。 | +| grid-row-[start\|end] | number | - | 否 | 用于设置当前元素在网格布局中的起止行号,仅当父组件display样式为grid时生效(仅div支持display样式设置为grid)。 | +| grid-column-[start\|end] | number | - | 否 | 用于设置当前元素在网格布局中的起止列号,仅当父组件display样式为grid时生效(仅div支持display样式设置为grid)。 | +| grid-auto-flow | string | - | 否 | 使用框架自动布局算法进行网格的布局,可选值为:
- row:逐行填充元素,如果行空间不够,则新增行。
- column:逐列填充元素,如果列空间不够,则新增列。 | +| align-items | string | - | 否 | 设置容器中元素交叉轴上的对齐方式:
- stretch:Flex容器内容在交叉轴方向被拉伸到与容器相同的高度或宽度。
- flex-start:Flex布局容器内元素向交叉轴起点对齐。
- flex-end:Flex布局容器内元素向交叉轴终点对齐。
- center:Flex布局容器内元素在交叉轴居中对齐。
- baseline:如Flex布局纵向排列,则该值与'flex-start'等效。横向布局时,内容元素存在文本时按照文本基线对齐,否则底部对齐。 | + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + +1. Flex样式 + + ```html + +
+
+
+
+
+
+
+ ``` + + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 454px; + height: 454px; + } + .flex-box { + justify-content: space-around; + align-items: center; + width: 400px; + height: 140px; + background-color: #ffffff; + } + .flex-item { + width: 120px; + height: 120px; + border-radius: 16px; + } + .color-primary { + background-color: #007dff; + } + .color-warning { + background-color: #ff7500; + } + .color-success { + background-color: #41ba41; + } + ``` + **2*4卡片** + + ![zh-cn_image_0000001231610863](figures/zh-cn_image_0000001231610863.png) + +2. Flex Wrap样式 + + ```html + +
+
+
+
+
+
+
+ ``` + + + ```css + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 454px; + height: 454px; + } + .flex-box { + justify-content: space-around; + align-items: center; + flex-wrap: wrap; + width: 300px; + height: 250px; + background-color: #ffffff; + } + .flex-item { + width: 120px; + height: 120px; + border-radius: 16px; + } + .color-primary { + background-color: #007dff; + } + .color-warning { + background-color: #ff7500; + } + .color-success { + background-color: #41ba41; + } + ``` + **4*4卡片** + + ![zh-cn_image_0000001186131150](figures/zh-cn_image_0000001186131150.png) + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list-item.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list-item.md new file mode 100644 index 0000000000000000000000000000000000000000..f76f8a12e77baab472dbc3af1d82888cd8734e2e --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list-item.md @@ -0,0 +1,49 @@ +# list-item + + +<[list](js-service-widget-container-list.md)>的子组件,用来展示列表具体item。 + + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> - 由于父元素list组件的align-items默认样式为stretch,该组件宽度默认充满list组件。设置父元素list组件的align-items样式为非stretch来生效自定义宽度。 +> +> - list-item组件开发避免长按和拖动操作。 + + +## 子组件 + +支持。 + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| type | string | default | 否 | list-item类型,默认值为default,同一list中可以包含多种type的list-item,相同type的list-item需要确保渲染后的视图布局也相同,如果type固定,则使用show属性代替if属性,确保视图布局不变。 | +| section | string | - | 否 | 当前item的匹配字符串,如不设置则为空。不支持动态修改。group内只有主item设置有效。 | +| sticky | string | none | 否 | 设置当前item是否为吸顶item以及其吸顶消失的效果,当前仅支持纵向list,group内部的item不可吸顶,设置该属性无效。
- none:当前item不吸顶。
- normal:当前item吸顶,消失效果滑动消失。
- opacity:当前item吸顶,消失效果渐隐消失,仅在智能穿戴上支持。 | +| clickeffect | boolean | true | 否 | 设置当前item是否有点击动效。
- false:item点击时无点击动效。
- true:item点击时有点击动效。 | + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| -------- | -------- | -------- | -------- | -------- | +| column-span | <number> | 1 | 否 | 当前的list-item需要在list中占据的列的数量,默认占一列,仅在list为多列时生效。 | +| click-color | <color> | - | 否 | 设置列表项按压点击时的背板颜色。 | + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + +详见[list示例](js-service-widget-container-list.md#示例)。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list.md new file mode 100644 index 0000000000000000000000000000000000000000..02576d205dc77aa2c8754dbdb494cb23d7eb116a --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-list.md @@ -0,0 +1,121 @@ +# list + + +列表包含一系列相同宽度的列表项。适合连续、多行呈现同类数据,例如图片和文本。 + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 +> +> 针对卡片场景,建议开发者控制list中的子节点list-item的数量(建议30条以内)以便获取更好的卡片交互体验。 + + + + +## 子组件 + +仅支持<[list-item](js-service-widget-container-list-item.md)>子组件。 + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| ------------- | -------------- | ------- | ---- | ---------------------------------------- | +| cachedcount | number | 0 | 否 | 长列表延迟加载时list-item最少缓存数量。 | +| scrollbar | string | off | 否 | 侧边滑动栏的显示模式(当前只支持纵向):
- off:不显示。
- auto:按需显示(触摸时显示,2s后消失)。
- on:常驻显示。 | +| scrolleffect | string | spring | 否 | 滑动效果,目前支持如下滑动效果:
- spring:弹性物理动效,滑动到边缘后可以根据初始速度或通过触摸事件继续滑动一段距离,松手后回弹。
- fade:渐隐物理动效,滑动到边缘后展示一个波浪形的渐隐,根据速度和滑动距离的变化渐隐也会发送一定的变化。
- no:滑动到边缘后无效果。 | +| divider | boolean | false | 否 | item是否自带分隔线。
其样式参考[样式列表](#样式)的divider-color、divider-height、divider-length、divider-origin。 | +| shapemode | string | default | 否 | 侧边滑动栏的形状类型。
- default:不指定,跟随主题。
- rect:矩形。
- round:圆形。 | +| updateeffect | boolean | false | 否 | 用于设置当list内部的item发生删除或新增时是否支持动效。
- false:新增删除item时无过渡动效。
- true:新增删除item时播放过程动效。 | +| initialindex | number | 0 | 否 | 用于设置当前List初次加载时视口起始位置显示的item,默认为0,即显示第一个item,如设置的序号超过了最后一个item的序号,则设置不生效,当同时设置了initialoffset属性时,当前属性不生效。 | +| initialoffset | <length> | 0 | 否 | 用于设置当前List初次加载时视口的起始偏移量,偏移量无法超过当前List可滑动的范围,如果超过会被截断为可滑动范围的极限值。 | +| selected | string | - | 否 | 指定当前列表中被选中激活的项,可选值为list-item的section属性值。 | + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| ---------------- | ---------------------------------------- | ----------- | ---- | ---------------------------------------- | +| divider-color | <color> | transparent | 否 | item分隔线颜色,仅当list的divider属性为true时生效。 | +| divider-height | <length> | 1 | 否 | item分隔线高度,仅当list的divider属性为true时生效。 | +| divider-length | <length> | 主轴宽度 | 否 | item分隔线长度,不设置时最大长度为主轴宽度,具体长度取决于divider-origin,仅当list的divider属性为true时生效。 | +| divider-origin | <length> | 0 | 否 | item分隔线相对于item主轴起点位置的偏移量,仅当list的divider属性为true时生效。 | +| flex-direction | string | column | 否 | 设置flex容器主轴的方向,指定flex项如何放置在flex容器中,可选值为:
- column:主轴为纵向。
- row:主轴为横向。
其他组件默认值为row,在list组件中默认值为column。 | +| columns | number | 1 | 否 | list交叉轴方向的显示列数,默认为1列。
设置多列时,在list交叉轴上进行均分,每一列大小相同。 | +| align-items | string | stretch | 否 | list每一列交叉轴上的对齐格式,可选值为:
- stretch:弹性元素被在交叉轴方向被拉伸到与容器相同的高度或宽度。
- flex-start:元素向交叉轴起点对齐。
- flex-end:元素向交叉轴终点对齐。
- center:元素在交叉轴居中。
 align-items样式作用在每一列的子元素上,列与列之间采用均分方式布局。 | +| item-extent | <length> \| <percentage> | - | 否 | 设置内部item为固定大小,设置为百分比格式时,指相对于list的视口主轴方向长度的百分比。 | +| fade-color | <color> | grey | 否 | 设置渐隐物理动效的颜色。当滑动效果设置为渐隐物理动效时生效。 | +| scrollbar-color | <color> | - | 否 | 设置滚动条的颜色。 | +| scrollbar-width | <length> | - | 否 | 设置滚动条的宽度。 | +| scrollbar-offset | <length> | 0 | 否 | 设置滚动条距离List默认位置的偏移量,只支持正数,默认位置在List右边缘,可以通过这个偏移量调整滚动条的水平位置,如果滚动条绘制在list外部,而list父组件有裁剪,会导致滚动条被裁剪。 | + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + +```html + +
+ + + {{$item.title}} + {{$item.date}} + + +
+``` + + +```json +{ + "data": { + "todolist": [{ + "title": "work", + "date": "2021-12-31 10:00:00" + }, { + "title": "watch movie", + "date": "2021-12-31 20:00:00" + }] + } +} +``` + + +```css +/* index.css */ +.container { + display: flex; + justify-content: center; + align-items: center; + left: 0px; + top: 0px; + width: 454px; + height: 454px; +} +.todo-wraper { + width: 454px; + height: 300px; +} +.todo-item { + width: 454px; + height: 80px; + flex-direction: column; +} +.todo-title { + width: 454px; + height: 40px; + text-align: center; +} +``` +**4*4卡片** + +![zh-cn_image_0000001231370803](figures/zh-cn_image_0000001231370803.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-stack.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..304ae0c2efbe216464bae09757904a6dad2154d5 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-stack.md @@ -0,0 +1,78 @@ +# stack + + +堆叠容器,子组件按照顺序依次入栈,后一个子组件覆盖前一个子组件。 + +> **说明:** +> +>从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + +## 子组件 + +支持。 + + +## 属性 + +支持[通用属性](js-service-widget-common-attributes.md)。 + + +## 样式 + +支持[通用样式](js-service-widget-common-styles.md)。 + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + +```html + + +
+
+
+
+``` + + +```css +/* xxx.css */ +.stack-parent { + width: 400px; + height: 400px; + margin: 50px; + background-color: #ffffff; + border-width: 1px; + border-style: solid; +} +.back-child { + width: 300px; + height: 300px; + background-color: #3f56ea; +} +.front-child { + width: 100px; + height: 100px; + background-color: #00bfc9; +} +.positioned-child { + width: 100px; + height: 100px; + left: 50px; + top: 50px; + background-color: #47cc47; +} +.bd-radius { + border-radius: 16px; +} +``` +**4*4卡片** + +![卡片 stack](figures/stack.PNG) + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-swiper.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-swiper.md new file mode 100644 index 0000000000000000000000000000000000000000..236748668d0c771c15ccf1cdfd961b8fd5d0db23 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-container-swiper.md @@ -0,0 +1,99 @@ +# swiper + + +滑动容器,提供切换子组件显示的能力。 + + +> **说明:** +> +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + + +## 属性 + +除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| --------- | ------- | ----- | ---- | ---------------------------------------- | +| index | number | 0 | 否 | 当前在容器中显示的子组件的索引值。 | +| indicator | boolean | true | 否 | 是否启用导航点指示器,默认true。 | +| digital | boolean | false | 否 | 是否启用数字导航点,默认为false。
必须设置indicator时才能生效数字导航点。 | +| loop | boolean | true | 否 | 是否开启循环滑动。 | +| duration | number | - | 否 | 子组件切换的动画时长。 | +| vertical | boolean | false | 否 | 是否为纵向滑动,纵向滑动时采用纵向的指示器。 | + + +## 样式 + +除支持[通用样式](js-service-widget-common-styles.md)外,还支持如下样式: + +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| ---------------------------------- | ---------------------------------------- | ---- | ---- | -------------------- | +| indicator-color | <color> | - | 否 | 导航点指示器的填充颜色。 | +| indicator-selected-color | <color> | - | 否 | 导航点指示器选中的颜色。 | +| indicator-size | <length> | 4px | 否 | 导航点指示器的直径大小。 | +| indicator-top\|left\|right\|bottom | <length> \| <percentage> | - | 否 | 导航点指示器在swiper中的相对位置。 | + + +## 事件 + +支持[通用事件](js-service-widget-common-events.md)。 + + +## 示例 + + +```html + + +
+ 1 +
+
+ 2 +
+
+ 3 +
+
+``` + + +```css +/* xxx.css */ +.container { + left: 0px; + top: 0px; + width: 454px; + height: 454px; +} +.swiper-item { + width: 454px; + height: 454px; + justify-content: center; + align-items: center; +} +.primary-item { + background-color: #007dff; +} +.warning-item { + background-color: #ff7500; +} +.success-item { + background-color: #41ba41; +} +``` + + +```json +{ + "data": { + "index": 1 + } +} +``` +**4*4卡片** + +![卡片swiper](figures/swiper.png) + diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md new file mode 100644 index 0000000000000000000000000000000000000000..b32292dc65c4f008ad088f267dcb9d2b2ecb7f09 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-basic-usage.md @@ -0,0 +1,27 @@ +# 自定义组件基本用法 + + +> **说明:** +> 从API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + + 自定义组件是用户根据业务需求,将已有的组件组合,封装成的新组件,可以在工程中多次调用,提高代码的可读性。自定义组件通过element引入到宿主页面,使用方法: + +```html + +
+ +
+``` + +- name属性指自定义组件名称(非必填),组件名称对大小写不敏感,默认使用小写。src属性指自定义组件hml文件路径(必填),若没有设置name属性,则默认使用hml文件名作为组件名。 + +- 事件绑定:自定义组件中绑定子组件事件使用(on|\@)child1语法,子组件中通过{action:"proxy", method: "eventName"}触发事件并进行传值,父组件执行bindParentVmMethod方法并接收子组件传递的参数。 + + +## 自定义组件配置文件标签 + +| 属性 | 类型 | 描述 | +| -------- | -------- | -------- | +| data | Object | 页面的数据模型,类型是对象。属性名不能以$或_开头,不要使用保留字for, if, show, tid。 | +| props | Array/Object | props用于组件之间的通信,可以通过<tag xxxx='value'>方式传递给组件;props名称必须用小写,不能以$或_开头,不要使用保留字for, if, show, tid。目前props的数据类型不支持Function。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md new file mode 100644 index 0000000000000000000000000000000000000000..05287a5e1f56337015048392cdcc11e1cfa617d7 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-events.md @@ -0,0 +1,104 @@ +# 自定义事件 + + +自定义组件内支持自定义事件,该事件的标识需要action类型指定为proxy,事件名则通过method指定。使用该自定义组件的卡片页面可以通过该事件名注册相应的事件回调,当自定义组件内该自定义事件触发时,会触发卡片页面上注册的回调事件。 + + +> **说明:** +> +> 事件名不支持大写字母。 + + +## 子组件comp示例: + + +```html + +
+
+ +
+
+``` + + + +```css +/* comp.css */ +.container { + flex-direction:column; + background-color: green; + width: 100%; + height: 100%; +} + +.row-3 { + width: 100%; + height: 50px; + background-color: orange; + font-size:15px; +} +``` + + + +```json +{ + "data": { + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method":"event_1" + } + } +} +``` + + +## 卡片页面示例 + + +```html + + + +
+ + +
+``` + + + +```css +/* xxx.css */ +.container { + background-color: red; + height: 500px; + width: 500px; +} +``` + + + +```j'so +{ + "data": { + }, + "actions": { + "click": { + "action": "message", + "params": { + "message": "click event" + } + }, + "buttonClick": { + "action": "message", + "params": { + "message": "click event 2" + } + } + } +} +``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md new file mode 100644 index 0000000000000000000000000000000000000000..9d3a1fbf02c4de67afe52a6172f7cf265c30e3f0 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-custom-props.md @@ -0,0 +1,78 @@ +# Props + + +自定义组件可以通过props声明属性,父组件通过设置属性向子组件传递参数。通过父组件向下传递参数的示例如下: + +## 添加默认值 + +子组件可以通过固定值default设置默认值,当父组件没有设置该属性时,将使用其默认值。此情况下props属性必须为对象形式,不能用数组形式,示例如下: + + + +```html + +
+
+
+ xiaoziti +
+
+ {{text}} +
+
+ {{textdata[0]}} +
+
+
+ +
+
+ +
+
+``` + + + +```json +{ + "data": { + "progress": { + "default": "80" + } + }, + "props": { + "textdata": { + "default": ["a","b"] + }, + "progress": { + "default": 60 + }, + "text": { + "default": "ha" + } + }, + "actions": { + "buttonClicked": { + "action": "proxy", + "method": "event_1" + } + } +} +``` + + + +```html + + + +
+ +
+``` + + +## 数据单向性 + +父子组件之间数据的传递是单向的,只能从父组件传递给子组件,子组件不能直接修改父组件传递下来的值,可以将props传入的值用data接收后作为默认值,再对data的值进行修改。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md new file mode 100644 index 0000000000000000000000000000000000000000..6e7b373bfe3a5d1450c0b86dbc278ad60840336e --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-file.md @@ -0,0 +1,57 @@ +# 文件组织 + + +## 目录结构 + +JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: + +``` +├─widget +│ ├─common +│ │ └─widget.png +│ ├─i18n +│ │ ├─en-US.json +│ │ └─zh-CN.json +│ └─pages +│ └─index +│ ├─index.css +│ ├─index.hml +│ └─index.json +``` + +目录结构中文件分类如下: + +- .hml结尾的HML模板文件,这个文件用来描述卡片页面的模板布局结构。 + +- .css结尾的CSS样式文件,这个文件用于描述页面样式。 + +- .json结尾的JSON文件,这个文件用于配置卡片中使用的变量action事件。 + +各个文件夹的作用: + +- pages目录用于存放卡片模板页面。 + +- common目录用于存放公共资源文件,比如:图片资源。 + +- i18n目录用于配置不同语言场景资源内容,比如应用文本词条,图片路径等资源。 + +## 文件访问规则 + +应用资源可通过绝对路径或相对路径的方式进行访问,本开发框架中绝对路径以"/"开头,相对路径以"./"或"../"。具体访问规则如下: + +- 引用代码文件,需使用相对路径,比如:../common/style.css。 + +- 引用资源文件,推荐使用绝对路径。比如:/common/xxx.png。 + +- 公共代码文件和资源文件推荐放在common下,通过规则1和规则2进行访问。 + +- CSS样式文件中通过url()函数创建<url>数据类型,如:url(/common/xxx.png)。 + +> **说明:** +> 当代码文件A需要引用代码文件B时: +> +> - 如果代码文件A和文件B位于同一目录,则代码文件B引用资源文件时可使用相对路径,也可使用绝对路径。 +> +> - 如果代码文件A和文件B位于不同目录,则代码文件B引用资源文件时必须使用绝对路径。因为Webpack打包时,代码文件B的目录会发生变化。 +> +> - 在json文件中定义的数据为资源文件路径时,需使用绝对路径。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-multiple-languages.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-multiple-languages.md new file mode 100644 index 0000000000000000000000000000000000000000..456b3d40ff345a7365a5970b135518b75b311979 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-multiple-languages.md @@ -0,0 +1,116 @@ +# 多语言支持 + + +基于开发框架的应用会覆盖多个国家和地区,开发框架支持多语言能力后,可以让应用开发者无需开发多个不同语言的版本,就可以同时支持多种语言的切换,为项目维护带来便利。 + + +开发者仅需要通过[定义资源文件](#定义资源文件)和[引用资源](#引用资源)两个步骤,就可以使用开发框架的多语言能力。 + + +## 定义资源文件 + +资源文件用于存放应用在多种语言场景下的资源内容,开发框架使用JSON文件保存资源定义。 + +在[文件组织](js-service-widget-file.md)中指定的i18n文件夹内放置每个语言地区下的资源定义文件即可,资源文件命名为“语言-地区.json”格式,例如英文(美国)的资源文件命名为en-US.json。当开发框架无法在应用中找到系统语言的资源文件时,默认使用en-US.json中的资源内容。 + +由于不同语言针对单复数有不同的匹配规则,在资源文件中的使用“zero”“one”“two”“few”“many”“other”定义不同单复数场景下的词条内容。例如中文不区分单复数仅存在“other”场景;英文存在“one”、“other”场景;阿拉伯语存在上述6种场景。 + + 以en-US.json和ar-AE.json为例,资源文件内容格式如下: + +```json +{ + "strings": { + "hello": "Hello world!", + "symbol": "@#$%^&*()_+-={}[]\\|:;\"'<>,./?", + "plurals": { + "one": "one person", + "other": "other people" + } + }, + + "files": { + "image": "image/en_picture.PNG" + } +} +``` + + +```json +{ + "strings": { + "plurals": { + "zero": "لا أحد", + "one": "وحده", + "two": "اثنان", + "few": "ستة اشخاص", + "many": "خمسون شخص", + "other": "مائة شخص" + } + } +} +``` + + +## 引用资源 + +在应用开发的页面中使用多语言的语法,包含简单格式化和单复数格式化两种,都可以在hml或js中使用。 + +- 简单格式化方法 + 在应用中使用$t方法引用资源,$t既可以在hml中使用,也可以在js中使用。系统将根据当前语言环境和指定的资源路径(通过$t的path参数设置),显示对应语言的资源文件中的内容。 + + **表1** 简单格式化 + + | 属性 | 类型 | 参数 | 必填 | 描述 | + | ---- | -------- | -------- | ---- | -------------------------------------- | + | $t | Function | 请见$t参数说明 | 是 | 根据系统语言完成简单的替换:this.$t('strings.hello') | + + **表2** $t参数说明 + + | 参数 | 类型 | 必填 | 描述 | + | ---- | ------ | ---- | ---- | + | path | string | 是 | 资源路径 | + +- 简单格式化示例代码 + + ```html + +
+ {{ $t('strings.hello') }} + +
+ ``` + +- 单复数格式化方法 + + **表3** 单复数格式化 + + | 属性 | 类型 | 参数 | 必填 | 描述 | + | ---- | -------- | --------- | ---- | ---------------------------------------- | + | $tc | Function | 请见$tc参数说明 | 是 | 根据系统语言完成单复数替换:this.$tc('strings.plurals')
定义资源的内容通过json格式的key为“zero”、“one”、“two”、“few”、“many”和“other”区分。 | + + **表4** $tc参数说明 + + | 参数 | 类型 | 必填 | 描述 | + | ----- | ------ | ---- | ----- | + | path | string | 是 | 资源路径 | + | count | number | 是 | 要表达的值 | + +- 单复数格式化示例代码 + + ```html + +
+ + {{ $tc('strings.plurals', 0) }} + + {{ $tc('strings.plurals', 1) }} + + {{ $tc('strings.plurals', 2) }} + + {{ $tc('strings.plurals', 6) }} + + {{ $tc('strings.plurals', 50) }} + + {{ $tc('strings.plurals', 100) }} +
+ ``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md new file mode 100644 index 0000000000000000000000000000000000000000..9838ed3a9b2b4ed23312e49a9b608bf59ebbd02d --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-css.md @@ -0,0 +1,101 @@ +# CSS语法参考 + + +CSS是描述HML页面结构的样式语言。所有组件均存在系统默认样式,也可在页面CSS样式文件中对组件、页面自定义不同的样式。 + + +## 尺寸单位 + +1. 逻辑像素px(文档中以<length>表示): + 1. 默认卡片具有的逻辑宽度为150px(配置见[配置文件](js-service-widget-config-file.md#window)中的window小节),实际显示时会将页面布局缩放至屏幕实际宽度,如100px在宽度为300的卡片上,实际渲染为200物理像素(从150px向300物理像素,所有尺寸放大2倍)。 + 2. 额外配置autoDesignWidth为true时(配置见[配置文件](js-service-widget-config-file.md#window)中的window小节),逻辑像素px将按照屏幕密度进行缩放,如100px在屏幕密度为3的设备上,实际渲染为300物理像素。应用需要适配多种设备时,建议采用此方法。 + +2. 百分比(文档中以<percentage>表示):表示该组件占父组件尺寸的百分比,如组件的width设置为50%,代表其宽度为父组件的50%。 + + +## 样式导入 + +为了模块化管理和代码复用,CSS样式文件支持 \@import 语句,导入 CSS 文件。 + + +## 声明样式 + +每个页面目录下存在一个与布局hml文件同名的css文件,用来描述该hml页面中组件的样式,决定组件应该如何显示。 + +1. 内部样式,支持使用style、class属性来控制组件的样式。例如: + + ```html + +
+ Hello World +
+ ``` + + + ```css + /* index.css */ + .container { + justify-content: center; + } + ``` + +2. 文件导入,合并外部样式文件。例如,在common目录中定义样式文件style.css,并在index.css中进行导入: + + ```css + /* style.css */ + .title { + font-size: 50px; + } + ``` + + + ```css + /* index.css */ + @import '../../common/style.css'; + .container { + justify-content: center; + } + ``` + + +## 选择器 + +css选择器用于选择需要添加样式的元素,支持的选择器如下表所示: + +| 选择器 | 样例 | 样例描述 | +| -------- | -------- | -------- | +| .class | .container | 用于选择class="container"的组件。 | +| \#id | \#titleId | 用于选择id="titleId"的组件。 | + +示例: + + +```html + +
+ 标题 +
+ 内容 +
+
+``` + + +```css +/* 页面样式xxx.css */ +/* 对class="title"的组件设置样式 */ +.title { + font-size: 30px; +} +/* 对id="contentId"的组件设置样式 */ +#contentId { + font-size: 20px; +} +``` + + +## 选择器优先级 + +选择器的优先级计算规则与w3c规则保持一致(只支持:内联样式,id,class),其中内联样式为在元素style属性中声明的样式。 + +当多条选择器声明匹配到同一元素时,各类选择器优先级由高到低顺序为:内联样式 > id > class 。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md new file mode 100644 index 0000000000000000000000000000000000000000..6cd29b1341e3259773fd6212ac188137eec9ea18 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-syntax-hml.md @@ -0,0 +1,296 @@ +# HML语法参考 + + +HML(OpenHarmony Markup Language)是一套类HTML的标记语言,通过组件,事件构建出页面的内容。页面具备数据绑定、事件绑定、条件渲染和逻辑控制等高级能力。 + + +## 页面结构 + + +```html + +
+ Image Show +
+ +
+
+``` + + +## 数据绑定 + + +```html + +
+ {{content}} + {{key1}} {{key2}} + key1 {{key1}} + {{flag1 && flag2}} + {{flag1 || flag2}} + {{!flag1}} +
+``` + + +```json +{ + "data": { + "content": "Hello World!", + "key1": "Hello", + "key2": "World", + "flag1": true, + "flag2": false + } +} +``` + + +> **说明:** +> - key值支持对象操作符和数组操作符,如{{key.value}}、{{key[0]}}。 +> +> - 从 API Version 6 开始支持字符串拼接、逻辑运算和三元表达式。 +> - 字符串拼接: +> - 支持变量跟变量:{{key1}}{{key2}}等 +> - 支持常量跟变量: "my name is {{name}}, i am from {{city}}." "key1 {{key1}}" +> - 逻辑运算: +> - 与:{{flag1 && flag2}}(仅支持两个boolean变量间的与) +> - 或:{{flag1 || flag2}} (仅支持两个boolean变量间的或) +> - 非:{{!flag1}} (仅支持boolean变量的非运行) +> - 三元表达式 +> - {{flag? key1:key2}}(flag为boolean变量,key1和key2可以是变量,也可以是常量) +> - 注意事项 +> - 非boolean类型值进行bool运算默认为false +> - 以上所有变量解析跟运算解析均不支持嵌套 + +## 事件绑定 + +卡片仅支持click通用事件,事件的定义只能是直接命令式,事件定义必须包含action字段,用以说明事件类型。卡片支持两种事件类型:跳转事件(router)和消息事件(message)。跳转事件可以跳转到卡片提供方的OpenHarmony应用,消息事件可以将开发者自定义信息传递给卡片提供方。事件参数支持变量,变量以"{{}}"修饰。跳转事件中若定义了params字段,则在被拉起应用的onStart的intent中,可用"params"作为key将跳转事件定义的params字段的值取到。 + +- 跳转事件格式 + + 通过定义ability名称和携带的参数字段params直接跳转,可用"params"作为key提取到跳转事件定义的params字段值。 + + | 选择器 | 样例 | 默认值 | 样例描述 | + | ----------- | ------ | -------- | ---------------------------------------- | + | action | string | "router" | 事件类型。
- "router":用于应用跳转。
- "message":自定义点击事件。 | + | abilityName | string | - | 跳转ability名。 | + | params | Object | - | 跳转应用携带的额外参数。 | + + + ```json + { + "data": { + "mainAbility": "xxx.xxx.xxx" + }, + "actions": { + "routerEvent": { + "action": "router", + "abilityName": "{{mainAbility}}", + "params":{} + } + } + } + ``` + + 也可以使用want格式绑定参数跳转到目标应用,want定义了ability名称、包名、携带的参数字段等。 + + | 选择器 | 类型 | 默认值 | 样例描述 | + | ------ | ------ | -------- | ---------------------------------------- | + | action | string | "router" | 事件类型。
- "router":用于应用跳转。
- "message":自定义点击事件。 | + | want | Object | - | 跳转目标应用的信息,参考want格式表。 | + + **表1** want格式 + + | 选择器 | 类型 | 默认值 | 样例描述 | + | ----------- | -------------------- | ------------ | ---------------------------------------- | + | bundleName | string | - | 表示包描述。如果在Want中同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。 | + | abilityName | string | - | 表示待启动的Ability名称。 | + | action | string | - | 表示action选项描述。 | + | uri | string | - | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | + | type | string | "text/plain" | 表示MIME type类型描述,比如:"text/plain" 、 "image/*"等。 | + | flags | number | - | 表示处理Want的方式。默认传数字,具体参考[flags说明](../apis/js-apis-featureAbility.md#flags说明)。 | + | entities | Array\ | - | 类别,用于指定Intent的操作类别。 | + | parameters | {[key: string]: any} | - | 表示WantParams描述。 | + + + ```json + { + "data": { + "mainAbility": "xxx.xxx.xxx" + }, + "actions": { + "routerEventName1": { + "action": "router", + "want": { + "bundleName": "com.example.myapplication", + "abilityName": "com.example.entry.MainAbility" + } + }, + "routerEventName2": { + "action": "router", + "want": { + "action": "xxx.intent.action.DIAL", + "uri": "tel:12345678" + } + } + } + } + ``` + + 在API Version 8,want参数需要在app.js或app.ets文件的onCreate方法中调用[featureAbility.getWant](../apis/js-apis-featureAbility.md)接口接收相关参数。 + +- 消息事件格式 + + | 选择器 | 样例 | 默认值 | 样例描述 | + | ------ | ------ | ------- | ------------ | + | action | string | message | 表示事件类型。 | + | params | Object | - | 跳转应用携带的额外参数。 | + + + ```json + { + "actions": { + "activeEvent": { + "action": "message", + "params": {} + } + } + } + ``` + +- 绑定路由事件和消息事件 + + ```html + +
+ +
+ +
+
+ ``` + + +## 列表渲染 + + +```html + +
+ + +
+ {{$item.name}} +
+ +
+ {{value.name}} +
+ +
+ {{value.name}} +
+
+``` + + +```json +{ + "data": { + "array": [ + {"id": 1, "name": "jack", "age": 18}, + {"id": 2, "name": "tony", "age": 18} + ] + } +} +``` + +tid属性主要用来加速for循环的重渲染,旨在列表中的数据有变更时,提高重新渲染的效率。tid属性是用来指定数组中每个元素的唯一标识,如果未指定,数组中每个元素的索引为该元素的唯一id。例如上述tid="id"表示数组中的每个元素的id属性为该元素的唯一标识。for循环支持的写法如下: + +- for="array":其中array为数组对象,array的元素变量默认为$item。 + +- for="v in array":其中v为自定义的元素变量,元素索引默认为$idx。 + +- for="(i, v) in array":其中元素索引为i,元素变量为v,遍历数组对象array。 + +> **说明:** +> - 数组中的每个元素必须存在tid指定的数据属性,否则运行时可能会导致异常。 +> +> - 数组中被tid指定的属性要保证唯一性,如果不是则会造成性能损耗。比如,示例中只有id和name可以作为tid字段,因为它们属于唯一字段。 +> +> - tid不支持表达式。 +> +> - 不支持for嵌套使用。 +> +> - for对应的变量数组,当前要求数组中的object是相同类型,不支持多种object类型混合写在一个数组中。 + + +## 条件渲染 + +条件渲染分为2种:if/elif/else和show。 + +当使用if/elif/else写法时,节点必须是兄弟节点,否则编译无法通过。实例如下: + + +```html + +
+ Hello-TV + Hello-Wearable + Hello-World +
+``` + + +```json +{ + "data": { + "show": false, + "display": true + } +} +``` + +当show为真时,节点正常渲染;当show为假时,节点不渲染,效果等同display样式为none。 + + +```html + + Hello World +``` + + +```json +{ + "data": { + "visible": false + } +} +``` + + +## 逻辑控制块 + +<block>控制块使得循环渲染和条件渲染变得更加灵活;block在构建时不会被当作真实的节点编译。block标签只支持if属性。 + + +```html + +
+ + Hello + World + +
+``` + + +```json +{ + "data": { + "show": true + } +} +``` diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md new file mode 100644 index 0000000000000000000000000000000000000000..07b5eca24b2027f8b1045f9c3c74a4ea71bbe200 --- /dev/null +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-version-compatibility.md @@ -0,0 +1,62 @@ +# 低版本兼容 + + +卡片特性不断增加,使用了新特性的卡片,在不支持这些新特性的老系统上可能显示异常。可以在卡片工程中指定最小SDK版本,防止使用新特性的卡片推送安装在老的系统上。也可以参考本章节的内容,在卡片开发阶段做前向兼容适配。 + + +> **说明:** +> +> 低版本兼容能力从 API Version 6 开始支持。 + + +开发者可以通过JSON配置文件配置前向兼容能力。该文件提供了apiVersion属性用于兼容版本,该字段和卡片配置文件的数据字段data、事件字段actions同级。在apiVersion标签下定义的内容会基于当前运行版本信息,覆盖原始的data标签内容。 + + +示例如下: + + +假设JS服务卡片框架从API Version 6开始,支持引用系统内置资源颜色,从API Version 7开始支持slider组件(仅用于举例,不代表实际情况),则可以按照如下的方式,做前向兼容。 + + + +```html + +
+ hello world + +
+``` + + +xxx.json配置文件: + + + +```json +{ + "data": { + "myBackgroundColor": "#87ceeb", + "canUseSlider": "false" + }, + "apiVersion": { + "6": { + "myBackgroundColor": "@sys.color.fa_background" + }, + "7": { + "canUseSlider": "true" + } + } +} +``` + + +JS服务卡片开发框架会根据应用中的配置及当前系统运行版本,选取最合适的数据。 + + +假设系统运行版本在5及以下,则实际解析的myBackgroundColor值为\#87ceeb,canUseSlider值为false; + + +假设系统运行版本为6,则实际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为false; + + +假设系统运行版本为7及以上,则实际解析的际解析的myBackgroundColor值为\@sys.color.fa_background,canUseSlider值为true。 diff --git a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md index 3c313db67b3fce890adff06e4f3a4eb8e6fcfcd8..98a19c118a66b4b556ae269e216f33ebdb0a0828 100644 --- a/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md +++ b/zh-cn/application-dev/reference/native-lib/third_party_napi/napi.md @@ -9,7 +9,7 @@ Node-API是用于封装JavaScript能力为Native插件的API,独立于底层Ja Node-API可以去除底层的JavaScript引擎的差异,提供一套稳定的接口。 -OpenHarmony的Native API组件对Node-API的接口进行了重新实现,底层对接了ArkJS等引擎。当前支持Node-API标准库中的部分接口。 +OpenHarmony的Native API组件对Node-API的接口进行了重新实现,底层对接了ArkJS等引擎。当前支持[Node-API](https://nodejs.org/docs/v14.9.0/api/n-api.html)标准库中的部分接口。 ## Native API组件扩展的符号列表 diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 2ab9bcc05dbf63a2756fc61c0aed48df44111525..596eda8ed6b0c2ef48b1a5863752b4eb15804003 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -68,7 +68,7 @@ "when":"always" } } - ], + ] } } ``` diff --git a/zh-cn/application-dev/ui/js-framework-syntax-css.md b/zh-cn/application-dev/ui/js-framework-syntax-css.md index 9def147357018c331a88ede5c43bf35f652636cb..1c62aadebe72cd7e9854cf6be14c659a7de43077 100644 --- a/zh-cn/application-dev/ui/js-framework-syntax-css.md +++ b/zh-cn/application-dev/ui/js-framework-syntax-css.md @@ -79,7 +79,7 @@ css选择器用于选择需要添加样式的元素,支持的选择器如下 ```css /* 页面样式xxx.css */ -/\* 对所有div组件设置样式 \*/ +/* 对所有div组件设置样式 */ div { flex-direction: column; } @@ -95,13 +95,13 @@ div { .title, .content { padding: 5px; } -/\* 对class="container"的组件下的所有text设置样式 \*/ +/* 对class="container"的组件下的所有text设置样式 */ .container text { - color: \#007dff; + color: #007dff; } -/\* 对class="container"的组件下的直接后代text设置样式 \*/ +/* 对class="container"的组件下的直接后代text设置样式 */ .container > text { - color: \#fa2a2d; + color: #fa2a2d; } ``` diff --git a/zh-cn/application-dev/ui/ts-resource-access.md b/zh-cn/application-dev/ui/ts-resource-access.md index 7858ba7a8adee799dbf99aede2092ce54b21513a..faa397e8dd850efa2974c4ae44a785c8865bdd5c 100644 --- a/zh-cn/application-dev/ui/ts-resource-access.md +++ b/zh-cn/application-dev/ui/ts-resource-access.md @@ -8,7 +8,10 @@ 引用rawfile下资源时使用```"$rawfile('filename')"```的形式,filename需要表示为rawfile目录下的文件相对路径,文件名需要包含后缀,路径开头不可以以"/"开头。 > **说明:** +> > 资源描述符不能拼接使用,仅支持普通字符串如`'app.type.name'`。 +> +> `$r`返回值为Resource对象,可通过[getString](../../reference/apis/js-apis-resource-manager.md#getstring) 方法获取对应的字符串。 在xxx.ets文件中,可以使用在resources目录中定义的资源。 diff --git a/zh-cn/application-dev/ui/ui-js-components-switch.md b/zh-cn/application-dev/ui/ui-js-components-switch.md index 9430f6e94215b5d88a0a10374076598663cbba3c..e236251483a79026fdcc87663ead6d309a221329 100644 --- a/zh-cn/application-dev/ui/ui-js-components-switch.md +++ b/zh-cn/application-dev/ui/ui-js-components-switch.md @@ -52,10 +52,8 @@ switch为开关选择器,切换开启或关闭状态。具体用法请参考[s align-items: center; background-color: #F1F3F5; } -switch{ - // 选中时的字体颜色 +switch { texton-color: #002aff; - // 未选中时的字体颜色 textoff-color: silver; text-padding: 20px; font-size: 50px; diff --git a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md b/zh-cn/application-dev/ui/ui-ts-basic-components-button.md index 9983e643f1015dd8e4ecf4fe1449c6876b191565..06ff221c14b45531dc919dca123e6d1ac28f5b43 100644 --- a/zh-cn/application-dev/ui/ui-ts-basic-components-button.md +++ b/zh-cn/application-dev/ui/ui-ts-basic-components-button.md @@ -134,7 +134,7 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) 可以将按钮用于启动操作的任何用户界面元素。按钮会根据用户的操作触发相应的事件。如,在List容器里边通过点击按钮进行页面跳转: ```ts - // xxx.js + // xxx.ets import router from '@ohos.router' @Entry @@ -167,26 +167,27 @@ Button('Ok', { type: ButtonType.Normal, stateEffect: true }) ``` - ![zh-cn_image_0000001235626467](figures/zh-cn_image_0000001235626467.png) +​ ![zh-cn_image_0000001235626467](figures/zh-cn_image_0000001235626467.png) - 用于表单的提交 - 在用户登录/注册页面,用户的登录或注册的提交操作会用按钮。 + 在用户登录/注册页面,用户的登录或注册的提交操作会用按钮。 ```ts -// xxx.js -@Entry - @Component - struct ButtonCase2 { - build() { - Column() { - TextInput({ placeholder: 'input your username' }).margin({ top: 20 }) - TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 }) - Button('Register').width(300).margin({ top: 20 }) - }.padding(20) + // xxx.ets + @Entry + @Component + struct ButtonCase2 { + build() { + Column() { + TextInput({ placeholder: 'input your username' }).margin({ top: 20 }) + TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 }) + Button('Register').width(300).margin({ top: 20 }) + }.padding(20) + } } - } ``` + ![zh-cn_image_0000001190466492](figures/zh-cn_image_0000001190466492.png) diff --git a/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md b/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md index 8f704f9f69a725690f39e855e38a51477c6cfe1e..a162017315d13a063d7d5e7cb5fa0f7369af8d5f 100644 --- a/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md +++ b/zh-cn/application-dev/ui/ui-ts-basic-resource-file-categories.md @@ -75,7 +75,7 @@ base目录与限定词目录下面可以创建资源组目录(包括element、 | ------- | ---------------------------------------- | ---------------------------------------- | | element | 表示元素资源,以下每一类数据都采用相应的JSON文件来表征。
- boolean,布尔型
- color,颜色
- float,浮点型
- intarray,整型数组
- integer,整型
- pattern,样式
- plural,复数形式
- strarray,字符串数组
- string,字符串 | element目录中的文件名称建议与下面的文件名保持一致。每个文件中只能包含同一类型的数据。
- boolean.json
- color.json
- float.json
- intarray.json
- integer.json
- pattern.json
- plural.json
- strarray.json
- string.json | | media | 表示媒体资源,包括图片、音频、视频等非文本格式的文件。 | 文件名可自定义,例如:icon.png。 | -| profile | 表示其他类型文件,以原始文件形式保存。 | 文件名可自定义。 | +| rawfile | 表示其他类型文件,在应用构建为hap包后,以原始文件形式保存,不会被集成到resources.index文件中。 | 文件名可自定义。 | ### 媒体资源类型说明 diff --git a/zh-cn/application-dev/ui/ui-ts-local-storage.md b/zh-cn/application-dev/ui/ui-ts-local-storage.md index 9fb55fdaa18b4a90cc7f563dec0da43ddfac0533..02e927cb539e1ff478bb1942b9aa0a520db7dd9a 100644 --- a/zh-cn/application-dev/ui/ui-ts-local-storage.md +++ b/zh-cn/application-dev/ui/ui-ts-local-storage.md @@ -278,8 +278,8 @@ clear(): boolean ### 示例1(在一个Ability创建的LocalStorage) -```javascript -import Ability from '@ohos.appLication.Ability' +```ts +import Ability from '@ohos.application.Ability' export default class MainAbility extends Ability { storage : LocalStorage onCreate(want) { @@ -335,23 +335,23 @@ let storage = new LocalStorage({"PropA":47}); @Entry(storage) @Component struct ComA { - @LocalStorageLink("PropA") storLink : number = 1; + @LocalStorageLink("PropA") storLink: number = 1; build() { Column() { - Text(`Parent from LocalStorage $(this.storLink)`) + Text(`Parent from LocalStorage ${ this.storLink }`) .onClick(()=>this.storLink+=1) - Child() - } + Child() + } } } @Component struct Child{ - @LocalStorageLink("PropA") storLink : number = 1; + @LocalStorageLink("PropA") storLink: number = 1; build() { - Text(`Parent from LocalStorage $(this.storLink)`) - .onClick(()=>this.storLink1+=1) + Text(`Parent from LocalStorage ${ this.storLink }`) + .onClick(()=>this.storLink+=1) } } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/windowmanager/application-window-fa.md b/zh-cn/application-dev/windowmanager/application-window-fa.md index be0148a32c242e3d38c3baefbd6265aaa3ce0889..80131f59bc55955aa9e8427bd0cb977894063723 100644 --- a/zh-cn/application-dev/windowmanager/application-window-fa.md +++ b/zh-cn/application-dev/windowmanager/application-window-fa.md @@ -22,7 +22,7 @@ | 实例名 | 接口名 | 描述 | | -------- | -------- | -------- | -| window静态方法 | create(id:string,type:WindowType,callback:AsyncCallback]<Window>):void | 创建子窗口。
此接口仅可在`FA`模型下使用。 | +| window静态方法 | create(id:string,type:WindowType,callback:AsyncCallback<Window>):void | 创建子窗口。
此接口仅可在`FA`模型下使用。 | | window静态方法 | getTopWindow(callback:AsyncCallback<Window>):void | 获取当前应用内最后显示的窗口。
此接口仅可在`FA`模型下使用。 | | window静态方法 | find(id:string,callback:AsyncCallback<Window>):void | 查找`id`所对应的窗口。 | | Window | loadContent(path:string,callback:AsyncCallback<void>):void | 为当前窗口加载具体页面内容。 | diff --git a/zh-cn/application-dev/windowmanager/display-guidelines.md b/zh-cn/application-dev/windowmanager/display-guidelines.md index ef1ef4abb5c15e2711eb69cab51658809efd037a..b6bfaa63d306396da1d91d16048d4277de21c6ff 100644 --- a/zh-cn/application-dev/windowmanager/display-guidelines.md +++ b/zh-cn/application-dev/windowmanager/display-guidelines.md @@ -15,7 +15,6 @@ ```js import display from '@ohos.display' // 导入模块 -let disp; // disp用来保存默认Display display.getDefaultDisplay().then((disp) => { console.log('display.getDefaultDisplay success, display :' + JSON.stringify(disp)); }, (err) => { diff --git a/zh-cn/application-dev/windowmanager/window-overview.md b/zh-cn/application-dev/windowmanager/window-overview.md index f3e2ba39243ce42c7052249b967d9467550f8715..66592376084eccb141fa6399d9e116386bd24a5d 100644 --- a/zh-cn/application-dev/windowmanager/window-overview.md +++ b/zh-cn/application-dev/windowmanager/window-overview.md @@ -16,15 +16,15 @@ 在OpenHarmony中,窗口模块主要负责以下职责: -- 提供应用和系统界面的窗口对象。应用开发者通过窗口加载UI界面,实现界面显示功能。 +- **提供应用和系统界面的窗口对象。** 应用开发者通过窗口加载UI界面,实现界面显示功能。 -- 组织不同窗口的显示关系,即维护不同窗口间的叠加层次和位置属性。应用和系统的窗口具有多种类型,不同类型的窗口具有不同的默认位置和叠加层次(Z轴高度)。同时,用户操作也可以在一定范围内对窗口的位置和叠加层次进行调整。 +- **组织不同窗口的显示关系,即维护不同窗口间的叠加层次和位置属性。** 应用和系统的窗口具有多种类型,不同类型的窗口具有不同的默认位置和叠加层次(Z轴高度)。同时,用户操作也可以在一定范围内对窗口的位置和叠加层次进行调整。 -- 提供窗口装饰。窗口装饰指窗口标题栏和窗口边框。窗口标题栏通常包括窗口最大化、最小化及关闭按钮等界面元素,具有默认的点击行为,方便用户进行操作;窗口边框则方便用户对窗口进行拖拽缩放等行为。窗口装饰是系统的默认行为,开发者可选择启用/禁用,无需关注UI代码层面的实现。 +- **提供窗口装饰。窗口装饰指窗口标题栏和窗口边框。** 窗口标题栏通常包括窗口最大化、最小化及关闭按钮等界面元素,具有默认的点击行为,方便用户进行操作;窗口边框则方便用户对窗口进行拖拽缩放等行为。窗口装饰是系统的默认行为,开发者可选择启用/禁用,无需关注UI代码层面的实现。 -- 提供窗口动效。在窗口显示、隐藏及窗口间切换时,窗口模块通常会添加动画效果,以使各个交互过程更加连贯流畅。在OpenHarmony中,应用窗口的动效为默认行为,不需要开发者进行设置或者修改。 +- **提供窗口动效。** 在窗口显示、隐藏及窗口间切换时,窗口模块通常会添加动画效果,以使各个交互过程更加连贯流畅。在OpenHarmony中,应用窗口的动效为默认行为,不需要开发者进行设置或者修改。 -- 指导输入事件分发。即根据当前窗口的状态或焦点,进行事件的分发。触摸和鼠标事件根据窗口的位置和尺寸进行分发,而键盘事件会被分发至焦点窗口。应用开发者可以通过窗口模块提供的接口设置窗口是否可以触摸和是否可以获焦。 +- **指导输入事件分发。** 即根据当前窗口的状态或焦点,进行事件的分发。触摸和鼠标事件根据窗口的位置和尺寸进行分发,而键盘事件会被分发至焦点窗口。应用开发者可以通过窗口模块提供的接口设置窗口是否可以触摸和是否可以获焦。 ## 基本概念 @@ -33,17 +33,22 @@ ### 窗口类型 OpenHarmony的窗口模块将窗口界面分为系统窗口、应用窗口两种基本类型。 +- **系统窗口** -- 系统窗口 系统窗口指完成系统特定功能的窗口。如音量条、壁纸、通知栏、状态栏、导航栏等。 +- **应用窗口** -- 应用窗口 应用窗口区别于系统窗口,指与应用显示相关的窗口。根据显示内容的不同,应用窗口又分为应用主窗口、应用子窗口两种类型。 - - 应用主窗口 - 应用主窗口用于显示应用界面,会在"任务管理界面"显示。 - - 应用子窗口 - 应用子窗口用于显示应用的弹窗、悬浮窗等辅助窗口,不会在"任务管理界面"显示。 + - 应用主窗口 + + ​ 应用主窗口用于显示应用界面,会在"任务管理界面"显示。 + + - 应用子窗口 + + ​ 应用子窗口用于显示应用的弹窗、悬浮窗等辅助窗口,不会在"任务管理界面"显示。 + + ### 应用窗口模式 @@ -51,11 +56,11 @@ OpenHarmony的窗口模块将窗口界面分为系统窗口、应用窗口两种 应用窗口模式指应用主窗口启动时的显示方式。OpenHarmony目前支持全屏、分屏、自由窗口三种应用窗口模式。这种对多种应用窗口模式的支持能力,也称为操作系统的“多窗口能力”。 -- 全屏:应用主窗口启动时铺满整个屏幕。 +- **全屏** :应用主窗口启动时铺满整个屏幕。 -- 分屏:应用主窗口启动时占据屏幕的某个部分,当前支持二分屏。两个分屏窗口之间具有分界线,可通过拖拽分界线调整两个部分的窗口尺寸。 +- **分屏** :应用主窗口启动时占据屏幕的某个部分,当前支持二分屏。两个分屏窗口之间具有分界线,可通过拖拽分界线调整两个部分的窗口尺寸。 -- 自由窗口:自由窗口的大小和位置可自由改变。同一个屏幕上可同时显示多个自由窗口,这些自由窗口按照打开或者获取焦点的顺序在Z轴排布。当自由窗口被点击或触摸时,将导致其Z轴高度提升,并获取焦点。 +- **自由窗口** :自由窗口的大小和位置可自由改变。同一个屏幕上可同时显示多个自由窗口,这些自由窗口按照打开或者获取焦点的顺序在Z轴排布。当自由窗口被点击或触摸时,将导致其Z轴高度提升,并获取焦点。 ![windowMode](figures/windowMode.png) diff --git a/zh-cn/contribute/style-guide/style-guide-content-elements.md b/zh-cn/contribute/style-guide/style-guide-content-elements.md index b984629d236de6c4015dd4b7769077b4a6842011..6e4df91da149ba948da02bdc58abdcb0630ffc6a 100755 --- a/zh-cn/contribute/style-guide/style-guide-content-elements.md +++ b/zh-cn/contribute/style-guide/style-guide-content-elements.md @@ -32,6 +32,10 @@ 【规则】表格至少为两行两列。 +【规则】表格行数(Rows)应≤9行,列数(Columns)应≤4列,推荐2~3列。大于4列的表格需要拆分或将列内容合并,以减少列数;也可采用项目列表等形式改写。每个单元格中,内容所占行数不宜超过5行。 + +【规则】Markdown中,如果表格预览效果不佳,请采用减少列数、减少单元格内容中单个英文字符串长度、或将表格改写为项目列表等方式调整,以免影响可读性。 + 【规则】相同类型的表标题、表头,风格保持一致,采用名词或名词词组的形式。 同样对参数进行说明的表,不应出现“参数说明”、“参数解释”、“参数含义”、“参数意义”等不同的表头内容,需要全文保持统一。 @@ -48,6 +52,8 @@ 【规则】表格内容默认使用左对齐。 +【建议】如果表格的列数太多而行数较少,建议把表格的列转换成行。 + ## 图片 @@ -167,6 +173,13 @@ 【规则】中文文档中,缩略语全称中对应的字母大写。 +【规则】“[OpenHarmony术语表](https://gitee.com/openharmony/docs/blob/master/zh-cn/glossary.md)”中,术语名以“英文全称 (缩略语);中文全称”的形式写作;术语解释直接陈述术语内涵,不需要重复术语名。 + +| **正例** | **反例** | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| - Hardware Driver Foundation (HDF);硬件驱动框架
用于提供统一外设访问能力和驱动开发、管理框架。 | - HDF
Hardware Driver Foundation,硬件驱动框架,用于提供统一外设访问能力和驱动开发、管理框架。 | +| - ArkUI;方舟开发框架
一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。 | - ArkUI
是一套极简、高性能、跨设备应用设计研发的UI开发框架,支撑开发者高效地构建跨设备应用UI界面。 | + 【建议】一篇文档中某缩略语首次出现的位置(标题和表头除外),提供英文全称,可选提供中文全称。 【建议】开发板名称、设备名称等不作为术语或缩略语,不在术语表中体现。建议在文档中单独以表格或其他形式介绍。 diff --git a/zh-cn/contribute/template/js-template.md b/zh-cn/contribute/template/js-template.md index 5a38bc05af08e7d08ff96938d3ee4f4567f63a83..c39308ccc62161063ed688f4dee567d2cbc330f0 100644 --- a/zh-cn/contribute/template/js-template.md +++ b/zh-cn/contribute/template/js-template.md @@ -14,8 +14,8 @@ | 8 | 废弃接口说明 | 废弃内容不能直接删去,在废弃内容后面加标注deprecated,并使用“>”引用语法建议使用的替代方式,加上对应的链接。
示例:abandonmentMethod(deprecated)
> 从API Version 7 开始不再维护,建议使用[newMethod]\(#newmethod)替代。 | | 9 | 权限说明 | 与代码保持一致,下沉到各个方法、枚举、属性字段中。
1. 如果仅系统应用可申请,格式:
**需要权限:** ohos.permission.xxxx,仅系统应用可用。
2. 如果该权限所有应用可申请,格式:
**需要权限:** ohos.permission.xxxx
3. 如果该接口涉及多个权限,则采用“和、或”进行分割,格式:
**需要权限:** ohos.permission.A 和 ohos.permission.B
**需要权限:** ohos.permission.A 或 ohos.permission.B | | 10 | @syscap | 1. 每个方法都需要进行描述,格式:
**系统能力**:SystemCapability.xxx.xxx
2. 每个表格(属性、枚举、常量、变量)可统一进行说明,分两种情况:
1)每个表格下系统能力无差异的,同方法的写法:
**系统能力**:SystemCapability.xxx.xxx
2)有差异的:在每一个表格项里进行描述。 | -| 11 | @system api | 1. 如果某个模块全部接口均为system api,则在模块开头的版本说明下一行,增加:
- 本模块接口为系统接口。
2. 如果某个接口为system api,仅供OEM厂商使用,则需要在描述中增加:
此接口为系统接口。 | -| 12 | @FAModelOnly
@StageModelOnly | 1. 如果某个模块均只针对某模型实现,则在模块开头的版本说明下一行,增加:
- 本模块接口仅可在FA模型/Stage模型下使用。
2. 如果某个接口只针对某模型实现,则需要在描述中增加:
此接口仅可在FA模型/Stage模型下使用。 | +| 11 | @system api | 1. 如果某个模块全部接口均为system api,则在模块开头的版本说明下一行,增加:
- 本模块接口为系统接口。
2. 如果某个接口为system api,仅供OEM厂商使用,则需要在描述中增加:
**系统接口:** 此接口为系统接口。 | +| 12 | @FAModelOnly
@StageModelOnly | 1. 如果某个模块均只针对某模型实现,则在模块开头的版本说明下一行,增加:
- 本模块接口仅可在FA模型/Stage模型下使用。
2. 如果某个接口只针对某模型实现,则需要在描述中增加:
**模型约束:** 此接口仅可在FA模型/Stage模型下使用。 | | 13 | 异步接口说明(callback、Promise) | 对于callback、Promise在方法描述、参数说明、返回值说明的具体描述要求如下:
**callback**的固定句式:
方法介绍:xxx(方法描述)。使用callback异步回调。
参数说明:
**callback\**:回调函数。返回true表示xxx;返回false表示xxx。
**callback\**:回调函数,返回xxx。例如”回调函数,返回音频采集器对象。“
**AsyncCallback\**:回调函数。当具体的操作(视具体接口功能描述)成功,err为undefined,否则为错误对象。
**AsyncCallback\**:回调函数。当具体的操作(视具体接口功能描述)成功,err为undefined,data为获取到的Object x;否则为错误对象。
**Promise**的固定句式:
方法介绍:xxx(方法描述)。使用Promise异步回调。
参数说明:
**Promise\**:Promise对象。返回true表示xxx;返回false表示xxx。
**Promise\**:Promise对象,返回xxx。例如”Promise对象,返回音频采集器对象。“
**Promise\**:Promise对象。无返回结果的Promise对象。 | | 14 | 示例代码语言 | 所有的示例代码采用代码块的样式,并标记开发语言。
JS和eTS通用的标注`js`;仅eTS可用的,标注`ts`。 | | 15 | 链接写法 | 格式:[链接文字]\(链接内容)
跨文件夹链接:[指南]\(\.\./../xxx/xxx.md),一个`../`表示上移一层文件夹。
页面内链接:[接口A7+]\(#xxxa7),页面内链接和需要链接到的标题保持一致,全小写无特殊符号无标签。 | @@ -129,9 +129,9 @@ import call from '@ohos.telephony.call'; 在此处给出方法描述。说明请参考上述写作说明第4、5点。 -此接口仅可在Stage模型下使用。(可选) +**模型约束**:此接口仅可在FA模型下使用。(如不涉及可删除) -此接口为系统接口。(可选) +**系统接口**:此接口为系统接口。(如不涉及可删除) **需要权限**:ohos.permission.xxx(如不涉及可删除,如果是系统权限要说明) @@ -185,9 +185,9 @@ import call from '@ohos.telephony.call'; 在此处给出方法描述。说明请参考上述写作说明第4、5点。 -此接口仅可在Stage模型下使用。(可选) +**模型约束**:此接口仅可在FA模型下使用。(如不涉及可删除) -此接口为系统接口。(可选) +**系统接口**:此接口为系统接口。(如不涉及可删除) **需要权限**:ohos.permission.xxx(如不涉及可删除,如果是系统权限要说明) diff --git a/zh-cn/design/hdi-design-specifications.md b/zh-cn/design/hdi-design-specifications.md index 036d191fa13983763271425d39187296306c39b4..03d9969594a2482bbb2e4c44fb7608309e4f6c51 100644 --- a/zh-cn/design/hdi-design-specifications.md +++ b/zh-cn/design/hdi-design-specifications.md @@ -475,7 +475,7 @@ GetExecutorInfo([out] struct ExecutorInfo executorInfo); #### 数组类型使用约束 -| IDL容器数据类型 | C++数据类型 | C数据类型 | +| IDL数组数据类型 | C++数据类型 | C数据类型 | | --------- | -------------- | ----------- | | T[] | std::vector | T*,int size | diff --git a/zh-cn/device-dev/device-dev-guide.md b/zh-cn/device-dev/device-dev-guide.md index 3203ed3ce6a79e5c6d0a580805c21b03bb2bfa39..ca61f8fcfebcd60aead12103448302cb390ecd49 100644 --- a/zh-cn/device-dev/device-dev-guide.md +++ b/zh-cn/device-dev/device-dev-guide.md @@ -37,7 +37,7 @@ OpenHarmony也提供了一系列可选的系统组件,方便设备开发者按 | 了解OpenHarmony | 整体认知OpenHarmony | - [OpenHarmony概述](https://gitee.com/openharmony)
- [术语](../glossary.md) | | 获取开发资源 | 准备开发前相关资源 | - [获取源码](get-code/sourcecode-acquire.md)
- [获取工具](get-code/gettools-acquire.md) | | 快速入门 | 快速熟悉OpenHarmony环境搭建、编译、烧录、调测、运行 | - [轻量和小型系统快速入门](quick-start/quickstart-ide-lite-overview.md) | -| 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [轻量系统内核开发指南](kernel/kernel-mini-overview.md)
- [小型系统内核开发指南](kernel/kernel-small-overview.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-mini-lite.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | +| 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [轻量系统内核开发指南](kernel/kernel-mini-overview.md)
- [小型系统内核开发指南](kernel/kernel-small-overview.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-all.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | | 进阶开发 | 结合系统能力开发智能设备 | - [WLAN连接类产品](guide/device-wlan-led-control.md)
- [无屏摄像头类产品](guide/device-iotcamera-control-overview.md)
- [带屏摄像头类产品](guide/device-camera-control-overview.md) | | 移植适配 | - 针对特定芯片做移植适配
- 对三方库进行移植适配
- 三方厂商移植案例
| - [轻量系统芯片移植指导](porting/porting-minichip.md)
- [小型系统芯片移植指导](porting/porting-smallchip-prepare-needs.md)
- [轻量和小型系统三方库移植指导](porting/porting-thirdparty-overview.md)
- [带屏解决方案之恒玄芯片移植案例](porting/porting-bes2600w-on-minisystem-display-demo.md)
- [Combo解决方案之ASR芯片移植案例](porting/porting-asr582x-combo-demo.md)
- [物联网解决方案之芯海cst85芯片移植案例](porting/porting-cst85f01-combo-demo.md)
- [轻量系统STM32F407芯片移植案例](porting/porting-stm32f407-on-minisystem-eth.md)
- [Combo解决方案之W800芯片移植案例](porting/porting-w800-combo-demo.md)
- [小型设备STM32MP1芯片移植案例](porting/porting-stm32mp15xx-on-smallsystem.md)| | 贡献组件 | 为OpenHarmony贡献功能组件 | - [HPM Part 介绍](hpm-part/hpm-part-about.md)
- [HPM Part 开发指导](hpm-part/hpm-part-development.md)
- [HPM Part 参考](hpm-part/hpm-part-reference.md) | @@ -50,7 +50,7 @@ OpenHarmony也提供了一系列可选的系统组件,方便设备开发者按 | 了解OpenHarmony | 整体认知OpenHarmony | - [OpenHarmony概述](https://gitee.com/openharmony)
- [术语](../glossary.md) | | 获取开发资源 | 准备开发前相关资源 | - [获取源码](get-code/sourcecode-acquire.md)
- [获取工具](get-code/gettools-acquire.md) | | 快速入门 | 快速熟悉OpenHarmony环境搭建、编译、烧录、调测、运行 | - [标准系统快速入门](quick-start/quickstart-ide-standard-overview.md) | -| 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [内核开发指南](kernel/kernel-standard.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-standard-large.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | +| 基础能力使用 | 使用OpenHarmony提供的基础能力 | - [内核开发指南](kernel/kernel-standard.md)
- [驱动开发指南](driver/driver-hdf-overview.md)
- [子系统开发指南](subsystems/subsys-build-all.md)
- [安全指南](security/security-guidelines-overall.md)
- [隐私保护](security/security-privacy-protection.md) | | 进阶开发 | 结合系统能力开发智能设备 | - [时钟应用开发指导](guide/device-clock-guide.md)
- [平台驱动开发示例](guide/device-driver-demo.md)
- [外设驱动开发示例](guide/device-outerdriver-demo.md) | | 移植适配 | - 针对特定芯片做移植适配
- 快速移植OpenHarmony Linux内核的方法| - [标准系统芯片移植指导](porting/standard-system-porting-guide.md)
- [一种快速移植OpenHarmony Linux内核的方法](porting/porting-linux-kernel.md) | | 贡献组件 | 为OpenHarmony贡献功能组件 | - [HPM Part 介绍](hpm-part/hpm-part-about.md)
- [HPM Part 开发指导](hpm-part/hpm-part-development.md)
- [HPM Part 参考](hpm-part/hpm-part-reference.md) | diff --git a/zh-cn/device-dev/driver/driver-peripherals-motion-des.md b/zh-cn/device-dev/driver/driver-peripherals-motion-des.md new file mode 100644 index 0000000000000000000000000000000000000000..3d3608cbdf95cf412346a8d9ed5f9ebfbe4ea31f --- /dev/null +++ b/zh-cn/device-dev/driver/driver-peripherals-motion-des.md @@ -0,0 +1,252 @@ +# 手势识别 + +## 概述 + +### 功能简介 + +手势识别模块作为端侧设备不可或缺的一部分,为用户提供手势识别控制能力。当前支持的手势识别类型有拿起、翻转、摇一摇、旋转屏等。 + +基于HDF(Hardware Driver Foundation)驱动框架开发的手势识别驱动,能够屏蔽硬件器件差异,为上层MSDP(Multimodal Sensor +Data Platform)服务层提供稳定的手势识别控制能力接口,包括手势识别使能/去使能、手势识别订阅/去订阅等。 + +手势识别驱动框架如图1所示,上层为Framework层,提供MSDP服务,通过DAL层的Motion HDI Client与Motion HDI Server进行交互;而Motion HDI Server可调用Motion HDI实现类接口,从而实现上层服务的手势识别使能/去使能、手势识别订阅/去订阅等能力。 + +**图1** 手势识别驱动框架 + +![1660105057660](figures/手势识别驱动框架.png) + +### 运作机制 + +通过介绍手势识别驱动模型的加载以及运行流程,对模型内部关键组件以及关联组件之间的关系进行了划分,整体加载流程如图2所示: + +**图 2** 手势识别驱动运行图 + +![1660122293156](figures/手势识别驱动运行图.png) + +1. MSDP:上层综合传感信息处理平台服务层,当HDI接口服务实例获取成功后可以直接调用Motion HDI接口。 +2. IDL:接口抽象层。MSDP服务层首先从Motion Proxy获取到Motion HDI接口服务实例。而Motion Proxy获取到的接口实例是由IService Manager进行分配。当MSDP服务层成功获取到Motion HDI接口服务实例后,MSDP服务层就可以直接调用Motion Proxy中的HDI接口,然后通过IPC(Inter-Process Communication)调用到Motion Stub,从而调用到Motion Service的接口。这部分是由工具自动生成的代码,不用器件厂商自己开发。 +3. HD IService:HDI Service中包括Motion Interface Driver、Motion Service和Motion Impl三个部分。其中Motion Interface Driver为手势识别接口的驱动代码,在这部分驱动代码中通过定义一个struct HdfDriverEntry类型的结构体变量,实现此变量中的的Init、Bind和Release函数描述驱动能力,函数内部通过HDF_INIT宏加载驱动。Motion Service为手势识别服务接口类,具体的实现在Motion Impl中描述。此部分代码需要器件厂商根据自己器件来开发。 + +## 开发指导 + +### 场景介绍 + +手势识别驱动的主要工作是为上层MSDP服务提供稳定的使能/去使能手势识别服务,订阅/取消订阅手势识别数据回调函数的功能。可应用于拿起、翻转、摇一摇、旋转屏等手势识别场景。 + +### 接口说明 + +**表1** 接口功能介绍 + +| 接口名 | 功能介绍 | +| ------------------------------------------------------------ | ---------------------------- | +| int32_t EnableMotion(int32_t motionType) | 使能一种手势识别类型,只有数据订阅者使能手势识别后,才能获取订阅的手势识别数据。 | +| int32_t DisableMotion(int32_t motionType) | 去使能手势识别。 | +| int32_t Register(const sptr\ &callbackObj) | 订阅者成功注册手势识别数据回调函数,系统会将获取到的手势识别数据上报给订阅者。 | +| int32_t Unregister(const sptr\ &callbackObj) | 取消订阅手势识别数据回调函数。 | + +### 开发步骤 + +开发步骤分为两个大步骤。 + +1. 基于HDF驱动框架,完成手势识别用户态驱动开发。 +2. 厂商实现EnableMotion、DisableMotion、Register和Unregister接口功能。 + +手势识别目录结构及各部分功能简介。 + +```undefined +/drivers/peripheral/motion # 此目录具体实现需要厂商根据自己的器件进行开发 +├── hdi_service # 手势识别模块对上层MSDP服务提供的驱动能力 +├── test # 手势识别模块测试代码 +│ └── unittest\hdi # 手势识别模块HDI单元测试代码 +``` + +下面结合DEMO实例,介绍如何基于HDF驱动框架,手势识别用户态驱动开发。具体实现请参考 [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp)。 + +手势识别用户态驱动开发, 主要完成Bind、Init、Release、Dispatch函数接口实现。其中Bind函数为驱动对外提供的服务能力,Init函数为系统加载驱动前需要的一些初始化的操作,Release函数的主要作用为当系统加载驱动调用Init函数失败时对资源进行回收操作。 + +```c++ +// 自定义的HdfMotionInterfaceHost对象 +struct HdfMotionInterfaceHost { + struct IDeviceIoService ioService; + OHOS::sptr stub; +}; + +// 服务接口调用响应接口 +static int32_t MotionInterfaceDriverDispatch(struct HdfDeviceIoClient *client, int cmdId, struct HdfSBuf *data, + struct HdfSBuf *reply) +{ + auto *hdfMotionInterfaceHost = CONTAINER_OF(client->device->service, struct HdfMotionInterfaceHost, ioService); + + OHOS::MessageParcel *dataParcel = nullptr; + OHOS::MessageParcel *replyParcel = nullptr; + OHOS::MessageOption option; + + if (SbufToParcel(data, &dataParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s: invalid data sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + if (SbufToParcel(reply, &replyParcel) != HDF_SUCCESS) { + HDF_LOGE("%{public}s: invalid reply sbuf object to dispatch", __func__); + return HDF_ERR_INVALID_PARAM; + } + + return hdfMotionInterfaceHost->stub->SendRequest(cmdId, *dataParcel, *replyParcel, option); +} + +// 初始化接口 +int HdfMotionInterfaceDriverInit(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGI("HdfMotionInterfaceDriverInit enter"); + return HDF_SUCCESS; +} + +// Motion驱动对外提供的服务绑定到HDF框架 +int HdfMotionInterfaceDriverBind(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGI("HdfMotionInterfaceDriverBind enter"); + + auto *hdfMotionInterfaceHost = new (std::nothrow) HdfMotionInterfaceHost; + if (hdfMotionInterfaceHost == nullptr) { + HDF_LOGE("%{public}s: failed to create HdfMotionInterfaceHost object", __func__); + return HDF_FAILURE; + } + + hdfMotionInterfaceHost->ioService.Dispatch = MotionInterfaceDriverDispatch; + hdfMotionInterfaceHost->ioService.Open = NULL; + hdfMotionInterfaceHost->ioService.Release = NULL; + + auto serviceImpl = IMotionInterface::Get(true); + if (serviceImpl == nullptr) { + HDF_LOGE("%{public}s: failed to get of implement service", __func__); + return HDF_FAILURE; + } + + hdfMotionInterfaceHost->stub = OHOS::HDI::ObjectCollector::GetInstance().GetOrNewObject(serviceImpl, + IMotionInterface::GetDescriptor()); + if (hdfMotionInterfaceHost->stub == nullptr) { + HDF_LOGE("%{public}s: failed to get stub object", __func__); + return HDF_FAILURE; + } + + deviceObject->service = &hdfMotionInterfaceHost->ioService; + return HDF_SUCCESS; +} + +// 释放Motion驱动中的资源 +void HdfMotionInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGI("HdfMotionInterfaceDriverRelease enter"); + auto *hdfMotionInterfaceHost = CONTAINER_OF(deviceObject->service, struct HdfMotionInterfaceHost, ioService); + delete hdfMotionInterfaceHost; + hdfMotionInterfaceHost = nullptr; +} + +// 注册Motion驱动入口数据结构体对象 +struct HdfDriverEntry g_motioninterfaceDriverEntry = { + .moduleVersion = 1, + .moduleName = "motion_service", + .Bind = HdfMotionInterfaceDriverBind, + .Init = HdfMotionInterfaceDriverInit, + .Release = HdfMotionInterfaceDriverRelease, +}; + +// 调用HDF_INIT将驱动入口注册到HDF框架中,在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动,当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 +HDF_INIT(g_userAuthInterfaceDriverEntry); +``` + + +### 调测验证 + +测试代码开发步骤: + +1. 通过调用IMotionInterface::Get()获取到手势识别实例,并赋给IMotionInterface类型的智能指针对象g_motionInterface。 + +2. 通过g_motionInterface实例调用Register接口注册回调,回调函数需要根据自己的需求来设计。 + +3. 通过g_motionInterface实例调用EnableMotion接口使能Motion类型,当前支持拿起(HDF_MOTION_TYPE_PICKUP)、翻转(HDF_MOTION_TYPE_FLIP)、摇一摇(HDF_MOTION_TYPE_SHAKE)、旋转(HDF_MOTION_TYPE_ROTATION)等手势识别类型。 + +4. 通过g_motionInterface实例调用DisableMotion接口去使能手势识别类型。 + +5. 通过g_motionInterface实例调用Unregister取消订阅Motion数据回调函数。注意取消订阅必须先调用Register接口注册回调,否则Unregister会返回失败。 + + 测试代码实例如下: + + ```c++ + using namespace OHOS::HDI::Motion::V1_0; + using namespace testing::ext; + + namespace { + sptr g_motionInterface = nullptr; + sptr g_motionCallback = new MotionCallbackService(); + sptr g_motionCallbackUnregistered = new MotionCallbackService(); + } + + class HdfMotionTest : public testing::Test { + public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + }; + + void HdfMotionTest::SetUpTestCase() + { + // 1.获取手势识别实例 + g_motionInterface = IMotionInterface::Get(); + } + + void HdfMotionTest::TearDownTestCase() + { + } + + void HdfMotionTest::SetUp() + { + } + + void HdfMotionTest::TearDown() + { + } + + HWTEST_F(HdfMotionTest, EnableMotion_001, TestSize.Level1) + { + if (g_motionInterface == nullptr) { + ASSERT_NE(nullptr, g_motionInterface); + return; + } + + vector vec; + vec.push_back(HDF_MOTION_TYPE_PICKUP); + vec.push_back(HDF_MOTION_TYPE_FLIP); + vec.push_back(HDF_MOTION_TYPE_SHAKE); + vec.push_back(HDF_MOTION_TYPE_ROTATION); + + // 2.订阅手势识别数据回调函数 + int32_t ret = g_motionInterface->Register(g_motionCallback); + EXPECT_EQ(HDF_SUCCESS, ret); + + for (int i = 0; i < vec.size(); i++) { + // 3.使能手势识别 + ret = g_motionInterface->EnableMotion(vec[i]); + if (ret == HDF_SUCCESS) { + printf("Motion %d enabled successfully\n", vec[i]); + } else { + printf("Motion %d enable failed\n", vec[i]); + } + EXPECT_EQ(HDF_SUCCESS, ret); + OsalSleep(15); + // 4.去使能手势识别 + ret = g_motionInterface->DisableMotion(vec[i]); + if (ret == HDF_SUCCESS) { + printf("Motion %d disabled successfully\n", vec[i]); + } else { + printf("Motion %d disable failed\n", vec[i]); + } + EXPECT_EQ(HDF_SUCCESS, ret); + OsalSleep(2); + } + // 5.取消订阅手势识别数据回调函数 + ret = g_motionInterface->Unregister(g_motionCallback); + EXPECT_EQ(HDF_SUCCESS, ret); + } + ``` + \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-adc-develop.md b/zh-cn/device-dev/driver/driver-platform-adc-develop.md index 8c42784ae0aa08fb0c55725d0c665fd1b4bf16ea..00f17c7790ef4eccb41a75f97d94b9da3d0dff1c 100755 --- a/zh-cn/device-dev/driver/driver-platform-adc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-adc-develop.md @@ -34,35 +34,40 @@ struct AdcMethod { ## 开发步骤 -ADC模块适配的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +ADC模块适配必选的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 -1. 实例化驱动入口: +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. 配置属性文件: +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加adc_config.hcs器件属性文件。 -3. 实例化ADC控制器对象: +3. 实例化ADC控制器对象 - 初始化AdcDevice成员。 - 实例化AdcDevice成员AdcMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化AdcDevice成员AdcMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. 驱动调试: +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,信号采集的成功与否等。 ## 开发实例 接下来以adc_hi35xx.c为示例, 展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 ADC驱动入口参考: - ADC模块这种类型的控制器会出现很多个设备挂接的情况,因而在HDF框架中首先会为这类型的设备创建一个管理器对象。这样,需要打开某个设备时,管理器对象会根据指定参数查找到指定设备。 + ADC控制器会出现多个设备挂接的情况,因而在HDF框架中首先会为此类型的设备创建一个管理器对象。这样,需要打开某个设备时,管理器对象会根据指定参数查找到指定设备。 ADC管理器的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的AdcDeviceAdd函数,它会实现相应功能。 @@ -72,9 +77,9 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, .moduleVersion = 1, .Init = Hi35xxAdcInit, .Release = Hi35xxAdcRelease, - .moduleName = "hi35xx_adc_driver",//【必要且与HCS文件里面的名字匹配】 + .moduleName = "hi35xx_adc_driver", //【必要且与HCS文件里面的名字匹配】 }; - HDF_INIT(g_hi35xxAdcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_hi35xxAdcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 // 核心层adc_core.c管理器服务的驱动入口 struct HdfDriverEntry g_adcManagerEntry = { @@ -86,8 +91,13 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, HDF_INIT(g_adcManagerEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在adc_config.hcs中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层AdcDevice相关成员的默认值或限制范围有密切关系。 - 统一服务模式的特点是device_info文件中第一个设备节点必须为ADC管理器,其各项参数必须如下设置: +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在adc_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层AdcDevice相关成员的默认值或限制范围有密切关系。 + + 统一服务模式的特点是device_info文件中第一个设备节点必须为ADC管理器,其各项参数必须如下设置: + + | 成员名 | 值 | | -------- | -------- | | moduleName | 固定为HDF_PLATFORM_ADC_MANAGER | @@ -95,6 +105,7 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, | policy | 具体配置为0,不发布服务 | | deviceMatchAttr | 没有使用,可忽略 | + 从第二个节点开始配置具体ADC控制器信息,此节点并不表示某一路ADC控制器,而是代表一个资源性质设备,用于描述一类ADC控制器的信息。本例只有一个ADC设备,如有多个设备,则需要在device_info文件增加deviceNode信息,以及在adc_config文件中增加对应的器件属性。 - device_info.hcs配置参考 @@ -113,13 +124,14 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, serviceName = "HDF_PLATFORM_ADC_MANAGER"; } device1 :: deviceNode { - policy = 0; // 等于0,不需要发布服务 - priority = 55; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "hi35xx_adc_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - serviceName = "HI35XX_ADC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hisilicon_hi35xx_adc";//【必要】用于配置控制器私有数据,要与adc_config.hcs中对应控制器保持一致 - } // 具体的控制器信息在 adc_config.hcs 中 + policy = 0; // 等于0,不需要发布服务。 + priority = 55; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "hi35xx_adc_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HI35XX_ADC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_adc";//【必要】用于配置控制器私有数据,要与adc_config.hcs中对应控制器保持一致, + // 具体的控制器信息在adc_config.hcs中。 + } } } } @@ -154,30 +166,31 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层AdcDevice对象的初始化为核心,包括初始化厂商自定义结构体(传递参数和数据),实例化AdcDevice成员AdcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层AdcDevice对象的初始化为核心,包括初始化厂商自定义结构体(传递参数和数据),实例化AdcDevice成员AdcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + - 自定义结构体参考。 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且adc_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层AdcDevice对象,例如设备号、总线号等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且adc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层AdcDevice对象,例如设备号、总线号等。 ``` struct Hi35xxAdcDevice { - struct AdcDevice device;//【必要】是核心层控制对象,具体描述见下面 + struct AdcDevice device; //【必要】是核心层控制对象,具体描述见下面。 volatile unsigned char *regBase;//【必要】寄存器基地址 volatile unsigned char *pinCtrlBase; - uint32_t regBasePhy; //【必要】寄存器物理基地址 - uint32_t regSize; //【必要】寄存器位宽 - uint32_t deviceNum; //【必要】设备号 - uint32_t dataWidth; //【必要】信号接收的数据位宽 - uint32_t validChannel; //【必要】有效通道 - uint32_t scanMode; //【必要】扫描模式 + uint32_t regBasePhy; //【必要】寄存器物理基地址 + uint32_t regSize; //【必要】寄存器位宽 + uint32_t deviceNum; //【必要】设备号 + uint32_t dataWidth; //【必要】信号接收的数据位宽 + uint32_t validChannel; //【必要】有效通道 + uint32_t scanMode; //【必要】扫描模式 uint32_t delta; uint32_t deglitch; uint32_t glitchSample; - uint32_t rate; //【必要】采样率 + uint32_t rate; //【必要】采样率 }; - // AdcDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // AdcDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct AdcDevice { const struct AdcMethod *ops; OsalSpinlock spin; @@ -188,7 +201,9 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, }; ``` - - AdcDevice成员回调函数结构体AdcMethod的实例化,AdcLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 + - AdcDevice成员回调函数结构体AdcMethod的实例化。 + + AdcLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 ``` @@ -202,7 +217,7 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -227,7 +242,7 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, int32_t ret; struct DeviceResourceNode *childNode = NULL; ... - // 遍历、解析adc_config.hcs中的所有配置节点,并分别调用Hi35xxAdcParseInit函数来初始化device + // 遍历、解析adc_config.hcs中的所有配置节点,并分别调用Hi35xxAdcParseInit函数来初始化device。 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { ret = Hi35xxAdcParseInit(device, childNode);// 函数定义见下 ... @@ -253,12 +268,12 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, hi35xx->device.priv = (void *)node; //【必要】存储设备属性 hi35xx->device.devNum = hi35xx->deviceNum;//【必要】初始化AdcDevice成员 hi35xx->device.ops = &g_method; //【必要】AdcMethod的实例化对象的挂载 - ret = AdcDeviceAdd(&hi35xx->device); //【必要且重要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层 + ret = AdcDeviceAdd(&hi35xx->device); //【必要且重要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 ... return HDF_SUCCESS; __ERR__: - if (hi35xx != NULL) { // 不成功的话,需要反向执行初始化相关函数 + if (hi35xx != NULL) { // 不成功的话,需要反向执行初始化相关函数。 if (hi35xx->regBase != NULL) { OsalIoUnmap((void *)hi35xx->regBase); hi35xx->regBase = NULL; @@ -273,7 +288,7 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -281,7 +296,10 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作的前提是在Init函数中具备对应赋值的操作。 ``` @@ -289,7 +307,7 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, { const struct DeviceResourceNode *childNode = NULL; ... - // 遍历、解析adc_config.hcs中的所有配置节点,并分别进行release操作 + // 遍历、解析adc_config.hcs中的所有配置节点,并分别进行Release操作。 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { Hi35xxAdcRemoveByNode(childNode);// 函数定义见下 } @@ -307,12 +325,12 @@ ADC模块适配的三个环节是配置属性文件,实例化驱动入口, ... ret = drsOps->GetUint32(node, "deviceNum", (uint32_t *)&deviceNum, 0); ... - // 可以调用AdcDeviceGet函数通过设备的deviceNum获取AdcDevice对象,以及调用AdcDeviceRemove函数来释放AdcDevice对象的内容 + // 可以调用AdcDeviceGet函数通过设备的deviceNum获取AdcDevice对象,以及调用AdcDeviceRemove函数来释放AdcDevice对象的内容。 device = AdcDeviceGet(deviceNum); if (device != NULL && device->priv == node) { AdcDevicePut(device); AdcDeviceRemove(device); //【必要】主要是从管理器驱动那边移除AdcDevice对象 - hi35xx = (struct Hi35xxAdcDevice *)device;//【必要】通过强制转换获取自定义的对象并进行release操作 + hi35xx = (struct Hi35xxAdcDevice *)device;//【必要】通过强制转换获取自定义的对象并进行Release操作 OsalIoUnmap((void *)hi35xx->regBase); OsalMemFree(hi35xx); } diff --git a/zh-cn/device-dev/driver/driver-platform-dac-develop.md b/zh-cn/device-dev/driver/driver-platform-dac-develop.md index a0aa6e786ede96eaa6e94d20e3553ab8dafe1c3e..96df8a728013b1ef18d58c2a904288871df95dfc 100644 --- a/zh-cn/device-dev/driver/driver-platform-dac-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-dac-develop.md @@ -8,8 +8,8 @@ DAC(Digital to Analog Converter)是一种通过电流、电压或电荷的 DAC模块支持数模转换的开发。它主要用于: -1. 作为过程控制计算机系统的输出通道,与执行器相连,实现对生产过程的自动控制。 -2. 在利用反馈技术的魔术转换器设计中,作为重要的功能模块呈现。 +- 作为过程控制计算机系统的输出通道,与执行器相连,实现对生产过程的自动控制。 +- 在利用反馈技术的魔术转换器设计中,作为重要的功能模块呈现。 ### 基本概念 @@ -25,13 +25,13 @@ DAC模块支持数模转换的开发。它主要用于: 转换速度一般由建立时间决定。从输入由全0突变为全1时开始,到输出电压稳定在FSR±½LSB范围(或以FSR±x%FSR指明范围)内为止,这段时间称为建立时间,它是DAC的最大响应时间,所以用它衡量转换速度的快慢。 - 满量程范围FSR( Full Scale Range ),是指DAC输出信号幅度的最大范围,不同的DAC有不同的满量程范围, 该范围可以用正、负电流或者正、负电压来限制 。 + - 满量程范围FSR(Full Scale Range),是指DAC输出信号幅度的最大范围,不同的DAC有不同的满量程范围,该范围可以用正、负电流或者正、负电压来限制。 - 最低有效位LSB(Least Significant Byte),指的是一个二进制数字中的第0位(即最低位)。 + - 最低有效位LSB(Least Significant Byte),指的是一个二进制数字中的第0位(即最低位)。 ### 运作机制 -在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块接口适配模式采用统一服务模式(如图1所示)。 +在HDF框架中,同类型设备对象较多时(可能同时存在十几个同类型配置器),若采用独立服务模式,则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。DAC模块接口适配模式采用统一服务模式(如图1所示)。 DAC模块各分层的作用为:接口层提供打开设备、写入数据和关闭设备接口的能力。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其他具体的功能。 @@ -100,9 +100,9 @@ DAC模块适配包含以下四个步骤: .moduleVersion = 1, .Init = VirtualDacInit, .Release = VirtualDacRelease, - .moduleName = "virtual_dac_driver", //【必要且与 HCS 里面的名字匹配】 + .moduleName = "virtual_dac_driver", //【必要且与HCS里面的名字匹配】 }; - HDF_INIT(g_dacDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_dacDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` 2. 配置属性文件: @@ -124,7 +124,7 @@ DAC模块适配包含以下四个步骤: 从第二个节点开始配置具体DAC控制器信息,此节点并不表示某一路DAC控制器,而是代表一个资源性质设备,用于描述一类DAC控制器的信息。本例只有一个DAC设备,如有多个设备,则需要在device_info文件增加deviceNode信息,以及在dac_config文件中增加对应的器件属性。 - device_info.hcs配置参考。 + device_info.hcs配置参考: ```hcs root { @@ -143,15 +143,16 @@ DAC模块适配包含以下四个步骤: policy = 0; priority = 56; permission = 0644; - moduleName = "virtual_dac_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 - serviceName = "VIRTUAL_DAC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "virtual_dac"; //【必要】用于配置控制器私有数据,要与dac_config.hcs中对应控制器保持一致 + moduleName = "virtual_dac_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "VIRTUAL_DAC_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "virtual_dac"; //【必要】用于配置控制器私有数据,要与dac_config.hcs中对应控制器保持一致。 } } ``` - - 添加dac_test_config.hcs器件属性文件 - 在vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/xxx_test_config.hcs目录下新增文件用于驱动配置参数,(例如:vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/dac_test_config.hcs)其中配置参数如下: + - 添加dac_test_config.hcs器件属性文件。 + + 在vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/xxx_test_config.hcs目录下新增文件用于驱动配置参数,(例如:vendor/vendor_hisilicon/hispark_taurus/hdf_config/hdf_test/dac_test_config.hcs)其中配置参数如下: ```hcs root { @@ -159,13 +160,13 @@ DAC模块适配包含以下四个步骤: dac_config { match_attr = "virtual_dac"; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致 template dac_device { - deviceNum = 0; // 设备号 - validChannel = 0x1; // 有效通道1 - rate = 20000; // 速率 + deviceNum = 0; // 设备号 + validChannel = 0x1; // 有效通道1 + rate = 20000; // 速率 } device_0 :: dac_device { - deviceNum = 0; // 设备号 - validChannel = 0x2; // 有效通道2 + deviceNum = 0; // 设备号 + validChannel = 0x2; // 有效通道2 } } } @@ -252,12 +253,12 @@ DAC模块适配包含以下四个步骤: uint32_t rate; //【必要】采样率 }; - // DacDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // DacDevice是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct DacDevice { const struct DacMethod *ops; - OsalSpinlock spin; // 自旋锁 - uint32_t devNum; // 设备号 - uint32_t chanNum; // 设备通道号 + OsalSpinlock spin; // 自旋锁 + uint32_t devNum; // 设备号 + uint32_t chanNum; // 设备通道号 const struct DacLockMethod *lockOps; void *priv; }; @@ -270,7 +271,7 @@ DAC模块适配包含以下四个步骤: ```c++ static const struct DacMethod g_method = { .write = VirtualDacWrite, // DAC设备写入值 - .stop = VirtualDacStop, // 停止DAC设备 + .stop = VirtualDacStop, // 停止DAC设备 .start = VirtualDacStart, // 开始启动DAC设备 }; ``` @@ -282,7 +283,7 @@ DAC模块适配包含以下四个步骤: 入参: - HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -383,7 +384,7 @@ DAC模块适配包含以下四个步骤: 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -391,7 +392,10 @@ DAC模块适配包含以下四个步骤: 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + ![](../public_sys-resources/icon-note.gif) **说明:**
+ 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 ```c++ static void VirtualDacRemoveByNode(const struct DeviceResourceNode *node) diff --git a/zh-cn/device-dev/driver/driver-platform-gpio-develop.md b/zh-cn/device-dev/driver/driver-platform-gpio-develop.md index 42f08a6c3928ff6c0135c4ce7ee6baf75f4d79cf..a9336743edacb5668f27205239f7b8f328bd3878 100755 --- a/zh-cn/device-dev/driver/driver-platform-gpio-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-gpio-develop.md @@ -47,23 +47,26 @@ struct GpioMethod { ## 开发步骤 -GPIO模块适配的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。GPIO控制器分组管理所有管脚,相关参数会在属性文件中有所体现;驱动入口和接口函数的实例化环节是厂商驱动接入HDF的核心环节。 +GPIO模块适配的三个必选环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 -1. 实例化驱动入口: +GPIO控制器分组管理所有管脚,相关参数会在属性文件中有所体现;驱动入口和接口函数的实例化环节是厂商驱动接入HDF的核心环节。 + +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. 配置属性文件: +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加gpio_config.hcs器件属性文件。 -3. 实例化GPIO控制器对象: +3. 实例化GPIO控制器对象 - 初始化GpioCntlr成员。 - 实例化GpioCntlr成员GpioMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化GpioCntlr成员GpioMethod,详见[接口说明](#接口说明)。 -4. 驱动调试: +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如GPIO控制状态,中断响应情况等。 @@ -71,7 +74,10 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, 下方将以gpio_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 GPIO 驱动入口参考: @@ -79,7 +85,7 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, ``` struct HdfDriverEntry g_gpioDriverEntry = { .moduleVersion = 1, - .Bind = Pl061GpioBind, // GPIO不需要实现Bind,本例是一个空实现,厂商可根据自身需要添加相关操作 + .Bind = Pl061GpioBind, // GPIO不需要实现Bind,本例是一个空实现,厂商可根据自身需要添加相关操作。 .Init = Pl061GpioInit, // 见Init参考 .Release = Pl061GpioRelease, // 见Release参考 .moduleName = "hisi_pl061_driver",//【必要且需要与HCS文件中里面的moduleName匹配】 @@ -88,7 +94,10 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, HDF_INIT(g_gpioDriverEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 gpio_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层GpioCntlr 成员的默认值或限制范围有密切关系。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在gpio_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层GpioCntlr成员的默认值或限制范围有密切关系。 + 本例只有一个GPIO控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在gpio_config文件中增加对应的器件属性。 - device_info.hcs配置参考 @@ -101,12 +110,12 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, priority = 50; device_gpio :: device { device0 :: deviceNode { - policy = 0; // 等于0,不需要发布服务 - priority = 10; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "hisi_pl061_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - deviceMatchAttr = "hisilicon_hi35xx_pl061"; //【必要】用于配置控制器私有数据,要与 gpio_config.hcs 中 - // 对应控制器保持一致,其他控制器信息也在文件中 + policy = 0; // 等于0,不需要发布服务。 + priority = 10; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "hisi_pl061_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + deviceMatchAttr = "hisilicon_hi35xx_pl061"; //【必要】用于配置控制器私有数据,要与gpio_config.hcs中 + // 对应控制器保持一致,其他控制器信息也在文件中。 } } } @@ -120,38 +129,39 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, platform { gpio_config { controller_0x120d0000 { - match_attr = "hisilicon_hi35xx_pl061"; //【必要】必须和device_info.hcs中的deviceMatchAttr值一致 - groupNum = 12; //【必要】GPIO组索引,需要根据设备情况填写 - bitNum = 8; //【必要】每组GPIO管脚数 - regBase = 0x120d0000;//【必要】物理基地址 - regStep = 0x1000; //【必要】寄存器偏移步进 - irqStart = 48; //【必要】开启中断 - irqShare = 0; //【必要】共享中断 + match_attr = "hisilicon_hi35xx_pl061"; //【必要】必须和device_info.hcs中的deviceMatchAttr值一致。 + groupNum = 12; //【必要】GPIO组索引,需要根据设备情况填写。 + bitNum = 8; //【必要】每组GPIO管脚数 。 + regBase = 0x120d0000; //【必要】物理基地址。 + regStep = 0x1000; //【必要】寄存器偏移步进。 + irqStart = 48; //【必要】开启中断。 + irqShare = 0; //【必要】共享中断。 } } } } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层GpioCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化GpioCntlr成员GpioMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层GpioCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化GpioCntlr成员GpioMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + - 自定义结构体参考。 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且gpio_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层GpioCntlr对象,例如索引、管脚数等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且gpio_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层GpioCntlr对象,例如索引、管脚数等。 ``` struct Pl061GpioCntlr { - struct GpioCntlr cntlr;//【必要】是核心层控制对象,其成员定义见下面 - volatile unsigned char *regBase; //【必要】寄存器基地址 - uint32_t phyBase; //【必要】物理基址 - uint32_t regStep; //【必要】寄存器偏移步进 - uint32_t irqStart; //【必要】中断开启 - uint16_t groupNum; //【必要】用于描述厂商的GPIO端口号的参数 - uint16_t bitNum; //【必要】用于描述厂商的GPIO端口号的参数 - uint8_t irqShare; //【必要】共享中断 - struct Pl061GpioGroup *groups; //【可选】根据厂商需要设置 + struct GpioCntlr cntlr; //【必要】是核心层控制对象,其成员定义见下面。 + volatile unsigned char *regBase; //【必要】寄存器基地址。 + uint32_t phyBase; //【必要】物理基址。 + uint32_t regStep; //【必要】寄存器偏移步进。 + uint32_t irqStart; //【必要】中断开启。 + uint16_t groupNum; //【必要】用于描述厂商的GPIO端口号的参数。 + uint16_t bitNum; //【必要】用于描述厂商的GPIO端口号的参数。 + uint8_t irqShare; //【必要】共享中断。 + struct Pl061GpioGroup *groups; //【可选】根据厂商需要设置。 }; - struct Pl061GpioGroup { // 包括寄存器地址,中断号,中断函数和和锁 + struct Pl061GpioGroup { // 包括寄存器地址,中断号,中断函数和锁。 volatile unsigned char *regBase; unsigned int index; unsigned int irq; @@ -159,7 +169,7 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, OsalSpinlock lock; }; - // GpioCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // GpioCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct GpioCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -180,15 +190,15 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, static struct GpioMethod g_method = { .request = NULL, .release = NULL, - .write = Pl061GpioWrite, // 写管脚 - .read = Pl061GpioRead, // 读管脚 - .setDir = Pl061GpioSetDir, // 设置管脚方向 - .getDir = Pl061GpioGetDir, // 获取管脚方向 + .write = Pl061GpioWrite, // 写管脚。 + .read = Pl061GpioRead, // 读管脚。 + .setDir = Pl061GpioSetDir, // 设置管脚方向。 + .getDir = Pl061GpioGetDir, // 获取管脚方向。 .toIrq = NULL, - .setIrq = Pl061GpioSetIrq, // 设置管脚中断,如不具备此能力可忽略 - .unsetIrq = Pl061GpioUnsetIrq, // 取消管脚中断设置,如不具备此能力可忽略 - .enableIrq = Pl061GpioEnableIrq, // 使能管脚中断,如不具备此能力可忽略 - .disableIrq = Pl061GpioDisableIrq,// 禁止管脚中断,如不具备此能力可忽略 + .setIrq = Pl061GpioSetIrq, // 设置管脚中断,如不具备此能力可忽略。 + .unsetIrq = Pl061GpioUnsetIrq, // 取消管脚中断设置,如不具备此能力可忽略。 + .enableIrq = Pl061GpioEnableIrq, // 使能管脚中断,如不具备此能力可忽略。 + .disableIrq = Pl061GpioDisableIrq,// 禁止管脚中断,如不具备此能力可忽略。 }; ``` @@ -200,7 +210,7 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 **表2** Init函数说明 @@ -215,7 +225,7 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - 初始化自定义结构体对象,初始化GpioCntlr成员,调用核心层GpioCntlrAdd函数,【可选】接入VFS。 + 初始化自定义结构体对象,初始化GpioCntlr成员,调用核心层GpioCntlrAdd函数,接入VFS(可选)。 ``` @@ -236,12 +246,12 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, ... pl061->cntlr.count = pl061->groupNum * pl061->bitNum;//【必要】管脚数量计算 pl061->cntlr.priv = (void *)device->property; //【必要】存储设备属性 - pl061->cntlr.ops = &g_method; // 【必要】GpioMethod的实例化对象的挂载 - pl061->cntlr.device = device; // 【必要】使HdfDeviceObject与GpioCntlr可以相互转化的前提 - ret = GpioCntlrAdd(&pl061->cntlr); // 【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层 + pl061->cntlr.ops = &g_method; //【必要】GpioMethod的实例化对象的挂载 + pl061->cntlr.device = device; //【必要】使HdfDeviceObject与GpioCntlr可以相互转化的前提 + ret = GpioCntlrAdd(&pl061->cntlr); //【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 ... Pl061GpioDebugCntlr(pl061); - #ifdef PL061_GPIO_USER_SUPPORT //【可选】若支持用户级的虚拟文件系统,则接入 + #ifdef PL061_GPIO_USER_SUPPORT //【可选】若支持用户级的虚拟文件系统,则接入。 if (GpioAddVfs(pl061->bitNum) != HDF_SUCCESS) { HDF_LOGE("%s: add vfs fail!", __func__); } @@ -261,7 +271,10 @@ GPIO模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release 接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 ``` diff --git a/zh-cn/device-dev/driver/driver-platform-hdmi-develop.md b/zh-cn/device-dev/driver/driver-platform-hdmi-develop.md index 5f3d7c47d7287f8ff33e8b5abc550f81141e6f75..2568e2e3cd54ff1aff5e8874141b75b258057d12 100755 --- a/zh-cn/device-dev/driver/driver-platform-hdmi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-hdmi-develop.md @@ -5,7 +5,7 @@ ### 功能简介 -HDMI(High Definition Multimedia Interface),即高清多媒体接口,是Hitachi、Panasonic、Philips、Silicon Image、Sony、Thomson、Toshiba共同发布的一款音视频传输协议,主要用于DVD、机顶盒等音视频source到TV、显示器等Sink设备的传输。HDMI传输过程遵循TMDS(Transition Minimized Differential Signaling)协议。 +HDMI(High Definition Multimedia Interface),即高清多媒体接口,是Hitachi、Panasonic、Philips、Silicon Image、Sony、Thomson、Toshiba共同发布的一款音视频传输协议,主要用于DVD、机顶盒等音视频Source设备到TV、显示器等Sink设备的传输。HDMI传输过程遵循TMDS(Transition Minimized Differential Signaling)协议。 ### 基本概念 @@ -15,13 +15,14 @@ HDMI(High Definition Multimedia Interface),即高清多媒体接口,是H - CEC(Consumer Electronics Control):消费电子控制,该功能应该能够在连接HDMI的发送设备与接收设备之间实现交互操作。 -- FRL(Fixed Rate Link):TMDS 的架构进行讯号传输时,最高带宽可达18Gbps,而 FRL 模式的带宽则提升到48Gbps。 +- FRL(Fixed Rate Link):TMDS的架构进行讯号传输时,最高带宽可达18Gbps,而FRL模式的带宽则提升到48Gbps。 + - HDCP(High-bandwidth Digital Content Protection):即高带宽数字内容保护技术,当用户对高清晰信号进行非法复制时,该技术会进行干扰,降低复制出来的影像的质量,从而对内容进行保护。 ### 运作机制 -在HDF框架中,HDMI的接口适配模式采用独立服务模式(如图1),在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用率。 +在HDF框架中,HDMI的接口适配模式采用独立服务模式(如图1)。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用率。 **图 1** HDMI独立服务模式 @@ -35,7 +36,7 @@ HDMI模块当前仅支持轻量和小型系统内核(LiteOS) 。 ### 场景介绍 -HDMI具有体积小,传输速率高,传输带宽宽,兼容性好,能同时传输无压缩音视频信号等优点。与传统的全模拟接口相比,HDMI不但增加了设备间接线的便捷性,还提供了一些HDMI特有的智能化功能,可用于小体积设备进行高质量音视频传输的场景。 +HDMI具有体积小、传输速率高、传输带宽宽、兼容性好、能同时传输无压缩音视频信号等优点。与传统的全模拟接口相比,HDMI不但增加了设备间接线的便捷性,还提供了一些HDMI特有的智能化功能,可用于小体积设备进行高质量音视频传输的场景。 ### 接口说明 @@ -86,40 +87,40 @@ struct HdmiCntlrOps { | hardWareInit | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | 无 | 初始化HDMI硬件 | | hardWareStatusGet | **cntlr**:结构体指针,核心层HDMI控制器
| **status**:HDMI硬件状态 ; | 无 | 获取HDMI当前硬件状态 | | controllerReset | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | 无 | 复位HDMI控制器 | -| hotPlugStateGet | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | bool: HDMI热插拔状态 | 获取HDMI热插拔状态 | -| hotPlugInterruptStateGet | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | bool: HDMI热插拔中断状态 | 获取HDMI热插拔中断状态 | -| lowPowerSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | 无 | 使能/去使能低功耗 | +| hotPlugStateGet | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | bool:HDMI热插拔状态 | 获取HDMI热插拔状态 | +| hotPlugInterruptStateGet | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | bool:HDMI热插拔中断状态 | 获取HDMI热插拔中断状态 | +| lowPowerSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | 无 | 使能/去使能低功耗 | | tmdsModeSet | **cntlr**:结构体指针,核心层HDMI控制器
**mode**:TMDS模式 | 无 | 无 | 设置TMDS模式 | -| tmdsConfigSet | **cntlr**:结构体指针,核心层HDMI控制器
**mode**: TMDS参数 | 无 | HDF_STATUS相关状态 | 配置TMDS参数 | -| infoFrameEnable | **cntlr**:结构体指针,核心层HDMI控制器
**infoFrameType**: packet类型
**enable**: bool,使能/去使能 | 无 | 无 | 使能/去使能infoFrame | -| infoFrameSend | **cntlr**:结构体指针,核心层HDMI控制器
**infoFrameType**: packet类型
**data**: infoFrame数据
**len**:数据长度 | 无 | HDF_STATUS相关状态 | 发送infoFrame | -| cecMsgSend | **cntlr**:结构体指针,核心层HDMI控制器
**msg**: CEC消息 | 无 | HDF_STATUS相关状态 | 发送CEC消息 | -| audioPathEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能| 无 | 无 | 使能/去使能audio通路 | -| audioPathSet | **cntlr**:结构体指针,核心层HDMI控制器
**config**: 配置信息 | 无 | 无 | 设置audio通路配置信息 | -| phyOutputEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | 无 | 使能/去使能物理层输出状态 | -| phyOutputSet | **cntlr**:结构体指针,核心层HDMI控制器
**cfg**: 配置信息 | 无 | 无 | 设置物理层配置信息 | -| blackDataSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | 无 | 设置黑屏 | -| videoMuteEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | 无 | 使能/去使能video静音 | +| tmdsConfigSet | **cntlr**:结构体指针,核心层HDMI控制器
**mode**:TMDS参数 | 无 | HDF_STATUS相关状态 | 配置TMDS参数 | +| infoFrameEnable | **cntlr**:结构体指针,核心层HDMI控制器
**infoFrameType**:packet类型
**enable**:bool,使能/去使能 | 无 | 无 | 使能/去使能infoFrame | +| infoFrameSend | **cntlr**:结构体指针,核心层HDMI控制器
**infoFrameType**:packet类型
**data**:infoFrame数据
**len**:数据长度 | 无 | HDF_STATUS相关状态 | 发送infoFrame | +| cecMsgSend | **cntlr**:结构体指针,核心层HDMI控制器
**msg**:CEC消息 | 无 | HDF_STATUS相关状态 | 发送CEC消息 | +| audioPathEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能| 无 | 无 | 使能/去使能audio通路 | +| audioPathSet | **cntlr**:结构体指针,核心层HDMI控制器
**config**:配置信息 | 无 | 无 | 设置audio通路配置信息 | +| phyOutputEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | 无 | 使能/去使能物理层输出状态 | +| phyOutputSet | **cntlr**:结构体指针,核心层HDMI控制器
**cfg**:配置信息 | 无 | 无 | 设置物理层配置信息 | +| blackDataSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | 无 | 设置黑屏 | +| videoMuteEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | 无 | 使能/去使能video静音 | | videoPathSet | **cntlr**:结构体指针,核心层HDMI控制器
**attr**:配置信息| 无 | 无 | 设置video通路配置信息 | -|audioMuteEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | 无 | 使能/去使能audio静音 | -| avmuteSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能| 无 | 无 | 使能/去使能声音图像消隐 | +|audioMuteEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | 无 | 使能/去使能audio静音 | +| avmuteSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能| 无 | 无 | 使能/去使能声音图像消隐 | | ddcTransfer | **cntlr**:结构体指针,核心层HDMI控制器
**ddcCfg**:DDC配置参数 |**ddcCfg**:DDC配置参数 |HDF_STATUS相关状态 | 读写DDC数据 | | scdcSourceScrambleGet | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | bool,加扰状态 | 获取source端的加扰状态 | -| scdcSourceScrambleSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | HDF_STATUS相关状态 | 使能/去使能source端的加扰 | -| frlEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**: bool,使能/去使能 | 无 | HDF_STATUS相关状态 | 使能/去使能FRL | +| scdcSourceScrambleSet | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | HDF_STATUS相关状态 | 使能/去使能source端的加扰 | +| frlEnable | **cntlr**:结构体指针,核心层HDMI控制器
**enable**:bool,使能/去使能 | 无 | HDF_STATUS相关状态 | 使能/去使能FRL | | audioNctsSet | **cntlr**:结构体指针,核心层HDMI控制器
**cfg**:N/CTS配置参数 | 无 | HDF_STATUS相关状态 | 设置audio的N/CTS信息 | | frlTrainingConfigSet | **cntlr**:结构体指针,核心层HDMI控制器
**cfg**:FRL Training配置参数 | 无 | 无| 设置FRL Training配置信息 | | frlTrainingStart | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | 无 | 开始FRL Training流程 | | frlGetTriningRslt | **cntlr**:结构体指针,核心层HDMI控制器 | **rslt**:FRL Training结果 | 无 | 获取FRL Training结果 | | hdcpRegInit | **cntlr**:结构体指针,核心层HDMI控制器 | 无 | 无 | 初始化HDCP流程相关的寄存器 | |hdcpGenerateAksvAndAn |**cntlr**:结构体指针,核心层HDMI控制器 | 无 | HDF_STATUS相关状态 | HDCP流程中生成aksv和an | -| hdcpOptReg | **cntlr**:结构体指针,核心层HDMI控制器
**type**: 操作类型
**data**: 寄存器数据
**len**: 数据长度 | **data**: 寄存器数据 | HDF_STATUS相关状态 | HDCP流程中读写相关寄存器 | -| hdrTimerSet | **cntlr**:结构体指针,核心层HDMI控制器
**config**: timer配置信息 | 无 | 无 | 设置HDR相关的timer配置信息 | +| hdcpOptReg | **cntlr**:结构体指针,核心层HDMI控制器
**type**:操作类型
**data**:寄存器数据
**len**:数据长度 | **data**:寄存器数据 | HDF_STATUS相关状态 | HDCP流程中读写相关寄存器 | +| hdrTimerSet | **cntlr**:结构体指针,核心层HDMI控制器
**config**:timer配置信息 | 无 | 无 | 设置HDR相关的timer配置信息 | ### 开发步骤 -HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以及实例化HDMI控制器对象。 +HDMI模块适配的三个环节是实例化驱动入口、配置属性文件以及实例化HDMI控制器对象。 - 实例化驱动入口: - 实例化HdfDriverEntry结构体成员。 @@ -135,7 +136,7 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 1. 实例化驱动入口 - 驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 @@ -165,13 +166,13 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 platform :: host { device_hdmi :: device { device0 :: deviceNode { - policy = 2; // 等于2,需要发布服务 - priority = 20; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - serviceName = "HDF_PLATFORM_HDMI_0"; //【必要】驱动对外发布服务的名称,必须唯一 - moduleName = "hdmi_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - deviceMatchAttr = "adapter_hdmi_driver"; //【必要】用于配置控制器私有数据,要与hdmi_config.hcs中对应控制器保持一致 - } // 具体的控制器信息在 hdmi_config.hcs 中 + policy = 2; // 等于2,需要发布服务。 + priority = 20; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + serviceName = "HDF_PLATFORM_HDMI_0"; //【必要】驱动对外发布服务的名称,必须唯一。 + moduleName = "hdmi_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + deviceMatchAttr = "adapter_hdmi_driver"; //【必要】用于配置控制器私有数据,要与hdmi_config.hcs中对应控制器保持一致。 + } // 具体的控制器信息在hdmi_config.hcs中。 } } } @@ -183,8 +184,8 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 root { platform { hdmi_config { - template hdmi_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 - match_attr = ""; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + template hdmi_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 + match_attr = ""; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致。 index = 0; //【必要】hdmi控制器编号 regBasePhy = 0x10100000; //【必要】寄存器物理基地址 regSize = 0xd1; //【必要】寄存器位宽 @@ -237,14 +238,14 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 ```c struct HdmiAdapterHost { - struct HdmiCntlr *cntlr; //【必要】是核心层控制对象,具体描述如下 + struct HdmiCntlr *cntlr; //【必要】是核心层控制对象,具体描述如下。 volatile unsigned char *regBase;//【必要】寄存器基地址 uint32_t regBasePhy; //【必要】寄存器物理基地址 uint32_t regSize; //【必要】寄存器位宽 uint32_t irqNum; //【必要】中断号 }; - /* HdmiCntlr是核心层控制器结构体,其中的成员在Init函数中被赋值 */ + /* HdmiCntlr是核心层控制器结构体,其中的成员在Init函数中被赋值。 */ struct HdmiCntlr { struct IDeviceIoService service; struct HdfDeviceObject *hdfDevObj; @@ -314,9 +315,11 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 - Bind函数参考 **入参:** - HdfDeviceObject是整个驱动对外呈现的接口参数,具备hcs配置文件的信息 + + HdfDeviceObject是整个驱动对外呈现的接口参数,具备HCS配置文件的信息。 **返回值:** + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义) |状态(值)|状态描述| @@ -329,6 +332,7 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 |HDF_FAILURE |传输失败| **函数说明:** + 初始化自定义结构体对象HdmiAdapterHost,初始化HdmiCntlr成员,调用核心层HdmiCntlrAdd函数。 HdmiCntlr,HdmiAdapterHost,HdfDeviceObject之间互相赋值,方便其他函数可以相互转化。 @@ -349,17 +353,17 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 HDF_LOGE("%s: malloc host failed!", __func__); return HDF_ERR_MALLOC_FAIL; } - cntlr->priv = (void *)host; //【必要】将host存放至cntlr的私有数据 - cntlr->ops = &g_hdmiHostOps; //【必要】HdmiCntlrOps的实例化对象的挂载 - cntlr->hdfDevObj = obj; //【必要】使HdfDeviceObject与HdmiCntlr可以相互转化的前提 - obj->service = &cntlr->service; //【必要】使HdfDeviceObject与HdmiCntlr可以相互转化的前提 - ret = HdmiAdapterCntlrParse(cntlr, obj); //【必要】初始化cntlr,失败则 goto __ERR; + cntlr->priv = (void *)host; //【必要】将host存放至cntlr的私有数据 + cntlr->ops = &g_hdmiHostOps; //【必要】HdmiCntlrOps的实例化对象的挂载 + cntlr->hdfDevObj = obj; //【必要】使HdfDeviceObject与HdmiCntlr可以相互转化的前提 + obj->service = &cntlr->service; //【必要】使HdfDeviceObject与HdmiCntlr可以相互转化的前提 + ret = HdmiAdapterCntlrParse(cntlr, obj); //【必要】初始化cntlr,失败则goto __ERR。 ... - ret = HdmiAdapterHostParse(host, obj); //【必要】初始化host对象的相关属性,失败则 goto __ERR; + ret = HdmiAdapterHostParse(host, obj); //【必要】初始化host对象的相关属性,失败则goto __ERR。 ... - ret = HdmiAdapterHostInit(host, cntlr); // 厂商自定义的初始化,失败则 goto __ERR; + ret = HdmiAdapterHostInit(host, cntlr); // 厂商自定义的初始化,失败则goto __ERR。 ... - ret = HdmiCntlrAdd(cntlr); // 调用核心层函数 失败则 goto __ERR; + ret = HdmiCntlrAdd(cntlr); // 调用核心层函数,失败则goto __ERR。 ... HDF_LOGD("HdmiAdapterBind: success."); return HDF_SUCCESS; @@ -373,10 +377,12 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 - Init函数参考 **入参:** - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** - HDF_STATUS相关状态 + + HDF_STATUS相关状态。 **函数说明**: @@ -389,27 +395,32 @@ HDMI模块适配的三个环节是配置属性文件,实例化驱动入口以 } ``` - - Release 函数参考 + - Release函数参考 **入参:** - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** + 无 **函数说明:** + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + > ![](../public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + ```c static void HdmiAdapterRelease(struct HdfDeviceObject *obj) { struct HdmiCntlr *cntlr = NULL; ... - cntlr = (struct HdmiCntlr *)obj->service;// 这里有HdfDeviceObject到HdmiCntlr的强制转化,通过service成员,赋值见Bind函数 + cntlr = (struct HdmiCntlr *)obj->service; // 这里有HdfDeviceObject到HdmiCntlr的强制转化,通过service成员,赋值见Bind函数。 ... - HimciDeleteHost((struct HimciAdapterHost *)cntlr->priv);// 厂商自定义的内存释放函数,这里有HdmiCntlr到HimciAdapterHost的强制转化 + HimciDeleteHost((struct HimciAdapterHost *)cntlr->priv);// 厂商自定义的内存释放函数,这里有HdmiCntlr到HimciAdapterHost的强制转化。 } ``` - > ![](../public_sys-resources/icon-note.gif) **说明:**
- > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + diff --git a/zh-cn/device-dev/driver/driver-platform-i2c-develop.md b/zh-cn/device-dev/driver/driver-platform-i2c-develop.md index 971fd3ec118e7f71e71c922f4869daa8af5dff3c..fd0a6269e01b6d32f273a2628c6c793d0d6219b4 100755 --- a/zh-cn/device-dev/driver/driver-platform-i2c-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-i2c-develop.md @@ -3,7 +3,7 @@ ## 概述 -I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线,在HDF框架中,I2C模块接口适配模式采用统一服务模式,这需要一个设备服务来作为I2C模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如I2C可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 +I2C(Inter Integrated Circuit)总线是由Philips公司开发的一种简单、双向二线制同步串行总线。在HDF框架中,I2C模块接口适配模式采用统一服务模式,这需要一个设备服务来作为I2C模块的管理器,统一处理外部访问,这会在配置文件中有所体现。统一服务模式适合于同类型设备对象较多的情况,如I2C可能同时具备十几个控制器,采用独立服务模式需要配置更多的设备节点,且服务会占据内存资源。 **图1** I2C统一服务模式结构图 @@ -34,23 +34,27 @@ struct I2cLockMethod {// 锁机制操作结构体 ## 开发步骤 -I2C模块适配的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +I2C模块适配的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 + +1. 实例化驱动入口 -1. 实例化驱动入口: - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. 配置属性文件: +2. 配置属性文件 + - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加i2c_config.hcs器件属性文件。 -3. 实例化I2C控制器对象: +3. 实例化I2C控制器对象 + - 初始化I2cCntlr成员。 - 实例化I2cCntlr成员I2cMethod和I2cLockMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化I2cCntlr成员I2cMethod和I2cLockMethod,详见[接口说明](#接口说明)。 -4. 驱动调试: +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,消息传输的成功与否等。 @@ -58,14 +62,17 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, 下方将以i2c_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 I2C驱动入口参考: - I2C模块这种类型的控制器会出现很多个设备挂接的情况,因而在HDF框架中首先会为这类型的设备创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个设备时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定设备。 + I2C控制器会出现很多个设备挂接的情况,因而在HDF框架中首先会为此类型的设备创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个设备时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定设备。 - I2C管理器服务的驱动由核心层实现,厂商不需要关注这部分内容的实现,这个但在实现Init函数的时候需要调用核心层的I2cCntlrAdd函数,它会实现相应功能。 + I2C管理器服务的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I2cCntlrAdd函数,它会实现相应功能。 ``` @@ -73,9 +80,9 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, .moduleVersion = 1, .Init = Hi35xxI2cInit, .Release = Hi35xxI2cRelease, - .moduleName = "hi35xx_i2c_driver",// 【必要且与config.hcs文件里面匹配】 + .moduleName = "hi35xx_i2c_driver", // 【必要且与config.hcs文件里面匹配】 }; - HDF_INIT(g_i2cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_i2cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 // 核心层i2c_core.c管理器服务的驱动入口 struct HdfDriverEntry g_i2cManagerEntry = { @@ -83,12 +90,15 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, .Bind = I2cManagerBind, .Init = I2cManagerInit, .Release = I2cManagerRelease, - .moduleName = "HDF_PLATFORM_I2C_MANAGER",// 这与device_info文件中device0对应 + .moduleName = "HDF_PLATFORM_I2C_MANAGER", // 这与device_info文件中device0对应 }; HDF_INIT(g_i2cManagerEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i2c_config.hcs中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I2cCntlr相关成员的默认值或限制范围有密切关系。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i2c_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I2cCntlr相关成员的默认值或限制范围有密切关系。 + 统一服务模式的特点是device_info文件中第一个设备节点必须为I2C管理器,其各项参数必须如表2设置: **表2** 统一服务模式的特点 @@ -101,6 +111,7 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, | deviceMatchAttr | 没有使用,可忽略 | 从第二个节点开始配置具体I2C控制器信息,此节点并不表示某一路I2C控制器,而是代表一个资源性质设备,用于描述一类I2C控制器的信息。多个控制器之间相互区分的参数是busID和reg_pbase,这在i2c_config文件中有所体现。 + - device_info.hcs配置参考 @@ -118,13 +129,13 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, deviceMatchAttr = "hdf_platform_i2c_manager"; } device1 :: deviceNode { - policy = 0; // 等于0,不需要发布服务 - priority = 55; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "hi35xx_i2c_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - serviceName = "HI35XX_I2C_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hisilicon_hi35xx_i2c"; //【必要】用于配置控制器私有数据,要与i2c_config.hcs中对应控制器保持一致 - // 具体的控制器信息在 i2c_config.hcs中 + policy = 0; // 等于0,不需要发布服务。 + priority = 55; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "hi35xx_i2c_driver"; //【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HI35XX_I2C_DRIVER"; //【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_i2c"; //【必要】用于配置控制器私有数据,要与i2c_config.hcs中对应控制器保持一致, + // 具体的控制器信息在 i2c_config.hcs中。 } } } @@ -139,13 +150,13 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, platform { i2c_config { match_attr = "hisilicon_hi35xx_i2c"; //【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - template i2c_controller { //模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 - bus = 0; // 【必要】i2c 识别号 - reg_pbase = 0x120b0000; // 【必要】物理基地址 - reg_size = 0xd1; // 【必要】寄存器位宽 - irq = 0; // 【可选】根据厂商需要来使用 - freq = 400000; // 【可选】根据厂商需要来使用 - clk = 50000000; // 【可选】根据厂商需要来使用 + template i2c_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 + bus = 0; //【必要】i2c识别号 + reg_pbase = 0x120b0000; //【必要】物理基地址 + reg_size = 0xd1; //【必要】寄存器位宽 + irq = 0; //【可选】根据厂商需要来使用 + freq = 400000; //【可选】根据厂商需要来使用 + clk = 50000000; //【可选】根据厂商需要来使用 } controller_0x120b0000 :: i2c_controller { bus = 0; @@ -160,7 +171,8 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层I2cCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化I2cCntlr成员I2cMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层I2cCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化I2cCntlr成员I2cMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + - 自定义结构体参考 从驱动的角度看,自定义结构体是参数和数据的载体,而且i2c_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层I2cCntlr对象,例如设备号、总线号等。 @@ -169,8 +181,8 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, ``` // 厂商自定义功能结构体 struct Hi35xxI2cCntlr { - struct I2cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面 - OsalSpinlock spin; // 【必要】厂商需要基于此锁变量对各个 i2c 操作函数实现对应的加锁解锁 + struct I2cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面。 + OsalSpinlock spin; // 【必要】厂商需要基于此锁变量对各个i2c操作函数实现对应的加锁解锁。 volatile unsigned char *regBase; // 【必要】寄存器基地址 uint16_t regSize; // 【必要】寄存器位宽 int16_t bus; // 【必要】i2c_config.hcs文件中可读取具体值 @@ -180,7 +192,7 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, uint32_t regBasePhy; // 【必要】寄存器物理基地址 }; - // I2cCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // I2cCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct I2cCntlr { struct OsalMutex lock; void *owner; @@ -208,7 +220,7 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -227,14 +239,14 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - 初始化自定义结构体对象,初始化I2cCntlr成员,调用核心层I2cCntlrAdd函数,【可选】接入VFS。 + 初始化自定义结构体对象,初始化I2cCntlr成员,调用核心层I2cCntlrAdd函数,接入VFS(可选)。 ``` static int32_t Hi35xxI2cInit(struct HdfDeviceObject *device) { ... - // 遍历、解析 i2c_config.hcs中的所有配置节点,并分别进行初始化,需要调用Hi35xxI2cParseAndInit函数 + // 遍历、解析i2c_config.hcs中的所有配置节点,并分别进行初始化,需要调用Hi35xxI2cParseAndInit函数。 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { ret = Hi35xxI2cParseAndInit(device, childNode);//函数定义见下 ... @@ -257,13 +269,13 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, hi35xx->cntlr.ops = &g_method; // 【必要】I2cMethod的实例化对象的挂载 hi35xx->cntlr.lockOps = &g_lockOps; // 【必要】I2cLockMethod的实例化对象的挂载 (void)OsalSpinInit(&hi35xx->spin); // 【必要】锁的初始化 - ret = I2cCntlrAdd(&hi35xx->cntlr); // 【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层 + ret = I2cCntlrAdd(&hi35xx->cntlr); // 【必要】调用此函数填充核心层结构体,返回成功信号后驱动才完全接入平台核心层。 ... #ifdef USER_VFS_SUPPORT - (void)I2cAddVfsById(hi35xx->cntlr.busId);// 【可选】若支持用户级的虚拟文件系统,则接入 + (void)I2cAddVfsById(hi35xx->cntlr.busId);// 【可选】若支持用户级的虚拟文件系统,则接入。 #endif return HDF_SUCCESS; - __ERR__: // 不成功的话,需要反向执行初始化相关函数 + __ERR__: // 不成功的话,需要反向执行初始化相关函数。 if (hi35xx != NULL) { if (hi35xx->regBase != NULL) { OsalIoUnmap((void *)hi35xx->regBase); @@ -279,7 +291,7 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -294,7 +306,7 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, static void Hi35xxI2cRelease(struct HdfDeviceObject *device) { ... - // 与Hi35xxI2cInit一样,需要将对每个节点分别进行释放 + // 与Hi35xxI2cInit一样,需要将对每个节点分别进行释放。 DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { Hi35xxI2cRemoveByNode(childNode);// 函数定义见下 } @@ -303,12 +315,12 @@ I2C模块适配的三个环节是配置属性文件,实例化驱动入口, static void Hi35xxI2cRemoveByNode(const struct DeviceResourceNode *node) { ... - // 【必要】可以调用 I2cCntlrGet函数通过设备的busid获取I2cCntlr对象, 以及调用I2cCntlrRemove函数来释放I2cCntlr对象的内容 + // 【必要】可以调用I2cCntlrGet函数通过设备的busid获取I2cCntlr对象,以及调用I2cCntlrRemove函数来释放I2cCntlr对象的内容。 cntlr = I2cCntlrGet(bus); if (cntlr != NULL && cntlr->priv == node) { ... I2cCntlrRemove(cntlr); - // 【必要】解除地址映射,锁和内存的释放 + // 【必要】解除地址映射,锁和内存的释放。 hi35xx = (struct Hi35xxI2cCntlr *)cntlr; OsalIoUnmap((void *)hi35xx->regBase); (void)OsalSpinDestroy(&hi35xx->spin); diff --git a/zh-cn/device-dev/driver/driver-platform-i3c-develop.md b/zh-cn/device-dev/driver/driver-platform-i3c-develop.md index 00fbe1ee7951bea1874d228126816abeb78b299b..cb91d218e6ce2baa475efed246cf8d2d1d2f1725 100755 --- a/zh-cn/device-dev/driver/driver-platform-i3c-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-i3c-develop.md @@ -10,21 +10,39 @@ I3C是两线双向串行总线,针对多个传感器从设备进行了优化 ### 基本概念 -- IBI(In-Band Interrupt):带内中断。在SCL线没有启动信号时,I3C从设备可以通过拉低SDA线使主设备发出SCL启动信号,从而发出带内中断请求。若有多个从机同时发出中断请求,I3C主机则通过从机地址进行仲裁,低地址优先相应。 -- DAA(Dynamic Address Assignment):动态地址分配。I3C支持对从设备地址进行动态分配从而避免地址冲突。在分配动态地址之前,连接到I3C总线上的每个I3C设备都应以两种方式之一来唯一标识: -1)设备可能有一个符合I2C规范的静态地址,主机可以使用此静态地址; -2)在任何情况下,设备均应具有48位的临时ID。 除非设备具有静态地址且主机使用静态地址,否则主机应使用此48位临时ID。 +- IBI(In-Band Interrupt):带内中断。 -- CCC(Common Command Code) :通用命令代码(CCC),所有I3C设备均支持CCC,可以直接将其传输到特定的I3C从设备,也可以同时传输到所有I3C从设备。 -- BCR(Bus Characteristic Register):总线特性寄存器,每个连接到I3C总线的 I3C 设备都应具有相关的只读总线特性寄存器(BCR),该寄存器描述了I3C兼容设备在动态地址分配和通用命令代码中的作用和功能。 -- DCR(Device Characteristic Register):设备特性寄存器,连接到I3C总线的每个 I3C 设备都应具有相关的只读设备特性寄存器(DCR)。该寄存器描述了用于动态地址分配和通用命令代码的I3C兼容设备类型(例如,加速度计、陀螺仪等)。 + 在SCL线没有启动信号时,I3C从设备可以通过拉低SDA线使主设备发出SCL启动信号,从而发出带内中断请求。若有多个从设备同时发出中断请求,I3C主设备则通过从设备地址进行仲裁,低地址优先相应。 + +- DAA(Dynamic Address Assignment):动态地址分配。 + + I3C支持对从设备地址进行动态分配从而避免地址冲突。在分配动态地址之前,连接到I3C总线上的每个I3C设备都应以两种方式之一来唯一标识: + + - 设备可能有一个符合I2C规范的静态地址,主机可以使用此静态地址。 + + - 在任何情况下,设备均应具有48位的临时ID。除非设备具有静态地址且主机使用静态地址,否则主机应使用此48位临时ID。 + +- CCC(Common Command Code):通用命令代码。 + + 所有I3C设备均支持CCC,可以直接将其传输到特定的I3C从设备,也可以同时传输到所有I3C从设备。 + +- BCR(Bus Characteristic Register):总线特性寄存器。 + + 每个连接到I3C总线的I3C设备都应具有相关的只读总线特性寄存器(BCR),该寄存器描述了I3C兼容设备在动态地址分配和通用命令代码中的作用和功能。 + +- DCR(Device Characteristic Register):设备特性寄存器。 + + 连接到I3C总线的每个I3C设备都应具有相关的只读设备特性寄存器(DCR),该寄存器描述了用于动态地址分配和通用命令代码的I3C兼容设备类型(例如加速度计、陀螺仪等)。 ### 运作机制 -在HDF框架中,同类型控制器对象较多时(可能同时存在十几个同类型控制器),如果采用独立服务模式则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。I3C模块接口适配模式采用统一服务模式(如[图1](#fig1)所示)。 +在HDF框架中,同类型控制器对象较多时(可能同时存在十几个同类型控制器),如果采用独立服务模式则需要配置更多的设备节点,且相关服务会占据更多的内存资源。相反,采用统一服务模式可以使用一个设备服务作为管理器,统一处理所有同类型对象的外部访问(这会在配置文件中有所体现),实现便捷管理和节约资源的目的。I3C模块接口适配模式采用统一服务模式(如图1所示)。 -I3C模块各分层的作用为:接口层提供打开控制器、传输消息、获取和设置控制器参数以及关闭控制器的接口。核心层主要提供绑定设备、初始化设备以及释放设备的能力。适配层实现其他具体的功能。 +I3C模块各分层的作用为: +- 接口层提供打开控制器、传输消息、获取和设置控制器参数以及关闭控制器的接口。 +- 核心层主要提供绑定设备、初始化设备以及释放设备的能力。 +- 适配层实现其他具体的功能。 **图 1** I3C统一服务模式 @@ -39,8 +57,8 @@ I3C模块当前仅支持轻量和小型系统内核(LiteOS) 。 ### 场景介绍 I3C可连接单个或多个I3C、I2C从器件,它主要用于: -1. 与传感器通信,如陀螺仪、气压计或支持I3C协议的图像传感器等。 -2. 通过软件或硬件协议转换,与其他通信接口(如 UART 串口等)的设备进行通信。 +- 与传感器通信,如陀螺仪、气压计或支持I3C协议的图像传感器等。 +- 通过软件或硬件协议转换,与其他通信接口(如UART串口等)的设备进行通信。 ### 接口说明 @@ -60,14 +78,13 @@ struct I3cMethod { **表1** I3cMethod结构体成员的回调函数功能说明 |函数成员|入参|出参|返回值|功能| |-|-|-|-|-| -|sendCccCmd| **cntlr**: 结构体指针,核心层I3C控制器
**ccc**:传入的通用命令代码结构体指针 | **ccc**:传出的通用命令代码结构体指针 | HDF_STATUS相关状态|发送CCC(Common command Code,即通用命令代码)| -|Transfer | **cntlr**: 结构体指针,核心层I3C控制器
**msgs**:结构体指针,用户消息
**count**:int16_t,消息数量 | **msgs**:结构体指针,用户消息 - | HDF_STATUS相关状态 | 使用I3C模式传递用户消息 | -|i2cTransfer | **cntlr**: 结构体指针,核心层I3C控制器
**msgs**:结构体指针,用户消息
**count**:int16_t,消息数量 | **msgs**:结构体指针,用户消息 | HDF_STATUS相关状态 | 使用I2C模式传递用户消息 | -|setConfig| **cntlr**: 结构体指针,核心层I3C控制器
**config**: 控制器配置参数| 无 | HDF_STATUS相关状态 | 设置I3C控制器配置参数 | -|getConfig| **cntlr**: 结构体指针,核心层I3C控制器| **config**: 控制器配置参数 | HDF_STATUS相关状态 | 获取I3C控制器配置参数 | -|requestIbi| **device**: 结构体指针,核心层I3C设备| 无 | HDF_STATUS相关状态 | 为I3C设备请求IBI(In-Bind Interrupt,即带内中断) | -|freeIbi| **device**: 结构体指针,核心层I3C设备| 无 | HDF_STATUS相关状态 | 释放IBI | +|sendCccCmd| **cntlr**:结构体指针,核心层I3C控制器
**ccc**:传入的通用命令代码结构体指针 | **ccc**:传出的通用命令代码结构体指针 | HDF_STATUS相关状态|发送CCC(Common command Code,即通用命令代码)| +|Transfer | **cntlr**:结构体指针,核心层I3C控制器
**msgs**:结构体指针,用户消息
**count**:int16_t,消息数量 | **msgs**:结构体指针,用户消息| HDF_STATUS相关状态 | 使用I3C模式传递用户消息 | +|i2cTransfer | **cntlr**:结构体指针,核心层I3C控制器
**msgs**:结构体指针,用户消息
**count**:int16_t,消息数量 | **msgs**:结构体指针,用户消息 | HDF_STATUS相关状态 | 使用I2C模式传递用户消息 | +|setConfig| **cntlr**:结构体指针,核心层I3C控制器
**config**:控制器配置参数| 无 | HDF_STATUS相关状态 | 设置I3C控制器配置参数 | +|getConfig| **cntlr**:结构体指针,核心层I3C控制器| **config**:控制器配置参数 | HDF_STATUS相关状态 | 获取I3C控制器配置参数 | +|requestIbi| **device**:结构体指针,核心层I3C设备| 无 | HDF_STATUS相关状态 | 为I3C设备请求IBI(In-Bind Interrupt,即带内中断) | +|freeIbi| **device**:结构体指针,核心层I3C设备| 无 | HDF_STATUS相关状态 | 释放IBI | ### 开发步骤 @@ -91,13 +108,15 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 1. 实例化驱动入口 - 驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 I3C驱动入口参考: - > I3C模块这种类型的控制器会出现很多个控制器挂接的情况,因而在HDF框架中首先会为这类型的控制器创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个控制器时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定控制器。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > I3C控制器会出现很多个控制器挂接的情况,因而在HDF框架中首先会为此类型的控制器创建一个管理器对象,并同时对外发布一个管理器服务来统一处理外部访问。这样,用户需要打开某个控制器时,会先获取到管理器服务,然后管理器服务根据用户指定参数查找到指定控制器。 > > I3C管理器服务的驱动由核心层实现,厂商不需要关注这部分内容的实现,但在实现Init函数的时候需要调用核心层的I3cCntlrAdd函数,它会实现相应功能。 @@ -106,9 +125,9 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 .moduleVersion = 1, .Init = VirtualI3cInit, .Release = VirtualI3cRelease, - .moduleName = "virtual_i3c_driver",// 【必要且与hcs文件中的名字匹配】 + .moduleName = "virtual_i3c_driver", // 【必要且与hcs文件中的名字匹配】 }; - HDF_INIT(g_virtualI3cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_virtualI3cDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 /* 核心层i3c_core.c管理器服务的驱动入口 */ struct HdfDriverEntry g_i3cManagerEntry = { @@ -122,7 +141,9 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 2. 配置属性文件 - 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i3c_config.hcs中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I3cCntlr相关成员的默认值或限制范围有密切关系。 + 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在i3c_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值对于厂商驱动的实现以及核心层I3cCntlr相关成员的默认值或限制范围有密切关系。 统一服务模式的特点是device_info文件中第一个设备节点必须为I3C管理器,其各项参数必须如下设置: @@ -149,13 +170,13 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 } } i3c_virtual :: deviceNode { - policy = 0; // 等于0,不需要发布服务 - priority = 56; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "virtual_i3c_driver"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - serviceName = "VIRTUAL_I3C_DRIVER"; // 【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "virtual_i3c"; // 【必要】用于配置控制器私有数据,要与i3c_config.hcs中对应控制器保持一致 - } // 具体的控制器信息在 i3c_config.hcs 中 + policy = 0; // 等于0,不需要发布服务。 + priority = 56; // 驱动启动优先级。 + permission = 0644; // 驱动创建设备节点权限。 + moduleName = "virtual_i3c_driver"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "VIRTUAL_I3C_DRIVER"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "virtual_i3c"; // 【必要】用于配置控制器私有数据,要与i3c_config.hcs中对应控制器保持一致。 + } // 具体的控制器信息在i3c_config.hcs中。 } ``` @@ -166,9 +187,9 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 platform { i3c_config { match_attr = "virtual_i3c"; // 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 - template i3c_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 + template i3c_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 busId = 0; // 【必要】i3c总线号 - busMode = 0x0; // 总线模式,0x0:纯净; 0x1:混合高速; 0x2:混合受限; 0x3: 混合低速; + busMode = 0x0; // 总线模式,0x0:纯净;0x1:混合高速:0x2:混合受限;0x3:混合低速。 regBasePhy = 0x120b0000; // 【必要】物理基地址 regSize = 0xd1; // 【必要】寄存器位宽 IrqNum = 20; // 【必要】中断号 @@ -192,17 +213,20 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 此步骤需要通过实现HdfDriverEntry成员函数(Bind,Init,Release)来完成。 + I3cCntlr成员回调函数结构体I3cMethod的实例化,I3cLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化。 + - 自定义结构体参考 - - > 从驱动的角度看,自定义结构体是参数和数据的载体,而且i3c_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层I3cCntlr对象,例如设备号、总线号等。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 从驱动的角度看,自定义结构体是参数和数据的载体,而且i3c_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,其中一些重要数值也会传递给核心层I3cCntlr对象,例如设备号、总线号等。 ```c struct VirtualI3cCntlr { - struct I3cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面 + struct I3cCntlr cntlr; // 【必要】是核心层控制对象,具体描述见下面。 volatile unsigned char *regBase;// 【必要】寄存器基地址 - uint32_t regBasePhy; // 【必要】寄存器物理基地址 - uint32_t regSize; // 【必要】寄存器位宽 - uint16_t busId; // 【必要】设备号 + uint32_t regBasePhy; // 【必要】寄存器物理基地址 + uint32_t regSize; // 【必要】寄存器位宽 + uint16_t busId; // 【必要】设备号 uint16_t busMode; uint16_t IrqNum; uint32_t i3cMaxRate; @@ -211,7 +235,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 uint32_t i2cFmPlusRate; }; - /* I3cCntlr是核心层控制器结构体,其中的成员在Init函数中被赋值 */ + /* I3cCntlr是核心层控制器结构体,其中的成员在Init函数中被赋值。 */ struct I3cCntlr { OsalSpinlock lock; void *owner; @@ -225,15 +249,17 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 }; ``` - > I3cCntlr成员回调函数结构体I3cMethod的实例化,I3cLockMethod回调函数结构体本例未实现,若要实例化,可参考I2C驱动开发,其他成员在Init函数中初始化 - - init函数参考 + + - Init函数参考 **入参:** - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备 HCS 配置文件的信息 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** - HDF_STATUS相关状态 (下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义) + + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 |状态(值)|问题描述| @@ -246,16 +272,17 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 |HDF_FAILURE |传输失败| **函数说明:** + 初始化自定义结构体对象,初始化I3cCntlr成员,调用核心层I3cCntlrAdd函数。 ```c static int32_t VirtualI3cParseAndInit(struct HdfDeviceObject *device, const struct DeviceResourceNode *node) { int32_t ret; - struct VirtualI3cCntlr *virtual = NULL; // 【必要】自定义结构体对象 + struct VirtualI3cCntlr *virtual = NULL; // 【必要】自定义结构体对象 (void)device; - virtual = (struct VirtualI3cCntlr *)OsalMemCalloc(sizeof(*virtual)); // 【必要】内存分配 + virtual = (struct VirtualI3cCntlr *)OsalMemCalloc(sizeof(*virtual)); // 【必要】内存分配 if (virtual == NULL) { HDF_LOGE("%s: Malloc virtual fail!", __func__); return HDF_ERR_MALLOC_FAIL; @@ -267,7 +294,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 goto __ERR__; } ... - virtual->regBase = OsalIoRemap(virtual->regBasePhy, virtual->regSize);// 【必要】地址映射 + virtual->regBase = OsalIoRemap(virtual->regBasePhy, virtual->regSize); // 【必要】地址映射 ret = OsalRegisterIrq(hi35xx->softIrqNum, OSAL_IRQF_TRIGGER_NONE, I3cIbiHandle, "I3C", virtual); //【必要】注册中断程序 if (ret != HDF_SUCCESS) { HDF_LOGE("%s: register irq failed!", __func__); @@ -279,7 +306,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 virtual->cntlr.busId = virtual->busId; // 【必要】初始化I3cCntlr成员 virtual->cntlr.ops = &g_method; // 【必要】I3cMethod的实例化对象的挂载 (void)OsalSpinInit(&virtual->spin); - ret = I3cCntlrAdd(&virtual->cntlr); // 【必要且重要】调用此函数将控制器添加至核心,返回成功信号后驱动才完全接入平台核心层 + ret = I3cCntlrAdd(&virtual->cntlr); // 【必要且重要】调用此函数将控制器添加至核心,返回成功信号后驱动才完全接入平台核心层。 if (ret != HDF_SUCCESS) { HDF_LOGE("%s: add i3c controller failed! ret = %d", __func__, ret); (void)OsalSpinDestroy(&virtual->spin); @@ -287,7 +314,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 } return HDF_SUCCESS; - __ERR__: // 若控制器添加失败,需要执行去初始化相关函数 + __ERR__: // 若控制器添加失败,需要执行去初始化相关函数。 if (virtual != NULL) { OsalMemFree(virtual); virtual = NULL; @@ -320,13 +347,19 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 - Release函数参考 **入参:** - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备hcs配置文件的信息 。 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** + 无。 **函数说明:** - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 ```c static void VirtualI3cRemoveByNode(const struct DeviceResourceNode *node) @@ -349,7 +382,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 return; } ... - /* 可以调用I3cCntlrGet函数通过设备的cntlrNum获取I3cCntlr对象, 以及调用I3cCntlrRemove函数来释放I3cCntlr对象的内容 */ + /* 可以调用I3cCntlrGet函数通过设备的cntlrNum获取I3cCntlr对象,以及调用I3cCntlrRemove函数来释放I3cCntlr对象的内容。 */ cntlr = I3cCntlrGet(busId); if (cntlr != NULL && cntlr->priv == node) { I3cCntlrPut(cntlr); @@ -424,7 +457,7 @@ I3C模块适配的四个环节是实例化驱动入口、配置属性文件、 return HDF_ERR_INVALID_PARAM; } virtual = (struct VirtualI3cCntlr *)data; - /* 【必要】获取产生中断的地址,使用CHECK_RESERVED_ADDR宏判断该地址是否为I3C保留地址 */ + /* 【必要】获取产生中断的地址,使用CHECK_RESERVED_ADDR宏判断该地址是否为I3C保留地址。 */ ibiAddr = VirtualI3cGetIbiAddr(); if (CHECK_RESERVED_ADDR(ibiAddr) == I3C_ADDR_RESERVED) { HDF_LOGD("%s: Calling VirtualI3cResAddrWorker...", __func__); diff --git a/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md b/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md index 517e780a6769541d768df807bf43c90114662a73..b7e27914d9d268c4684e9d82bcaff0225951eeac 100755 --- a/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mipicsi-develop.md @@ -1,6 +1,6 @@ # MIPI CSI -## 概述 +## 概述 CSI(Camera Serial Interface)是由MIPI(Mobile Industry Processor Interface)联盟下Camera工作组指定的接口标准。在HDF框架中,MIPI CSI的接口适配模式采用无服务模式,用于不需要在用户态提供API的设备类型,或者没有用户态和内核区分的OS系统,MIPI CSI的接口关联方式是DevHandle直接指向设备对象内核态地址(DevHandle是一个void类型指针)。 @@ -8,7 +8,7 @@ CSI(Camera Serial Interface)是由MIPI(Mobile Industry Processor Interface ![image1](figures/无服务模式结构图.png) -## 接口说明 +## 接口说明 MipiCsiCntlrMethod定义: @@ -44,37 +44,44 @@ struct MipiCsiCntlrMethod { | resetSensor | **cntlr**:结构体指针,MipiCsi控制器 ;
**snsClkSource**:uint8_t,传感器的时钟信号线号 | 无 | HDF_STATUS相关状态 | 复位Sensor | | unresetSensor | **cntlr**:结构体指针,MipiCsi控制器 ;
**snsClkSource**:uint8_t,传感器的时钟信号线号 | 无 | HDF_STATUS相关状态 | 撤销复位Sensor | -## 开发步骤 +## 开发步骤 -MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、以及实例化核心层接口函数。 +MIPI CSI模块适配的三个必选环节是配置属性文件、实例化驱动入口、以及实例化核心层接口函数。 -1. **实例化驱动入口:** - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 - -2. **配置属性文件:** +1. 配置属性文件: - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加mipicsi_config.hcs器件属性文件。 -3. **实例化MIPICSI控制器对象:** +2. 实例化驱动入口: + + - 实例化HdfDriverEntry结构体成员。 + - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 + +3. 实例化MIPI CSI控制器对象: + - 初始化MipiCsiCntlr成员。 - 实例化MipiCsiCntlr成员MipiCsiCntlrMethod。 >![](../public_sys-resources/icon-note.gif) **说明:**
- >实例化MipiCsiCntlr成员MipiCsiCntlrMethod,其定义和成员说明见[接口说明](#section2_MIPI_CSIDevelop)。 + >实例化MipiCsiCntlr成员MipiCsiCntlrMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** - - 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 +4. 驱动调试: + + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 -## 开发实例 +## 开发实例 下方将以mipi_rx_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 一般来说,驱动开发首先需要在 busxx_config.hcs 中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。器件属性值与核心层MipiCsiCntlr 成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 +1. 一般来说,驱动开发首先需要在busxx_config.hcs中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。 + + 器件属性值与核心层MipiCsiCntlr 成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 + + >![](../public_sys-resources/icon-note.gif) **说明:**
+ >本例中MIPI控制器自身属性在源文件文件中,如有厂商需要,则在device_info文件的deviceNode增加deviceMatchAttr信息,相应增加mipicsi_config.hcs文件。 - **本例中MIPI控制器自身属性在源文件文件中,如有厂商需要,则在device_info文件的deviceNode增加deviceMatchAttr信息,相应增加mipicsi_config.hcs文件**。 - device_info.hcs 配置参考 @@ -90,7 +97,7 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 policy = 0; priority = 160; permission = 0644; - moduleName = "HDF_MIPI_RX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; + moduleName = "HDF_MIPI_RX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 serviceName = "HDF_MIPI_RX"; // 【必要且唯一】驱动对外发布服务的名称 } } @@ -99,7 +106,9 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 } ``` -2. 完成器件属性文件的配置之后,下一步请实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 +2. 完成器件属性文件的配置之后,下一步请实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 一般在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 @@ -110,12 +119,14 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 .moduleVersion = 1, .Init = Hi35xxMipiCsiInit, // 见Init参考 .Release = Hi35xxMipiCsiRelease, // 见Release参考 - .moduleName = "HDF_MIPI_RX", // 【必要】需要与device_info.hcs 中保持一致。 + .moduleName = "HDF_MIPI_RX", // 【必要】需要与device_info.hcs 中保持一致 }; HDF_INIT(g_mipiCsiDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -3. 完成驱动入口注册之后,最后一步就是以核心层MipiCsiCntlr对象的初始化为核心,实现HdfDriverEntry成员函数(Bind,Init,Release)。MipiCsiCntlr对象的初始化包括厂商自定义结构体(用于传递参数和数据)和实例化MipiCsiCntlr成员MipiCsiCntlrMethod(让用户可以通过接口来调用驱动底层函数)。 +3. 完成驱动入口注册之后,最后一步就是以核心层MipiCsiCntlr对象的初始化为核心,实现HdfDriverEntry成员函数(Bind,Init,Release)。 + + MipiCsiCntlr对象的初始化包括厂商自定义结构体(用于传递参数和数据)和实例化MipiCsiCntlr成员MipiCsiCntlrMethod(让用户可以通过接口来调用驱动底层函数)。 - 自定义结构体参考 @@ -151,17 +162,17 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 }; } ComboDevAttr; - // MipiCsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // MipiCsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct MipiCsiCntlr { - /** 当驱动程序绑定到HDF框架时,将发送此控制器提供的服务 */ + /** 当驱动程序绑定到HDF框架时,将发送此控制器提供的服务。 */ struct IDeviceIoService service; - /** 当驱动程序绑定到HDF框架时,将传入设备端指针 */ + /** 当驱动程序绑定到HDF框架时,将传入设备端指针。 */ struct HdfDeviceObject *device; /** 设备号 */ unsigned int devNo; /** 控制器提供的所有接口 */ struct MipiCsiCntlrMethod *ops; - /** 对于控制器调试的所有接口,如果未实现驱动程序,则需要null */ + /** 对于控制器调试的所有接口,如果未实现驱动程序,则需要null。 */ struct MipiCsiCntlrDebugMethod *debugs; /** 控制器上下文参数变量 */ MipiDevCtx ctx; @@ -169,12 +180,17 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 OsalSpinlock ctxLock; /** 操作控制器时锁定方法 */ struct OsalMutex lock; - /** 匿名数据指针,用于存储csi设备结构 */ + /** 匿名数据指针,用于存储csi设备结构。 */ void *priv; }; ``` -- **【重要】** MipiCsiCntlr成员回调函数结构体MipiCsiCntlrMethod的实例化,其他成员在Init函数中初始化。 + +- MipiCsiCntlr成员回调函数结构体MipiCsiCntlrMethod的实例化 + + >![](../public_sys-resources/icon-note.gif) **说明:**
+ >其他成员在Init函数中初始化。 + ```c static struct MipiCsiCntlrMethod g_method = { @@ -196,10 +212,12 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 - **Init函数参考** **入参:** - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备hcs配置文件的信息 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义) + + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 | 状态(值) | 问题描述 | @@ -212,6 +230,7 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 | HDF_FAILURE | 执行失败 | **函数说明:** + MipiCsiCntlrMethod的实例化对象的挂载,调用MipiCsiRegisterCntlr,以及其他厂商自定义初始化操作。 @@ -235,7 +254,7 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 return ret; } - ret = MipiRxDrvInit(); // 【必要】厂商对设备的初始化,形式不限 + ret = MipiRxDrvInit(); // 【必要】厂商对设备的初始化,形式不限。 if (ret != HDF_SUCCESS) { HDF_LOGE("%s: [MipiRxDrvInit] failed.", __func__); return ret; @@ -258,14 +277,14 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 int32_t MipiCsiRegisterCntlr(struct MipiCsiCntlr *cntlr, struct HdfDeviceObject *device) { ... - // 定义的全局变量:static struct MipiCsiHandle g_mipiCsihandle[MAX_CNTLR_CNT]; + // 定义的全局变量:static struct MipiCsiHandle g_mipiCsihandle[MAX_CNTLR_CNT]; if (g_mipiCsihandle[cntlr->devNo].cntlr == NULL) { (void)OsalMutexInit(&g_mipiCsihandle[cntlr->devNo].lock); (void)OsalMutexInit(&(cntlr->lock)); - g_mipiCsihandle[cntlr->devNo].cntlr = cntlr; // 初始化MipiCsiHandle成员 + g_mipiCsihandle[cntlr->devNo].cntlr = cntlr; // 初始化MipiCsiHandle成员 g_mipiCsihandle[cntlr->devNo].priv = NULL; - cntlr->device = device; // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 + cntlr->device = device; // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 device->service = &(cntlr->service); // 使HdfDeviceObject与MipiCsiHandle可以相互转化的前提 cntlr->priv = NULL; HDF_LOGI("%s: success.", __func__); @@ -281,13 +300,20 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 - **Release函数参考** **入参:** - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备 HCS 配置文件的信息。 + + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 **返回值:** + 无 **函数说明:** - 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + + 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。 + + >![](../public_sys-resources/icon-note.gif) **说明:**
+ >所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + ```c static void Hi35xxMipiCsiRelease(struct HdfDeviceObject *device) @@ -302,7 +328,7 @@ MIPI CSI模块适配的三个环节是配置属性文件、实例化驱动入、 #ifdef MIPICSI_VFS_SUPPORT MipiCsiDevModuleExit(cntlr->devNo); #endif - MipiRxDrvExit(); // 【必要】对厂商设备所占资源的释放 + MipiRxDrvExit(); // 【必要】对厂商设备所占资源的释放 MipiCsiUnregisterCntlr(&g_mipiCsi); // 空函数 g_mipiCsi.priv = NULL; diff --git a/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md b/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md index ae0310c0b4620edd7ca6bf665299834f1888454f..dd819669cac4eb97072375ed70622840d4c2e44e 100755 --- a/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mipidsi-develop.md @@ -22,10 +22,10 @@ struct MipiDsiCntlrMethod { // 核心层结构体的成员函数 int32_t (*getCmd)(struct MipiDsiCntlr *cntlr, struct DsiCmdDesc *cmd, uint32_t readLen, uint8_t *out); void (*toHs)(struct MipiDsiCntlr *cntlr); void (*toLp)(struct MipiDsiCntlr *cntlr); - void (*enterUlps)(struct MipiDsiCntlr *cntlr);// 【可选】进入超低功耗模式 - void (*exitUlps)(struct MipiDsiCntlr *cntlr); // 【可选】退出超低功耗模式 + void (*enterUlps)(struct MipiDsiCntlr *cntlr); //【可选】进入超低功耗模式 + void (*exitUlps)(struct MipiDsiCntlr *cntlr); //【可选】退出超低功耗模式 int32_t (*powerControl)(struct MipiDsiCntlr *cntlr, uint8_t enable);//【可选】使能/去使能功耗控制 - int32_t (*attach)(struct MipiDsiCntlr *cntlr);// 【可选】将一个DSI设备连接上host + int32_t (*attach)(struct MipiDsiCntlr *cntlr); //【可选】将一个DSI设备连接上host }; ``` @@ -42,23 +42,24 @@ struct MipiDsiCntlrMethod { // 核心层结构体的成员函数 ## 开发步骤 -MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +MIPI DSI模块适配的三个必选环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 -1. **实例化驱动入口:** - - 实例化HdfDriverEntry结构体成员。 - - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 - -2. **配置属性文件:** +1. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加mipidsi_config.hcs器件属性文件。 -3. **实例化MIPIDSI控制器对象:** +2. 实例化驱动入口 + - 实例化HdfDriverEntry结构体成员。 + - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 + +3. 实例化MIPIDSI控制器对象 - 初始化MipiDsiCntlr成员。 - 实例化MipiDsiCntlr成员MipiDsiCntlrMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化MipiDsiCntlr成员MipiDsiCntlrMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 @@ -66,7 +67,9 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 下方将以mipi_tx_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 一般来说,驱动开发首先需要在xx_config.hcs中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。器件属性值与核心层MipiDsiCntlr成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 +1. 一般来说,驱动开发首先需要在xx_config.hcs中配置器件属性,并在device_info.hcs文件中添加deviceNode描述。 + + 器件属性值与核心层MipiDsiCntlr成员的默认值或限制范围有密切关系,deviceNode信息与驱动入口注册相关。 但本例中MIPI控制器无需配置额外属性,如有厂商需要,则需要在device_info文件的deviceNode增加deviceMatchAttr信息,以及增加mipidsi_config文件。 @@ -84,8 +87,8 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 policy = 0; priority = 150; permission = 0644; - moduleName = "HDF_MIPI_TX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 - serviceName = "HDF_MIPI_TX"; // 【必要且唯一】驱动对外发布服务的名称 + moduleName = "HDF_MIPI_TX"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HDF_MIPI_TX"; // 【必要且唯一】驱动对外发布服务的名称。 } } } @@ -93,10 +96,13 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 } ``` -2. 完成器件属性文件的配置之后,下一步请实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 +2. 完成器件属性文件的配置之后,下一步请实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HdfDriverEntry结构体的函数指针成员会被厂商操作函数填充,HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组,方便调用。 + 一般在加载驱动时HDF框架会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - - MIPI DSI驱动入口参考 + MIPI DSI驱动入口参考: ``` struct HdfDriverEntry g_mipiTxDriverEntry = { @@ -108,7 +114,8 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 HDF_INIT(g_mipiTxDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -3. 完成驱动入口注册之后,最后一步就是以核心层MipiDsiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MipiDsiCntlr成员MipiDsiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层MipiDsiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MipiDsiCntlr成员MipiDsiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考 从驱动的角度看,自定义结构体是参数和数据的载体,一般来说,config文件中的数值也会用来初始化结构体成员,但本例的mipidsi无器件属性文件,故基本成员结构与MipiDsiCntlr无太大差异。 @@ -118,7 +125,7 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 typedef struct { unsigned int devno; // 设备号 short laneId[LANE_MAX_NUM]; // lane号 - OutPutModeTag outputMode; // 输出模式选择:刷新模式,命令行模式和视频流模式 + OutPutModeTag outputMode; // 输出模式选择:刷新模式,命令行模式或视频流模式 VideoModeTag videoMode; // 显示设备的同步模式 OutputFormatTag outputFormat; // 输出DSI图像数据格式:RGB或YUV SyncInfoTag syncInfo; // 时序相关的设置 @@ -126,7 +133,7 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 unsigned int pixelClk; // 时钟,单位KHz } ComboDevCfgTag; - // MipiDsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // MipiDsiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct MipiDsiCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -153,11 +160,11 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态 (下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 | 状态(值) | 问题描述 | @@ -178,21 +185,21 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 static int32_t Hi35xxMipiTxInit(struct HdfDeviceObject *device) { int32_t ret; - g_mipiTx.priv = NULL; // g_mipiTx是定义的全局变量 - // static struct MipiDsiCntlr g_mipiTx { - // .devNo=0 - //}; - g_mipiTx.ops = &g_method;// MipiDsiCntlrMethod的实例化对象的挂载 + g_mipiTx.priv = NULL; // g_mipiTx是定义的全局变量 + // static struct MipiDsiCntlr g_mipiTx { + // .devNo=0 + //}; + g_mipiTx.ops = &g_method; // MipiDsiCntlrMethod的实例化对象的挂载 ret = MipiDsiRegisterCntlr(&g_mipiTx, device);// 【必要】调用核心层函数和g_mipiTx初始化核心层全局变量 ... - return MipiTxDrvInit(0); // 【必要】厂商对设备的初始化,形式不限 + return MipiTxDrvInit(0); // 【必要】厂商对设备的初始化,形式不限 } // mipi_dsi_core.c核心层 int32_t MipiDsiRegisterCntlr(struct MipiDsiCntlr *cntlr, struct HdfDeviceObject *device) { ... - // 定义的全局变量:static struct MipiDsiHandle g_mipiDsihandle[MAX_CNTLR_CNT]; + // 定义的全局变量:static struct MipiDsiHandle g_mipiDsihandle[MAX_CNTLR_CNT]; if (g_mipiDsihandle[cntlr->devNo].cntlr == NULL) { (void)OsalMutexInit(&g_mipiDsihandle[cntlr->devNo].lock); (void)OsalMutexInit(&(cntlr->lock)); @@ -213,7 +220,7 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -221,8 +228,10 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 函数说明: - 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 ``` static void Hi35xxMipiTxRelease(struct HdfDeviceObject *device) @@ -230,7 +239,7 @@ MIPI DSI模块适配的三个环节是配置属性文件,实例化驱动入口 struct MipiDsiCntlr *cntlr = NULL; ... cntlr = MipiDsiCntlrFromDevice(device);// 这里有HdfDeviceObject到MipiDsiCntlr的强制转化 - // return (device == NULL) ? NULL : (struct MipiDsiCntlr *)device->service; + // return (device == NULL) ? NULL : (struct MipiDsiCntlr *)device->service; ... MipiTxDrvExit(); // 【必要】对厂商设备所占资源的释放 MipiDsiUnregisterCntlr(&g_mipiTx); // 空函数 diff --git a/zh-cn/device-dev/driver/driver-platform-mmc-develop.md b/zh-cn/device-dev/driver/driver-platform-mmc-develop.md index b0624652da2a2948344a5ba0a8d7e55e6a375be9..f1ecd21a8ba4317a2fe93646ea936ba702e05913 100755 --- a/zh-cn/device-dev/driver/driver-platform-mmc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-mmc-develop.md @@ -58,23 +58,24 @@ struct MmcCntlrOps { ## 开发步骤 -MMC模块适配的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +MMC模块适配的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加mmc_config.hcs器件属性文件。 -3. **实例化MMC控制器对象:** +3. 实例化MMC控制器对象 - 初始化MmcCntlr成员。 - 实例化MmcCntlr成员MmcCntlrOps。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化MmcCntlr成员MmcCntlrOps,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,设备启动是否成功等。 @@ -82,7 +83,9 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, 下方将以himci.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 @@ -99,8 +102,12 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, HDF_INIT(g_mmcDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在mmc_config.hcs中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层MmcCntlr成员的默认值或限制范围有密切关系。 - 如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在mmc_config文件中增加对应的器件属性**。** +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在mmc_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层MmcCntlr成员的默认值或限制范围有密切关系。 + + 如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在mmc_config文件中增加对应的器件属性。 + - device_info.hcs 配置参考 @@ -116,9 +123,9 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, policy = 2; priority = 10; permission = 0644; - moduleName = "hi3516_mmc_driver"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致; - serviceName = "HDF_PLATFORM_MMC_0"; // 【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hi3516_mmc_emmc";// 【必要】用于配置控制器私有数据,要与 mmc_config.hcs 中对应控制器保持一致 + moduleName = "hi3516_mmc_driver"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_MMC_0"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hi3516_mmc_emmc";// 【必要】用于配置控制器私有数据,要与mmc_config.hcs中对应控制器保持一致。 } device1 :: deviceNode { policy = 1; @@ -149,7 +156,7 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, root { platform { mmc_config { - template mmc_controller {// 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 + template mmc_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 match_attr = ""; voltDef = 0; // 3.3V freqMin = 50000; // 【必要】最小频率值 @@ -158,13 +165,13 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, maxBlkNum = 2048; // 【必要】最大的block号 maxBlkSize = 512; // 【必要】最大的block个数 ocrDef = 0x300000; // 【必要】工作电压设置相关 - caps2 = 0; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps2定义 + caps2 = 0; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps2定义。 regSize = 0x118; // 【必要】寄存器位宽 hostId = 0; // 【必要】主机号 regBasePhy = 0x10020000;// 【必要】寄存器物理基地址 irqNum = 63; // 【必要】中断号 - devType = 2; // 【必要】模式选择:emmc, SD, SDIO ,COMBO - caps = 0x0001e045; // 【必要】属性寄存器相关,见mmc_caps.h 中 MmcCaps 定义 + devType = 2; // 【必要】模式选择:emmc、SD、SDIO、COMBO + caps = 0x0001e045; // 【必要】属性寄存器相关,见mmc_caps.h中MmcCaps 定义。 } controller_0x10100000 :: mmc_controller { match_attr = "hi3516_mmc_emmc";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 @@ -196,16 +203,17 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层MmcCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MmcCntlr成员MmcCntlrOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层MmcCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化MmcCntlr成员MmcCntlrOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且mmc_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员 ,一些重要数值也会传递给核心层对象。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且mmc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 ``` struct HimciHost { struct MmcCntlr *mmc;// 【必要】核心层结构体 - struct MmcCmd *cmd; // 【必要】核心层结构体,传递命令的,相关命令见枚举量 MmcCmdCode + struct MmcCmd *cmd; // 【必要】核心层结构体,传递命令的,相关命令见枚举量MmcCmdCode。 // 【可选】根据厂商驱动需要添加 void *base; enum HimciPowerStatus powerStatus; @@ -223,7 +231,7 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, bool waitForEvent; HIMCI_EVENT himciEvent; }; - // MmcCntlr是核心层控制器结构体,其中的成员在bind函数中会被赋值 + // MmcCntlr是核心层控制器结构体,其中的成员在Bind函数中会被赋值。 struct MmcCntlr { struct IDeviceIoService service; struct HdfDeviceObject *hdfDevObj; @@ -276,13 +284,13 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, ``` - Bind函数参考 - 入参**:** + 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 | 状态(值) | 问题描述 | | -------- | -------- | @@ -295,7 +303,7 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - MmcCntlr,HimciHost,HdfDeviceObject之间互相赋值,方便其他函数可以相互转化,初始化自定义结构体HimciHost对象,初始化MmcCntlr成员,调用核心层MmcCntlrAdd函数。 + MmcCntlr、HimciHost、HdfDeviceObject之间互相赋值,方便其他函数可以相互转化,初始化自定义结构体HimciHost对象,初始化MmcCntlr成员,调用核心层MmcCntlrAdd函数。 ``` @@ -307,18 +315,18 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, cntlr = (struct MmcCntlr *)OsalMemCalloc(sizeof(struct MmcCntlr)); host = (struct HimciHost *)OsalMemCalloc(sizeof(struct HimciHost)); - host->mmc = cntlr; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 - cntlr->priv = (void *)host; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 - cntlr->ops = &g_himciHostOps; // 【必要】MmcCntlrOps的实例化对象的挂载 - cntlr->hdfDevObj = obj; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - obj->service = &cntlr->service; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - ret = MmcCntlrParse(cntlr, obj); // 【必要】 初始化 cntlr,失败就goto _ERR; + host->mmc = cntlr; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 + cntlr->priv = (void *)host; // 【必要】使HimciHost与MmcCntlr可以相互转化的前提 + cntlr->ops = &g_himciHostOps; // 【必要】MmcCntlrOps的实例化对象的挂载 + cntlr->hdfDevObj = obj; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + obj->service = &cntlr->service; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + ret = MmcCntlrParse(cntlr, obj); // 【必要】 初始化cntlr,失败就goto _ERR。 ... - ret = HimciHostParse(host, obj); // 【必要】 初始化host对象的相关属性,失败就goto _ERR; + ret = HimciHostParse(host, obj); // 【必要】 初始化host对象的相关属性,失败就goto _ERR。 ... - ret = HimciHostInit(host, cntlr);// 厂商自定义的初始化,失败就 goto _ERR; + ret = HimciHostInit(host, cntlr); // 厂商自定义的初始化,失败就goto _ERR。 ... - ret = MmcCntlrAdd(cntlr); // 调用核心层函数 失败就goto _ERR; + ret = MmcCntlrAdd(cntlr); // 调用核心层函数,失败就goto _ERR。 ... (void)MmcCntlrAddDetectMsgToQueue(cntlr);// 将卡检测消息添加到队列中。 HDF_LOGD("HimciMmcBind: success."); @@ -334,7 +342,7 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -364,7 +372,7 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, 入参: - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -372,7 +380,11 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, 函数说明: - 释放内存和删除控制器等操作,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用 Release释放驱动资源。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + 释放内存和删除控制器等操作,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用 Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + ``` @@ -380,8 +392,8 @@ MMC模块适配的三个环节是配置属性文件,实例化驱动入口, { struct MmcCntlr *cntlr = NULL; ... - cntlr = (struct MmcCntlr *)obj->service;// 这里有HdfDeviceObject到MmcCntlr的强制转化,通过service成员,赋值见Bind函数 + cntlr = (struct MmcCntlr *)obj->service; // 这里有HdfDeviceObject到MmcCntlr的强制转化,通过service成员,赋值见Bind函数。 ... - HimciDeleteHost((struct HimciHost *)cntlr->priv);// 厂商自定义的内存释放函数,这里有MmcCntlr到HimciHost的强制转化 + HimciDeleteHost((struct HimciHost *)cntlr->priv);// 厂商自定义的内存释放函数,这里有MmcCntlr到HimciHost的强制转化。 } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-pin-develop.md b/zh-cn/device-dev/driver/driver-platform-pin-develop.md index 1b5acee3adf72477e8902e83e0412f50cd8e3bdf..f3da58f351440a893e3566eda4d94eaf72dcc6b4 100755 --- a/zh-cn/device-dev/driver/driver-platform-pin-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-pin-develop.md @@ -61,12 +61,12 @@ struct PinCntlrMethod { | 成员函数 | 入参 | 出参 | 返回值 | 功能 | | ------------ | ------------------------------------------- | ------ | ---- | ---- | -| SetPinPull | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号
**pullType**:枚举常量,Pin管脚推拉方式 | 无 |HDF_STATUS相关状态|PIN设置管脚推拉方式| -| GetPinPull | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号 | **pullType**:枚举常量指针,传出Pin管脚推拉方式 | HDF_STATUS相关状态 | PIN获取管脚推拉方式 | -| SetPinStrength | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号
**strength**:uint32_t变量,Pin推拉强度 | 无 | HDF_STATUS相关状态 | PIN设置推拉强度 | -| GetPinStrength | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号 | **strength**:uint32_t变量指针,传出Pin推拉强度 | HDF_STATUS相关状态 | PIN获取推拉强度 | -| SetPinFunc | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号
**funcName**:char指针常量,传入Pin管脚功能 | 无 | HDF_STATUS相关状态 | PIN设置管脚功能 | -| GetPinFunc | **cntlr**:结构体指针,核心层Pin控制器
**index**:uint32_t变量,管脚索引号 | **funcName**:char双重指针常量,传出Pin管脚功能 | HDF_STATUS相关状态 | PIN获取管脚功能 | +| SetPinPull | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
pullType:枚举常量,Pin管脚推拉方式 | 无 |HDF_STATUS相关状态|PIN设置管脚推拉方式| +| GetPinPull | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | pullType:枚举常量指针,传出Pin管脚推拉方式 | HDF_STATUS相关状态 | PIN获取管脚推拉方式 | +| SetPinStrength | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
strength:uint32_t变量,Pin推拉强度 | 无 | HDF_STATUS相关状态 | PIN设置推拉强度 | +| GetPinStrength | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | strength:uint32_t变量指针,传出Pin推拉强度 | HDF_STATUS相关状态 | PIN获取推拉强度 | +| SetPinFunc | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号
funcName:char指针常量,传入Pin管脚功能 | 无 | HDF_STATUS相关状态 | PIN设置管脚功能 | +| GetPinFunc | cntlr:结构体指针,核心层Pin控制器
index:uint32_t变量,管脚索引号 | funcName:char双重指针常量,传出Pin管脚功能 | HDF_STATUS相关状态 | PIN获取管脚功能 | ### 开发步骤 @@ -77,12 +77,14 @@ PIN模块适配包含以下四个步骤: - 实例化核心层接口函数。 - 驱动调试。 -1. **实例化驱动入口:** +1. 实例化驱动入口: - 实例化HdfDriverEntry结构体成员。 - 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 + 一般在加载驱动时HDF会先调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 ```c @@ -93,11 +95,13 @@ PIN模块适配包含以下四个步骤: .Release = Hi35xxPinRelease, .moduleName = "hi35xx_pin_driver", // 【必要且与HCS文件中里面的moduleName匹配】 }; - HDF_INIT(g_hi35xxPinDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 + HDF_INIT(g_hi35xxPinDriverEntry); // 调用HDF_INIT将驱动入口注册到HDF框架中 ``` -2. **配置属性文件:** +2. 配置属性文件: + - 在vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 + ```c root { device_info { @@ -105,13 +109,13 @@ PIN模块适配包含以下四个步骤: hostName = "platform_host"; priority = 50; device_pin :: device { - device0 :: deviceNode { // 为每一个Pin控制器配置一个HDF设备节点,存在多个时须添加,否则不用 - policy = 0; // 2:用户态可见,1:内核态可见,0:不需要发布服务 + device0 :: deviceNode { // 为每一个Pin控制器配置一个HDF设备节点,存在多个时须添加,否则不用。 + policy = 0; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 priority = 10; // 驱动启动优先级 permission = 0644; // 驱动创建设备节点权限 - /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 */ + /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 */ moduleName = "hi35xx_pin_driver"; - /* 【必要】用于配置控制器私有数据,要与pin_config.hcs中对应控制器保持一致,具体的控制器信息在pin_config.hcs中 */ + /* 【必要】用于配置控制器私有数据,要与pin_config.hcs中对应控制器保持一致,具体的控制器信息在pin_config.hcs中。 */ deviceMatchAttr = "hisilicon_hi35xx_pin_0"; } device1 :: deviceNode { @@ -128,12 +132,13 @@ PIN模块适配包含以下四个步骤: } ``` - 添加pin_config.hcs器件属性文件。 + 在device/soc/hisilicon/hi3516dv300/sdk_liteos/hdf_config/pin/pin_config.hcs目录下配置器件属性,其中配置参数如下: ```c root { platform { pin_config_hi35xx { - template pin_controller { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 + template pin_controller { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 number = 0; // 【必要】controller编号 regStartBasePhy = 0; // 【必要】寄存器物理基地址起始地址 regSize = 0; // 【必要】寄存器位宽 @@ -163,16 +168,18 @@ PIN模块适配包含以下四个步骤: F1 = "SFC_CLK"; F2 = "SFC_BOOT_MODE"; } - ...... // 对应管脚控制器下的每个管脚,按实际添加 + ...... // 对应管脚控制器下的每个管脚,按实际添加。 } - ......// 每个管脚控制器对应一个controller节点,如存在多个Pin控制器,请依次添加对应的controller节点 + ......// 每个管脚控制器对应一个controller节点,如存在多个Pin控制器,请依次添加对应的controller节点。 } } } ``` -3. **实例化PIN控制器对象:** +3. 实例化PIN控制器对象: + - 初始化PinCntlr成员。 + 在Hi35xxPinCntlrInit函数中对PinCntlr成员进行初始化操作。 ```c @@ -208,7 +215,7 @@ PIN模块适配包含以下四个步骤: uint32_t pinCount; }; - // PinCntlr是核心层控制器,其中的成员在init函数中会被赋值 + // PinCntlr是核心层控制器,其中的成员在Init函数中会被赋值。 struct PinCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -253,7 +260,7 @@ PIN模块适配包含以下四个步骤: HDF_LOGE("%s: read pinCount failed", __func__); return ret; } - // 将读取的值赋值给管脚控制器的成员,完成管脚控制器初始化 + // 将读取的值赋值给管脚控制器的成员,完成管脚控制器初始化。 hi35xx->cntlr.pinCount = hi35xx->pinCount; hi35xx->cntlr.number = hi35xx->number; hi35xx->regBase = OsalIoRemap(hi35xx->regStartBasePhy, hi35xx->regSize); // 管脚控制器映射 @@ -284,10 +291,12 @@ PIN模块适配包含以下四个步骤: - Init函数 入参: - HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + + HdfDeviceObject这个是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: - HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见/drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS 定义)。 + + HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见/drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS定义)。 | **状态(值)** | **问题描述** | | ---------------------- | -------------- | @@ -299,6 +308,7 @@ PIN模块适配包含以下四个步骤: | HDF_FAILURE | 初始化失败 | 函数说明: + 初始化自定义结构体对象和PinCntlr成员,并通过调用核心层PinCntlrAdd函数挂载Pin控制器。 ```c @@ -360,7 +370,7 @@ PIN模块适配包含以下四个步骤: ret = Hi35xxPinCntlrInit(device, hi35xx); // 管脚控制器初始化 ...... DEV_RES_NODE_FOR_EACH_CHILD_NODE(device->property, childNode) { // 遍历管脚控制器的每个子节点 - ret = Hi35xxPinParsePinNode(childNode, hi35xx, index); // 解析子节点 + ret = Hi35xxPinParsePinNode(childNode, hi35xx, index); // 解析子节点 ...... } @@ -378,7 +388,7 @@ PIN模块适配包含以下四个步骤: 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: @@ -424,5 +434,6 @@ PIN模块适配包含以下四个步骤: } } ``` -4. **驱动调试:** +4. 驱动调试: + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的信息反馈,数据传输的成功与否等。 \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-platform-pwm-develop.md b/zh-cn/device-dev/driver/driver-platform-pwm-develop.md index 3f32430896b29ef4bbfd07da47a62ccbbaf76316..2b83466cfae808ebc2d85c30ea96f920055f5baf 100755 --- a/zh-cn/device-dev/driver/driver-platform-pwm-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-pwm-develop.md @@ -27,30 +27,31 @@ struct PwmMethod { | 成员函数 | 入参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -| setConfig | -**pwm**:  结构体指针,核心层PWM控制器
-**config**:  结构体指针,属性传入值 | HDF_STATUS相关状态 | 配置属性 | -| open | **pwm**:  结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 打开设备 | -| close | **pwm**:  结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 关闭设备 | +| setConfig | pwm:结构体指针,核心层PWM控制器
config:结构体指针,属性传入值 | HDF_STATUS相关状态 | 配置属性 | +| open | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 打开设备 | +| close | pwm:结构体指针,核心层PWM控制器 | HDF_STATUS相关状态 | 关闭设备 | ## 开发步骤 -PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动入口,以及填充核心层接口函数。 +PWM模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加pwm_config.hcs器件属性文件。 -3. **实例化PWM控制器对象:** +3. 实例化PWM控制器对象 - 初始化PwmDev成员。 - 实例化PwmDev成员PwmMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化PwmDev成员PwmMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如PWM控制状态,中断响应情况等。 @@ -58,16 +59,20 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 下方将以pwm_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - PWM驱动入口参考: + PWM驱动入口参考: ``` struct HdfDriverEntry g_hdfPwm = { .moduleVersion = 1, - .moduleName = "HDF_PLATFORM_PWM",// 【必要,且与HCS文件中里面的moduleName匹配】 + .moduleName = "HDF_PLATFORM_PWM",// 【必要且与HCS文件中里面的moduleName匹配】 .Bind = HdfPwmBind, .Init = HdfPwmInit, .Release = HdfPwmRelease, @@ -76,7 +81,10 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 HDF_INIT(g_hdfPwm); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 pwm_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层PwmDev成员的默认值或限制范围有密切关系。如有更多个器件信息,则需要在device_info文件增加deviceNode信息,以及在pwm_config文件中增加对应的器件属性。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在pwm_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层PwmDev成员的默认值或限制范围有密切关系。如有更多个器件信息,则需要在device_info文件增加deviceNode信息,以及在pwm_config文件中增加对应的器件属性。 + - device_info.hcs配置参考 @@ -86,15 +94,15 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 platform :: host { hostName = "platform_host"; priority = 50; - device_pwm :: device {// 为每一个pwm控制器配置一个HDF设备节点 + device_pwm :: device { // 为每一个pwm控制器配置一个HDF设备节点 device0 :: deviceNode { - policy = 1; // 等于1,向内核态发布服务 - priority = 80; // 驱动启动优先级 - permission = 0644;// 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_PWM"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致; - serviceName = "HDF_PLATFORM_PWM_0";// 【必要且唯一】驱动对外发布服务的名称 - deviceMatchAttr = "hisilicon_hi35xx_pwm_0";// 【必要】用于配置控制器私有数据,要与 pwm_config.hcs 中对应 - // 控制器保持一致,具体的控制器信息在 pwm_config.hcs 中 + policy = 1; // 等于1,向内核态发布服务。 + priority = 80; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_PWM"; // 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_PWM_0"; // 【必要且唯一】驱动对外发布服务的名称 + deviceMatchAttr = "hisilicon_hi35xx_pwm_0";// 【必要】用于配置控制器私有数据,要与pwm_config.hcs中对应 + // 控制器保持一致,具体的控制器信息在pwm_config.hcs中。 } device1 :: deviceNode { policy = 1; @@ -135,30 +143,31 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层PwmDev对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化PwmDev成员PwmMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成驱动入口注册之后,下一步就是以核心层PwmDev对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化PwmDev成员PwmMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考。 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且pwm_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且pwm_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 ``` struct HiPwm { struct PwmDev dev; // 【必要】 核心层结构体 volatile unsigned char *base; - struct HiPwmRegs *reg; // 设备属性结构体,可自定义 + struct HiPwmRegs *reg; // 设备属性结构体,可自定义。 bool supportPolarity; }; - // PwmDev是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // PwmDev是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct PwmDev { struct IDeviceIoService service; struct HdfDeviceObject *device; - struct PwmConfig cfg; // 属性结构体,相关定义见下 + struct PwmConfig cfg; // 属性结构体,相关定义见下。 struct PwmMethod *method; // 钩子函数模板 bool busy; uint32_t num; // 设备号 OsalSpinlock lock; - void *priv; // 私有数据,一般存储自定义结构体首地址,方便调用 + void *priv; // 私有数据,一般存储自定义结构体首地址,方便调用。 }; struct PwmConfig { uint32_t duty; // 占空时间 nanoseconds @@ -189,11 +198,11 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 入参: - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 | 状态(值) | 问题描述 | | -------- | -------- | @@ -210,7 +219,7 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 ``` - // 此处bind函数为空函数,可与init函数结合,也可根据厂商需要实现相关操作 + // 此处Bind函数为空函数,可与Init函数结合,也可根据厂商需要实现相关操作。 static int32_t HdfPwmBind(struct HdfDeviceObject *obj) { (void)obj; @@ -237,16 +246,16 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE);//初始化自定义结构体HiPwm ... - hp->reg = (struct HiPwmRegs *)hp->base; // 初始化自定义结构体HiPwm - hp->supportPolarity = false; // 初始化自定义结构体HiPwm - hp->dev.method = &g_pwmOps; // PwmMethod的实例化对象的挂载 - hp->dev.cfg.duty = PWM_DEFAULT_DUTY_CYCLE; // 初始化PwmDev - hp->dev.cfg.period = PWM_DEFAULT_PERIOD; // 初始化PwmDev - hp->dev.cfg.polarity = PWM_DEFAULT_POLARITY; // 初始化PwmDev - hp->dev.cfg.status = PWM_DISABLE_STATUS; // 初始化PwmDev - hp->dev.cfg.number = 0; // 初始化PwmDev - hp->dev.busy = false; // 初始化PwmDev - if (PwmDeviceAdd(obj, &(hp->dev)) != HDF_SUCCESS) {// 【重要】调用核心层函数,初始化hp->dev 的设备和服务 + hp->reg = (struct HiPwmRegs *)hp->base; // 初始化自定义结构体HiPwm + hp->supportPolarity = false; // 初始化自定义结构体HiPwm + hp->dev.method = &g_pwmOps; // PwmMethod的实例化对象的挂载 + hp->dev.cfg.duty = PWM_DEFAULT_DUTY_CYCLE; // 初始化PwmDev + hp->dev.cfg.period = PWM_DEFAULT_PERIOD; // 初始化PwmDev + hp->dev.cfg.polarity = PWM_DEFAULT_POLARITY; // 初始化PwmDev + hp->dev.cfg.status = PWM_DISABLE_STATUS; // 初始化PwmDev + hp->dev.cfg.number = 0; // 初始化PwmDev + hp->dev.busy = false; // 初始化PwmDev + if (PwmDeviceAdd(obj, &(hp->dev)) != HDF_SUCCESS) { // 【重要】调用核心层函数,初始化hp->dev的设备和服务。 OsalIoUnmap((void *)hp->base); return HDF_FAILURE; } @@ -265,7 +274,7 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口, 当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 ``` @@ -275,7 +284,7 @@ PWM模块适配HDF框架的三个环节是配置属性文件,实例化驱动 ... hp = (struct HiPwm *)obj->service;// 这里有HdfDeviceObject到HiPwm的强制转化 ... - PwmDeviceRemove(obj, &(hp->dev));// 【必要】调用核心层函数,释放PwmDev的设备和服务,这里有HiPwm到PwmDev的强制转化 - HiPwmRemove(hp); // 释放HiPwm + PwmDeviceRemove(obj, &(hp->dev)); // 【必要】调用核心层函数,释放PwmDev的设备和服务,这里有HiPwm到PwmDev的强制转化。 + HiPwmRemove(hp); // 释放HiPwm } ``` diff --git a/zh-cn/device-dev/driver/driver-platform-regulator-develop.md b/zh-cn/device-dev/driver/driver-platform-regulator-develop.md index caf59384cdaca17354ed3b69a62d8362d96456a0..b72c9c13199b7ac7b9a5067936366316c0e0785d 100755 --- a/zh-cn/device-dev/driver/driver-platform-regulator-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-regulator-develop.md @@ -61,17 +61,17 @@ struct RegulatorMethod { | 成员函数 | 入参 | 返回值 | 功能 | | ------------ | ----------------------------------------------------------- | ----------------- | ---------------- | -| open | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 打开设备 | -| close | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 关闭设备 | -| release | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 释放设备句柄 | -| enable | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 使能 | -| disable | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 禁用 | -| forceDisable | **node**:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 强制禁用 | -| setVoltage | **node**:结构体指针,核心层Regulator节点
**minUv**:uint32_t变量,最小电压
**maxUv**:uint32_t变量,最大电压 | HDF_STATUS相关状态 | 设置输出电压范围 | -| getVoltage | **node**:结构体指针,核心层Regulator节点
**voltage**:uint32_t指针,传出电压值 | HDF_STATUS相关状态 | 获取电压 | -| setCurrent | **node**:结构体指针,核心层Regulator节点
**minUa**:uint32_t变量,最小电流
**maxUa**:uint32_t变量,最大电流 | HDF_STATUS相关状态 | 设置输出电流范围 | -| getCurrent | **node**:结构体指针,核心层Regulator节点
**regCurrent**:uint32_t指针,传出电流值 | HDF_STATUS相关状态 | 获取电流 | -| getStatus | **node**:结构体指针,核心层Regulator节点
**status**:uint32_t指针,传出状态值 | HDF_STATUS相关状态 | 获取设备状态 | +| open | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 打开设备 | +| close | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 关闭设备 | +| release | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 释放设备句柄 | +| enable | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 使能 | +| disable | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 禁用 | +| forceDisable | node:结构体指针,核心层Regulator节点 | HDF_STATUS相关状态 | 强制禁用 | +| setVoltage | node:结构体指针,核心层Regulator节点
minUv:uint32_t变量,最小电压
maxUv:uint32_t变量,最大电压 | HDF_STATUS相关状态 | 设置输出电压范围 | +| getVoltage | node:结构体指针,核心层Regulator节点
voltage:uint32_t指针,传出电压值 | HDF_STATUS相关状态 | 获取电压 | +| setCurrent | node:结构体指针,核心层Regulator节点
minUa:uint32_t变量,最小电流
maxUa:uint32_t变量,最大电流 | HDF_STATUS相关状态 | 设置输出电流范围 | +| getCurrent | node:结构体指针,核心层Regulator节点
regCurrent:uint32_t指针,传出电流值 | HDF_STATUS相关状态 | 获取电流 | +| getStatus | node:结构体指针,核心层Regulator节点
status:uint32_t指针,传出状态值 | HDF_STATUS相关状态 | 获取设备状态 | ### 开发步骤 @@ -82,9 +82,11 @@ Regulator模块适配包含以下四个步骤: - 实例化核心层接口函数。 - 驱动调试。 -1. **实例化驱动入口:** +1. 实例化驱动入口: - 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 HDF框架会汇总所有加载的驱动的HdfDriverEntry对象入口 ,形成一个类似数组的段地址空间,方便上层调用。 + 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会汇总所有加载的驱动的HdfDriverEntry对象入口,形成一个类似数组的段地址空间,方便上层调用。 一般在加载驱动时HDF会先调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 @@ -99,7 +101,7 @@ Regulator模块适配包含以下四个步骤: HDF_INIT(g_regulatorDriverEntry); ``` -2. **配置属性文件:** +2. 配置属性文件: - 在vendor/hisilicon/hispark_taurus/hdf_config/device_info/device_info.hcs文件中添加deviceNode描述。 @@ -127,14 +129,14 @@ Regulator模块适配包含以下四个步骤: hostName = "platform_host"; priority = 50; device_regulator :: device { - device0 :: deviceNode { // 为每一个Regulator控制器配置一个HDF设备节点,存在多个时添加,否则不用 - policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务 - priority = 50; // 驱动启动优先级 + device0 :: deviceNode { // 为每一个Regulator控制器配置一个HDF设备节点,存在多个时添加,否则不用。 + policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 + priority = 50; // 驱动启动优先级 permission = 0644; // 驱动创建设备节点权限 - /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致 */ + /* 【必要】用于指定驱动名称,需要与期望的驱动Entry中的moduleName一致。 */ moduleName = "HDF_PLATFORM_REGULATOR_MANAGER"; serviceName = "HDF_PLATFORM_REGULATOR_MANAGER"; //【必要且唯一】驱动对外发布服务的名称 - /* 【必要】用于配置控制器私有数据,要与regulator_config.hcs中对应控制器保持一致,具体的控制器信息在regulator_config.hcs中 */ + /* 【必要】用于配置控制器私有数据,要与regulator_config.hcs中对应控制器保持一致,具体的控制器信息在regulator_config.hcs中。 */ deviceMatchAttr = "hdf_platform_regulator_manager"; } device1 :: deviceNode { @@ -157,7 +159,7 @@ Regulator模块适配包含以下四个步骤: platform { regulator_config { match_attr = "linux_regulator_adapter"; - template regulator_controller { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 + template regulator_controller { // 【必要】模板配置,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 device_num = 1; name = ""; devName = "regulator_adapter_consumer01"; @@ -179,7 +181,7 @@ Regulator模块适配包含以下四个步骤: minUa = 0; maxUa = 0; } - /* 每个Regulator控制器对应一个controller节点,如存在多个Regulator控制器,请依次添加对应的controller节点 */ + /* 每个Regulator控制器对应一个controller节点,如存在多个Regulator控制器,请依次添加对应的controller节点。 */ controller_0x130d0001 :: regulator_controller { device_num = 1; name = "regulator_adapter_2"; @@ -196,16 +198,16 @@ Regulator模块适配包含以下四个步骤: } ``` -3. **实例化核心层接口函数:** +3. 实例化核心层接口函数: - - 完成驱动入口注册之后,最后一步就是对核心层RegulatorNode对象的初始化,包括厂商自定义结构体(传递参数和数据),实例化RegulatorNode成员RegulatorMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 + - 完成驱动入口注册之后,下一步就是对核心层RegulatorNode对象的初始化,包括厂商自定义结构体(传递参数和数据),实例化RegulatorNode成员RegulatorMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 - 自定义结构体参考。 从驱动的角度看,RegulatorNode结构体是参数和数据的载体,HDF框架通过DeviceResourceIface将regulator\_config.hcs文件中的数值读入其中。 ``` - // RegulatorNode是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // RegulatorNode是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct RegulatorNode { struct RegulatorDesc regulatorInfo; struct DListHead node; @@ -215,17 +217,17 @@ Regulator模块适配包含以下四个步骤: }; struct RegulatorDesc { - const char *name; /* regulator名称 */ - const char *parentName; /* regulator父节点名称 */ + const char *name; /* regulator名称 */ + const char *parentName; /* regulator父节点名称 */ struct RegulatorConstraints constraints; /* regulator约束信息 */ - uint32_t minUv; /* 最小输出电压值 */ - uint32_t maxUv; /* 最大输出电压值 */ - uint32_t minUa; /* 最小输出电流值 */ - uint32_t maxUa; /* 最大输出电流值 */ - uint32_t status; /* regulator的状态,开或关 */ + uint32_t minUv; /* 最小输出电压值 */ + uint32_t maxUv; /* 最大输出电压值 */ + uint32_t minUa; /* 最小输出电流值 */ + uint32_t maxUa; /* 最大输出电流值 */ + uint32_t status; /* regulator的状态,开或关。*/ int useCount; - int consumerRegNums; /* regulator用户数量 */ - RegulatorStatusChangecb cb; /* 当regulator状态改变时,可通过此变量通知 */ + int consumerRegNums; /* regulator用户数量 */ + RegulatorStatusChangecb cb; /* 当regulator状态改变时,可通过此变量通知。*/ }; struct RegulatorConstraints { @@ -261,11 +263,11 @@ Regulator模块适配包含以下四个步骤: 入参: - HdfDeviceObject 是整个驱动对外暴露的接口参数,具备hcs配置文件的信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,具备HCS配置文件的信息。 返回值: - HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS 定义)。 + HDF\_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf\_base.h中HDF\_STATUS定义)。 **表 2** HDF\_STATUS相关状态 @@ -304,12 +306,12 @@ Regulator模块适配包含以下四个步骤: regNode = (struct RegulatorNode *)OsalMemCalloc(sizeof(*regNode));//加载HCS文件 ... - ret = VirtualRegulatorReadHcs(regNode, node);// 读取HCS文件信息 + ret = VirtualRegulatorReadHcs(regNode, node); // 读取HCS文件信息 ... - regNode->priv = (void *)node; // 实例化节点 - regNode->ops = &g_method; // 实例化ops + regNode->priv = (void *)node; // 实例化节点 + regNode->ops = &g_method; // 实例化ops - ret = RegulatorNodeAdd(regNode); // 挂载节点 + ret = RegulatorNodeAdd(regNode); // 挂载节点 ... } ``` @@ -318,7 +320,7 @@ Regulator模块适配包含以下四个步骤: 入参: - HdfDeviceObject是整个驱动对外暴露的接口参数,其包含了hcs配置文件中的相关配置信息。 + HdfDeviceObject是整个驱动对外暴露的接口参数,其包含了HCS配置文件中的相关配置信息。 返回值: @@ -336,7 +338,7 @@ Regulator模块适配包含以下四个步骤: } ``` -4. **驱动调试:** +4. 驱动调试: 【可选】针对新增驱动程序,建议验证驱动基本功能,例如挂载后的测试用例是否成功等。 diff --git a/zh-cn/device-dev/driver/driver-platform-rtc-develop.md b/zh-cn/device-dev/driver/driver-platform-rtc-develop.md index e811116e5e5a08b4bde83f8e400c27d926c77b0c..e94f517b89392ef3e256833ad0ded234bbbe9e56 100755 --- a/zh-cn/device-dev/driver/driver-platform-rtc-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-rtc-develop.md @@ -3,7 +3,7 @@ ## 概述 -RTC(real-time clock)为操作系统中的实时时钟设备。在HDF框架中,RTC的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +RTC(Real-time Clock)为操作系统中的实时时钟设备。在HDF框架中,RTC的接口适配模式采用独立服务模式,在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 **图1** RTC独立服务模式结构图 @@ -50,23 +50,24 @@ struct RtcMethod { ## 开发步骤 -RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动入口,以及填充核心层接口函数。 +RTC模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加rtc_config.hcs器件属性文件。 -3. **实例化RTC控制器对象:** +3. 实例化RTC控制器对象 - 初始化RtcHost成员。 - 实例化RtcHost成员RtcMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化RtcHost成员RtcMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如RTC控制状态,中断响应情况等。 @@ -74,10 +75,15 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 下方将以rtc_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - RTC驱动入口参考: + RTC驱动入口参考: ``` struct HdfDriverEntry g_rtcDriverEntry = { @@ -85,15 +91,19 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 .Bind = HiRtcBind, // 见Bind参考 .Init = HiRtcInit, // 见Init参考 .Release = HiRtcRelease, // 见Release参考 - .moduleName = "HDF_PLATFORM_RTC",// 【必要】且与 HCS 里面的名字匹配 + .moduleName = "HDF_PLATFORM_RTC",// 【必要】且与HCS里面的名字匹配 }; //调用HDF_INIT将驱动入口注册到HDF框架中 HDF_INIT(g_rtcDriverEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 rtc_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层RtcHost成员的默认值或限制范围有密切关系。 - 本例只有一个RTC控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在rtc_config文件中增加对应的器件属性。 - - device_info.hcs 配置参考。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在rtc_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层RtcHost成员的默认值或限制范围有密切关系。 + + 本例只有一个RTC控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在rtc_config文件中增加对应的器件属性。 + + - device_info.hcs配置参考 ``` @@ -102,12 +112,12 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 platform :: host { device_rtc :: device { device0 :: deviceNode { - policy = 1; // 2:用户态可见,1:内核态可见,0:不需要发布服务 - priority = 30; // 值越小,优先级越高 + policy = 1; // 2:用户态可见;1:内核态可见;0:不需要发布服务。 + priority = 30; // 值越小,优先级越高。 permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_RTC"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致 - serviceName = "HDF_PLATFORM_RTC"; // 【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hisilicon_hi35xx_rtc";// 【必要】需要与设备hcs文件中的 match_attr 匹配 + moduleName = "HDF_PLATFORM_RTC"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_RTC"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_rtc";// 【必要】需要与设备hcs文件中的match_attr匹配。 } } } @@ -115,7 +125,7 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 } ``` - - rtc_config.hcs配置参考。 + - rtc_config.hcs配置参考 ``` @@ -140,10 +150,11 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层RtcHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化RtcHost成员RtcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成属性文件配置之后,下一步就是以核心层RtcHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化RtcHost成员RtcMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考。 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且rtc_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且rtc_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员。 ``` @@ -161,7 +172,7 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct OsalMutex mutex; // 互斥锁 }; - // RtcHost是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // RtcHost是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct RtcHost { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -219,11 +230,11 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 static int32_t HiRtcBind(struct HdfDeviceObject *device) { struct RtcHost *host = NULL; - host = RtcHostCreate(device); // 实际是申请内存并挂接device: host->device = device; + host = RtcHostCreate(device); // 实际是申请内存并挂接device: host->device = device // 使HdfDeviceObject与RtcHost可以相互转化的前提 ... device->service = &host->service;// 使HdfDeviceObject与RtcHost可以相互转化的前提 - // 方便后续通过调用RtcHostFromDevice 实现全局性质的host + // 方便后续通过调用RtcHostFromDevice实现全局性质的host return HDF_SUCCESS; } ``` @@ -252,19 +263,19 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 host = RtcHostFromDevice(device);// 这里是HdfDeviceObject到RtcHost的强制转化 rtcInfo = OsalMemCalloc(sizeof(*rtcInfo)); ... - // HiRtcConfigData 会从设备配置树中读取属性填充rtcInfo 的supportAnaCtrl, supportLock, spiBaseAddr, regAddrLength, irq - // 为HiRtcSwInit和HiRtcSwInit提供参数,当函数HiRtcSwInit和HiRtcSwInit内部执行失败后进行内存释放等操作 + // HiRtcConfigData会从设备配置树中读取属性填充rtcInfo的supportAnaCtrl、supportLock、spiBaseAddr、regAddrLength、irq, + // 为HiRtcSwInit和HiRtcSwInit提供参数,当函数HiRtcSwInit和HiRtcSwInit内部执行失败后进行内存释放等操作。 if (HiRtcConfigData(rtcInfo, device->property) != 0) { ... } if (HiRtcSwInit(rtcInfo) != 0) {// 地址映射以及中断注册相关 ... } - if (HiRtcHwInit(rtcInfo) != 0) {// 初始化anaCtrl 和 lockAddr 相关内容 + if (HiRtcHwInit(rtcInfo) != 0) {// 初始化anaCtrl和lockAddr相关内容 ... } - host->method = &g_method;//RtcMethod的实例化对象的挂载 + host->method = &g_method;// RtcMethod的实例化对象的挂载 host->data = rtcInfo; // 使RtcConfigInfo与RtcHost可以相互转化的前提 HDF_LOGI("Hdf dev service:%s init success!", HdfDeviceGetServiceName(device)); return HDF_SUCCESS; @@ -282,7 +293,10 @@ RTC模块适配HDF框架的三个环节是配置属性文件,实例化驱动 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作前提是在Init或Bind函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init或Bind函数中具备对应赋值的操作。 ``` diff --git a/zh-cn/device-dev/driver/driver-platform-sdio-develop.md b/zh-cn/device-dev/driver/driver-platform-sdio-develop.md index 9270200f585e72605bcc8dedda1f459730d2ffba..bd8a24365c64192e6abc03906022c298eb0df433 100755 --- a/zh-cn/device-dev/driver/driver-platform-sdio-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-sdio-develop.md @@ -3,7 +3,7 @@ ## 概述 -SDIO由SD卡发展而来,被统称为mmc(MultiMediaCard),相关技术差别不大。在HDF框架中,SDIO的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +SDIO(Secure Digital Input and Output)由SD卡发展而来,被统称为MMC(MultiMediaCard),相关技术差别不大。在HDF框架中,SDIO的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 **图1** SDIO独立服务模式结构图 @@ -60,29 +60,31 @@ struct SdioDeviceOps { | claimHost | dev:结构体指针,SDIO设备控制器 | 无 | HDF_STATUS相关状态 | 独占HOST | | releaseHost | dev:结构体指针,SDIO设备控制器 | 无 | HDF_STATUS相关状态 | 释放HOST | + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
-> CommonInfo包括maxBlockNum(单个request中最大block数), maxBlockSize(单个block最大字节数), maxRequestSize(单个Request最大字节数), enTimeout(最大超时时间,毫秒), funcNum(功能编号1~7), irqCap(IRQ capabilities), (void \*)data. +> CommonInfo包括maxBlockNum(单个request中最大block数)、maxBlockSize(单个block最大字节数)、maxRequestSize(单个Request最大字节数)、enTimeout(最大超时时间,毫秒)、funcNum(功能编号1~7)、irqCap(IRQ capabilities)、(void \*)data。 ## 开发步骤 -SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动入口,以及填充核心层接口函数。 +SDIO模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及填充核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加sdio_config.hcs器件属性文件。 -3. **实例化SDIO控制器对象:** +3. 实例化SDIO控制器对象 - 初始化SdioDevice成员。 - 实例化SdioDevice成员SdioDeviceOps。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化SdioDevice成员SdioDeviceOps,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如SDIO控制状态,中断响应情况等。 @@ -90,10 +92,15 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 下方将以sdio_adapter.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - SDIO 驱动入口参考: + SDIO 驱动入口参考: ``` struct HdfDriverEntry g_sdioDriverEntry = { @@ -101,14 +108,18 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 .Bind = Hi35xxLinuxSdioBind, // 见Bind参考 .Init = Hi35xxLinuxSdioInit, // 见Init参考 .Release = Hi35xxLinuxSdioRelease,// 见Release参考 - .moduleName = "HDF_PLATFORM_SDIO",// 【必要,且与HCS文件中里面的moduleName匹配】 + .moduleName = "HDF_PLATFORM_SDIO",// 【必要且与HCS文件中里面的moduleName匹配】 }; // 调用HDF_INIT将驱动入口注册到HDF框架中 HDF_INIT(g_sdioDriverEntry); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 sdio_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层SdioDevice成员的默认值或限制范围有密切关系。 - 本例只有一个SDIO控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在sdio_config文件中增加对应的器件属性。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在sdio_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层SdioDevice成员的默认值或限制范围有密切关系。 + + 本例只有一个SDIO控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在sdio_config文件中增加对应的器件属性。 + - device_info.hcs 配置参考: @@ -124,9 +135,9 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 policy = 1; priority = 70; permission = 0644; - moduleName = "HDF_PLATFORM_SDIO"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致; - serviceName = "HDF_PLATFORM_MMC_2"; // 【必要】驱动对外发布服务的名称,必须唯一 - deviceMatchAttr = "hisilicon_hi35xx_sdio_0";// 【必要】用于配置控制器私有数据,要与sdio_config.hcs中对应控制器保持一致 + moduleName = "HDF_PLATFORM_SDIO"; // 【必要】用于指定驱动名称,需要与驱动Entry中的moduleName一致。 + serviceName = "HDF_PLATFORM_MMC_2"; // 【必要】驱动对外发布服务的名称,必须唯一。 + deviceMatchAttr = "hisilicon_hi35xx_sdio_0";// 【必要】用于配置控制器私有数据,要与sdio_config.hcs中对应控制器保持一致。 } } } @@ -143,34 +154,35 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 sdio_config { template sdio_controller { match_attr = ""; - hostId = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍 - devType = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍 + hostId = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 + devType = 2; // 【必要】模式固定为2,在mmc_config.hcs有介绍。 } controller_0x2dd1 :: sdio_controller { - match_attr = "hisilicon_hi35xx_sdio_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 + match_attr = "hisilicon_hi35xx_sdio_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致。 } } } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层SdioDevice对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SdioDevice成员SdioDeviceOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成属性文件配置之后,下一步就是以核心层SdioDevice对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SdioDevice成员SdioDeviceOps(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考: - 从驱动的角度看,自定义结构体是参数和数据的载体,而且sdio_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且sdio_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象。 ``` typedef struct { uint32_t maxBlockNum; // 单个request最大的block个数 uint32_t maxBlockSize; // 单个block最大的字节数1~2048 - uint32_t maxRequestSize; // 单个request最大的字节数 1~2048 - uint32_t enTimeout; // 最大超时时间,单位毫秒,且不能超过一秒 + uint32_t maxRequestSize; // 单个request最大的字节数1~2048 + uint32_t enTimeout; // 最大超时时间,单位毫秒,且不能超过一秒。 uint32_t funcNum; // 函数编号1~7 uint32_t irqCap; // 中断能力 void *data; // 私有数据 } SdioFuncInfo; - // SdioDevice是核心层控制器结构体,其中的成员在Bind函数中会被赋值 + // SdioDevice是核心层控制器结构体,其中的成员在Bind函数中会被赋值。 struct SdioDevice { struct SdDevice sd; struct SdioDeviceOps *sdioOps; @@ -184,6 +196,7 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 bool threadRunning; }; ``` + - SdioDevice成员回调函数结构体SdioDeviceOps的实例化,其他成员在Init函数中初始化。 @@ -216,7 +229,8 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + **表2** Bind函数入参及返回值 | 状态(值) | 问题描述 | @@ -241,18 +255,18 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 ... cntlr = (struct MmcCntlr *)OsalMemCalloc(sizeof(struct MmcCntlr));// 分配内存 ... - cntlr->ops = &g_sdioCntlrOps; // 【必要】struct MmcCntlrOps g_sdioCntlrOps={ - // .rescanSdioDev = Hi35xxLinuxSdioRescan,}; - cntlr->hdfDevObj = obj; // 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - obj->service = &cntlr->service;// 【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 - ret = Hi35xxLinuxSdioCntlrParse(cntlr, obj);//【必要】初始化cntlr 的 index, devType, 失败则 goto _ERR; + cntlr->ops = &g_sdioCntlrOps; //【必要】struct MmcCntlrOps g_sdioCntlrOps={ + // .rescanSdioDev = Hi35xxLinuxSdioRescan,}; + cntlr->hdfDevObj = obj; //【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + obj->service = &cntlr->service; //【必要】使HdfDeviceObject与MmcCntlr可以相互转化的前提 + ret = Hi35xxLinuxSdioCntlrParse(cntlr, obj); //【必要】初始化cntlr的index、devType,失败则goto _ERR。 ... - ret = MmcCntlrAdd(cntlr); // 【必要】调用核心层mmc_core.c的函数, 失败则 goto _ERR; + ret = MmcCntlrAdd(cntlr); //【必要】调用核心层mmc_core.c的函数,失败则goto _ERR。 ... - ret = MmcCntlrAllocDev(cntlr, (enum MmcDevType)cntlr->devType);// 【必要】调用核心层mmc_core.c的函数, 失败则 goto _ERR; + ret = MmcCntlrAllocDev(cntlr, (enum MmcDevType)cntlr->devType); //【必要】调用核心层mmc_core.c的函数,失败则goto _ERR。 ... - MmcDeviceAddOps(cntlr->curDev, &g_sdioDeviceOps);// 【必要】调用核心层mmc_core.c的函数, 钩子函数挂载 + MmcDeviceAddOps(cntlr->curDev, &g_sdioDeviceOps); //【必要】调用核心层mmc_core.c的函数,钩子函数挂载。 HDF_LOGD("Hi35xxLinuxSdioBind: Success!"); return HDF_SUCCESS; @@ -298,8 +312,10 @@ SDIO模块适配HDF框架的三个环节是配置属性文件,实例化驱动 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给 Release 接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作前提是在Bind函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Bind函数中具备对应赋值的操作。 ``` static void Hi35xxLinuxSdioRelease(struct HdfDeviceObject *obj) diff --git a/zh-cn/device-dev/driver/driver-platform-spi-develop.md b/zh-cn/device-dev/driver/driver-platform-spi-develop.md index 4ef4033c13db3f68ce83509a02e32af98cf361dc..7d358e1fa4b8c8a5cd62a6258b5a4e2cc79f24ba 100755 --- a/zh-cn/device-dev/driver/driver-platform-spi-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-spi-develop.md @@ -37,23 +37,24 @@ struct SpiCntlrMethod { ## 开发步骤 -SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +SPI模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加spi_config.hcs器件属性文件。 -3. **实例化SPI控制器对象:** +3. 实例化SPI控制器对象 - 初始化SpiCntlr成员。 - 实例化SpiCntlr成员SpiCntlrMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化SpiCntlr成员SpiCntlrMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如SPI控制状态,中断响应情况等。 @@ -61,15 +62,20 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 下方将以spi_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - SPI驱动入口参考: + SPI驱动入口参考: ``` struct HdfDriverEntry g_hdfSpiDevice = { .moduleVersion = 1, - .moduleName = "HDF_PLATFORM_SPI",//【必要 且与 HCS文件中里面的moduleName匹配】 + .moduleName = "HDF_PLATFORM_SPI",//【必要且与HCS文件中里面的moduleName匹配】 .Bind = HdfSpiDeviceBind, //见Bind参考 .Init = HdfSpiDeviceInit, //见Init参考 .Release = HdfSpiDeviceRelease, //见Release参考 @@ -78,8 +84,12 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 HDF_INIT(g_hdfSpiDevice); ``` -2. 完成驱动入口注册之后,在device_info.hcs文件中添加deviceNode信息,并在 spi_config.hcs中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层SpiCntlr成员的默认值或限制范围有密切关系。 - 本例只有一个SPI控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在spi_config文件中增加对应的器件属性。 +2. 完成驱动入口注册之后,在device_info.hcs文件中添加deviceNode信息,并在spi_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层SpiCntlr成员的默认值或限制范围有密切关系。 + + 本例只有一个SPI控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在spi_config文件中增加对应的器件属性。 + - device_info.hcs配置参考 @@ -90,7 +100,7 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 platform :: host { hostName = "platform_host"; priority = 50; - device_spi :: device { //为每一个 SPI 控制器配置一个HDF设备节点 + device_spi :: device { //为每一个SPI控制器配置一个HDF设备节点 device0 :: deviceNode { policy = 1; priority = 60; @@ -103,9 +113,9 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 policy = 1; priority = 60; permission = 0644; - moduleName = "HDF_PLATFORM_SPI"; // 【必要】用于指定驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 - serviceName = "HDF_PLATFORM_SPI_1"; // 【必要且唯一】驱动对外发布服务的名称 - deviceMatchAttr = "hisilicon_hi35xx_spi_1"; // 需要与设备hcs文件中的match_attr匹配 + moduleName = "HDF_PLATFORM_SPI"; // 【必要】用于指定驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 + serviceName = "HDF_PLATFORM_SPI_1"; // 【必要且唯一】驱动对外发布服务的名称。 + deviceMatchAttr = "hisilicon_hi35xx_spi_1"; // 需要与设备hcs文件中的match_attr匹配。 } ... } @@ -114,28 +124,28 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 } ``` - - spi_config.hcs 配置参考 + - spi_config.hcs配置参考 ``` root { platform { - spi_config {// 每一个SPI控制器配置私有数据 - template spi_controller {// 模板公共参数, 继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省 + spi_config { // 每一个SPI控制器配置私有数据 + template spi_controller { // 模板公共参数,继承该模板的节点如果使用模板中的默认值,则节点字段可以缺省。 serviceName = ""; match_attr = ""; - transferMode = 0; // 数据传输模式:中断传输(0),流控传输(1),DMA传输(2) - busNum = 0; // 总线号 + transferMode = 0; // 数据传输模式:中断传输(0)、流控传输(1)、DMA传输(2) + busNum = 0; // 总线号 clkRate = 100000000; - bitsPerWord = 8; // 传输位宽 - mode = 19; // SPI 数据的输入输出模式 - maxSpeedHz = 0; // 最大时钟频率 - minSpeedHz = 0; // 最小时钟频率 - speed = 2000000; // 当前消息传输速度 - fifoSize = 256; // FIFO大小 - numCs = 1; // 片选号 - regBase = 0x120c0000; // 地址映射需要 - irqNum = 100; // 中断号 + bitsPerWord = 8; // 传输位宽 + mode = 19; // SPI 数据的输入输出模式 + maxSpeedHz = 0; // 最大时钟频率 + minSpeedHz = 0; // 最小时钟频率 + speed = 2000000; // 当前消息传输速度 + fifoSize = 256; // FIFO大小 + numCs = 1; // 片选号 + regBase = 0x120c0000; // 地址映射需要 + irqNum = 100; // 中断号 REG_CRG_SPI = 0x120100e4; // CRG_REG_BASE(0x12010000) + 0x0e4 CRG_SPI_CKEN = 0; CRG_SPI_RST = 0; @@ -144,9 +154,9 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 MISC_CTRL_SPI_CS_SHIFT = 0; } controller_0x120c0000 :: spi_controller { - busNum = 0; // 【必要】总线号 - CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk - CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset + busNum = 0; // 【必要】总线号 + CRG_SPI_CKEN = 0x10000; // (0x1 << 16) 0:close clk, 1:open clk + CRG_SPI_RST = 0x1; // (0x1 << 0) 0:cancel reset, 1:reset match_attr = "hisilicon_hi35xx_spi_0";// 【必要】需要和device_info.hcs中的deviceMatchAttr值一致 } controller_0x120c1000 :: spi_controller { @@ -158,16 +168,17 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 irqNum = 101; // 【必要】中断号 } ... - // 【可选】可新增,但需要在device_info.hcs添加对应的节点 + // 【可选】可新增,但需要在device_info.hcs添加对应的节点。 } } } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层SpiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SpiCntlr成员SpiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成属性文件配置之后,下一步就是以核心层SpiCntlr对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化SpiCntlr成员SpiCntlrMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且spi_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号、总线号等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且spi_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号、总线号等。 ``` @@ -197,7 +208,7 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 uint8_t transferMode; }; - // SpiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // SpiCntlr是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct SpiCntlr { struct IDeviceIoService service; struct HdfDeviceObject *device; @@ -249,14 +260,14 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct SpiCntlr *SpiCntlrCreate(struct HdfDeviceObject *device) { - struct SpiCntlr *cntlr = NULL; // 创建核心层SpiCntlr对象 + struct SpiCntlr *cntlr = NULL; // 创建核心层SpiCntlr对象 ... cntlr = (struct SpiCntlr *)OsalMemCalloc(sizeof(*cntlr));// 分配内存 ... - cntlr->device = device; // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 - device->service = &(cntlr->service);// 使HdfDeviceObject与SpiCntlr可以相互转化的前提 - (void)OsalMutexInit(&cntlr->lock); // 锁初始化 - DListHeadInit(&cntlr->list); // 添加对应的节点 + cntlr->device = device; // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 + device->service = &(cntlr->service); // 使HdfDeviceObject与SpiCntlr可以相互转化的前提 + (void)OsalMutexInit(&cntlr->lock); // 锁初始化 + DListHeadInit(&cntlr->list); // 添加对应的节点 cntlr->priv = NULL; return cntlr; } @@ -270,7 +281,7 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 返回值: - HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS 定义)。 + HDF_STATUS相关状态(下表为部分展示,如需使用其他状态,可见//drivers/framework/include/utils/hdf_base.h中HDF_STATUS定义)。 **表2** HDF_STATUS返回值描述 @@ -294,10 +305,10 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 int32_t ret; struct SpiCntlr *cntlr = NULL; ... - cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数 + cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数。 // return (device == NULL) ? NULL : (struct SpiCntlr *)device->service; ... - ret = Pl022Init(cntlr, device); // 【必要】实例化厂商自定义操作对象,示例见下 + ret = Pl022Init(cntlr, device); // 【必要】实例化厂商自定义操作对象,示例见下。 ... ret = Pl022Probe(cntlr->priv); ... @@ -311,11 +322,11 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 ... pl022 = (struct Pl022 *)OsalMemCalloc(sizeof(*pl022));// 申请内存 ... - ret = SpiGetBaseCfgFromHcs(pl022, device->property); // 初始化busNum, numCs, speed, fifoSize, clkRate,mode, bitsPerWord, transferMode参数值 + ret = SpiGetBaseCfgFromHcs(pl022, device->property); // 初始化busNum、numCs、speed、fifoSize、clkRate、mode、bitsPerWord、transferMode参数值。 ... - ret = SpiGetRegCfgFromHcs(pl022, device->property); // 初始化regBase, phyBase, irqNum, regCrg, clkEnBit,clkRstBit, regMiscCtrl, regMiscCtrl, miscCtrlCs,miscCtrlCsShift参数值 + ret = SpiGetRegCfgFromHcs(pl022, device->property); // 初始化regBase、phyBase、irqNum、regCrg、clkEnBit、clkRstBit、regMiscCtrl、regMiscCtrl、 miscCtrlCs、miscCtrlCsShift参数值。 ... - // 计算最大,最小速度对应的频率 + // 计算最大、最小速度对应的频率。 pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN); pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX); DListHeadInit(&pl022->deviceList); // 初始化DList链表 @@ -344,7 +355,10 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 函数说明: - 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。所有强制转换获取相应对象的操作**前提**是在Init函数中具备对应赋值的操作。 + 释放内存和删除控制器,该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 ``` @@ -352,8 +366,8 @@ SPI模块适配HDF框架的三个环节是配置属性文件,实例化驱动 { struct SpiCntlr *cntlr = NULL; ... - cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数 - // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service; + cntlr = SpiCntlrFromDevice(device); // 这里有HdfDeviceObject到SpiCntlr的强制转化,通过service成员,赋值见Bind函数 + // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service; ... if (cntlr->priv != NULL) { Pl022Remove((struct Pl022 *)cntlr->priv); // 这里有SpiCntlr到Pl022的强制转化 diff --git a/zh-cn/device-dev/driver/driver-platform-uart-develop.md b/zh-cn/device-dev/driver/driver-platform-uart-develop.md index 0a2abe456278938fe723ef09076f43f6045b9e87..29495e8eec5394b09e1d0a9446575abd59a097e3 100755 --- a/zh-cn/device-dev/driver/driver-platform-uart-develop.md +++ b/zh-cn/device-dev/driver/driver-platform-uart-develop.md @@ -3,7 +3,7 @@ ## 概述 -UART指通用异步收发传输器(Universal Asynchronous Receiver/Transmitter)。在HDF框架中,UART的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 +在HDF框架中,UART(Universal Asynchronous Receiver/Transmitter,通用异步收发传输器)的接口适配模式采用独立服务模式。在这种模式下,每一个设备对象会独立发布一个设备服务来处理外部访问,设备管理器收到API的访问请求之后,通过提取该请求的参数,达到调用实际设备对象的相应内部方法的目的。独立服务模式可以直接借助HDFDeviceManager的服务管理能力,但需要为每个设备单独配置设备节点,增加内存占用。 **图1** UART独立服务模式结构图 @@ -34,37 +34,38 @@ struct UartHostMethod { | 函数 | 入参 | 出参 | 返回值 | 功能 | | -------- | -------- | -------- | -------- | -------- | -| Init | host: 结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 初始化Uart设备 | -| Deinit | host: 结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 去初始化Uart设备 | -| Read | host: 结构体指针,核心层UART控制器
size:uint32_t,数据大小 | data: uint8_t指针,传出的数据 | HDF_STATUS相关状态 | 接收数据RX | -| Write | host: 结构体指针,核心层UART控制器
data:uint8_t指针,传入数据
size:uint32_t,数据大小 | 无 | HDF_STATUS相关状态 | 发送数据TX | -| SetBaud | host: 结构体指针,核心层UART控制器
baudRate: uint32_t指针,波特率传入值 | 无 | HDF_STATUS相关状态 | 设置波特率 | -| GetBaud | host: 结构体指针,核心层UART控制器 | baudRate: uint32_t指针,传出的波特率 | HDF_STATUS相关状态 | 获取当前设置的波特率 | -| GetAttribute | host: 结构体指针,核心层UART控制器 | attribute: 结构体指针,传出的属性值(见uart_if.h中UartAttribute定义) | HDF_STATUS相关状态 | 获取设备uart相关属性 | -| SetAttribute | host: 结构体指针,核心层UART控制器
attribute: 结构体指针,属性传入值 | 无 | HDF_STATUS相关状态 | 设置设备UART相关属性 | -| SetTransMode | host: 结构体指针,核心层UART控制器
mode: 枚举值(见uart_if.h中UartTransMode定义),传输模式 | 无 | HDF_STATUS相关状态 | 设置传输模式 | -| PollEvent | host: 结构体指针,核心层UART控制器
filep: void 指针file
table: void 指针poll_table | 无 | HDF_STATUS相关状态 | poll机制 | +| Init | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 初始化Uart设备 | +| Deinit | host:结构体指针,核心层UART控制器 | 无 | HDF_STATUS相关状态 | 去初始化Uart设备 | +| Read | host:结构体指针,核心层UART控制器
size:uint32_t,数据大小 | data:uint8_t指针,传出的数据 | HDF_STATUS相关状态 | 接收数据RX | +| Write | host:结构体指针,核心层UART控制器
data:uint8_t指针,传入数据
size:uint32_t,数据大小 | 无 | HDF_STATUS相关状态 | 发送数据TX | +| SetBaud | host:结构体指针,核心层UART控制器
baudRate:uint32_t指针,波特率传入值 | 无 | HDF_STATUS相关状态 | 设置波特率 | +| GetBaud | host:结构体指针,核心层UART控制器 | baudRate:uint32_t指针,传出的波特率 | HDF_STATUS相关状态 | 获取当前设置的波特率 | +| GetAttribute | host:结构体指针,核心层UART控制器 | attribute:结构体指针,传出的属性值(见uart_if.h中UartAttribute定义) | HDF_STATUS相关状态 | 获取设备uart相关属性 | +| SetAttribute | host:结构体指针,核心层UART控制器
attribute:结构体指针,属性传入值 | 无 | HDF_STATUS相关状态 | 设置设备UART相关属性 | +| SetTransMode | host:结构体指针,核心层UART控制器
mode:枚举值(见uart_if.h中UartTransMode定义),传输模式 | 无 | HDF_STATUS相关状态 | 设置传输模式 | +| PollEvent | host:结构体指针,核心层UART控制器
filep:void指针file
table:void指针poll_table | 无 | HDF_STATUS相关状态 | poll机制 | ## 开发步骤 -UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动入口,以及实例化核心层接口函数。 +UART模块适配HDF框架的三个必选环节是实例化驱动入口,配置属性文件,以及实例化核心层接口函数。 -1. **实例化驱动入口:** +1. 实例化驱动入口 - 实例化HdfDriverEntry结构体成员。 - 调用HDF_INIT将HdfDriverEntry实例化对象注册到HDF框架中。 -2. **配置属性文件:** +2. 配置属性文件 - 在device_info.hcs文件中添加deviceNode描述。 - 【可选】添加uart_config.hcs器件属性文件。 -3. **实例化UART控制器对象:** +3. 实例化UART控制器对象 - 初始化UartHost成员。 - 实例化UartHost成员UartHostMethod。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 实例化UartHost成员UartHostMethod,其定义和成员说明见[接口说明](#接口说明)。 -4. **驱动调试:** +4. 驱动调试 + 【可选】针对新增驱动程序,建议验证驱动基本功能,例如UART控制状态,中断响应情况等。 @@ -72,10 +73,15 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 下方将以uart_hi35xx.c为示例,展示需要厂商提供哪些内容来完整实现设备功能。 -1. 驱动开发首先需要实例化驱动入口,驱动入口必须为HdfDriverEntry(在 hdf_device_desc.h 中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 +1. 驱动开发首先需要实例化驱动入口。 + + 驱动入口必须为HdfDriverEntry(在hdf_device_desc.h中定义)类型的全局变量,且moduleName要和device_info.hcs中保持一致。 + + HDF框架会将所有加载的驱动的HdfDriverEntry对象首地址汇总,形成一个类似数组的段地址空间,方便上层调用。 + 一般在加载驱动时HDF会先调用Bind函数,再调用Init函数加载该驱动。当Init调用异常时,HDF框架会调用Release释放驱动资源并退出。 - UART驱动入口参考: + UART驱动入口参考: ``` struct HdfDriverEntry g_hdfUartDevice = { @@ -89,8 +95,12 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 HDF_INIT(g_hdfUartDevice); ``` -2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在 uart_config.hcs 中配置器件属性。deviceNode信息与驱动入口注册相关,器件属性值与核心层UartHost成员的默认值或限制范围有密切关系。 - 本例只有一个UART控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在uart_config文件中增加对应的器件属性。 +2. 完成驱动入口注册之后,下一步请在device_info.hcs文件中添加deviceNode信息,并在uart_config.hcs中配置器件属性。 + + deviceNode信息与驱动入口注册相关,器件属性值与核心层UartHost成员的默认值或限制范围有密切关系。 + + 本例只有一个UART控制器,如有多个器件信息,则需要在device_info文件增加deviceNode信息,以及在uart_config文件中增加对应的器件属性。 + - device_info.hcs 配置参考: @@ -103,12 +113,12 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 priority = 50; device_uart :: device { device0 :: deviceNode { - policy = 1; // 驱动服务发布的策略,policy大于等于1(用户态可见为2,仅内核态可见为1); - priority = 40; // 驱动启动优先级 - permission = 0644; // 驱动创建设备节点权限 - moduleName = "HDF_PLATFORM_UART"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致 - serviceName = "HDF_PLATFORM_UART_0";// 驱动对外发布服务的名称,必须唯一,必须要按照HDF_PLATFORM_UART_X的格式,X为UART控制器编号 - deviceMatchAttr = "hisilicon_hi35xx_uart_0";// 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值一致 + policy = 1; // 驱动服务发布的策略,policy大于等于1(用户态可见为2,仅内核态可见为1)。 + priority = 40; // 驱动启动优先级 + permission = 0644; // 驱动创建设备节点权限 + moduleName = "HDF_PLATFORM_UART"; // 驱动名称,该字段的值必须和驱动入口结构的moduleName值一致。 + serviceName = "HDF_PLATFORM_UART_0"; // 驱动对外发布服务的名称,必须唯一,必须要按照HDF_PLATFORM_UART_X的格式,X为UART控制器编号。 + deviceMatchAttr = "hisilicon_hi35xx_uart_0";// 驱动私有数据匹配的关键字,必须和驱动私有数据配置表中的match_attr值一致。 } device1 :: deviceNode { policy = 2; @@ -158,10 +168,11 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 } ``` -3. 完成驱动入口注册之后,最后一步就是以核心层UartHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化UartHost成员UartHostMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind,Init,Release)。 +3. 完成属性文件配置之后,下一步就是以核心层UartHost对象的初始化为核心,包括厂商自定义结构体(传递参数和数据),实例化UartHost成员UartHostMethod(让用户可以通过接口来调用驱动底层函数),实现HdfDriverEntry成员函数(Bind、Init、Release)。 + - 自定义结构体参考 - 从驱动的角度看,自定义结构体是参数和数据的载体,而且uart_config.hcs文件中的数值会被HDF读入通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 + 从驱动的角度看,自定义结构体是参数和数据的载体,而且uart_config.hcs文件中的数值会被HDF读入并通过DeviceResourceIface来初始化结构体成员,一些重要数值也会传递给核心层对象,例如设备号等。 ``` @@ -170,7 +181,7 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 unsigned long physBase; // 物理地址 uint32_t irqNum; // 中断号 uint32_t defaultBaudrate;// 默认波特率 - uint32_t flags; // 标志信号,下面三个宏与之相关 + uint32_t flags; // 标志信号,下面三个宏与之相关。 #define PL011_FLG_IRQ_REQUESTED (1 << 0) #define PL011_FLG_DMA_RX_REQUESTED (1 << 1) #define PL011_FLG_DMA_TX_REQUESTED (1 << 2) @@ -180,8 +191,8 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct UartDriverData { // 数据传输相关的结构体 uint32_t num; uint32_t baudrate; // 波特率(可设置) - struct UartAttribute attr; // 数据位、停止位等传输属性相关 - struct UartTransfer *rxTransfer; // 缓冲区相关,可理解为FIFO结构 + struct UartAttribute attr; // 数据位、停止位等传输属性相关。 + struct UartTransfer *rxTransfer; // 缓冲区相关,可理解为FIFO结构。 wait_queue_head_t wait; // 条件变量相关的排队等待信号 int32_t count; // 数据数量 int32_t state; // UART控制器状态 @@ -193,21 +204,22 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 #define UART_FLG_DMA_RX (1 << 0) #define UART_FLG_DMA_TX (1 << 1) #define UART_FLG_RD_BLOCK (1 << 2) - RecvNotify recv; // 函数指针类型,指向串口数据接收函数 - struct UartOps *ops; // 自定义函数指针结构体,详情见device/hisilicon/drivers/uart/uart_pl011.c - void *private; // 一般用来存储UartPl011Port首地址,方便调用 + RecvNotify recv; // 函数指针类型,指向串口数据接收函数。 + struct UartOps *ops; // 自定义函数指针结构体,详情见device/hisilicon/drivers/uart/uart_pl011.c。 + void *private; // 一般用来存储UartPl011Port首地址,方便调用。 }; - // UartHost是核心层控制器结构体,其中的成员在Init函数中会被赋值 + // UartHost是核心层控制器结构体,其中的成员在Init函数中会被赋值。 struct UartHost { struct IDeviceIoService service; struct HdfDeviceObject *device; uint32_t num; OsalAtomic atom; - void *priv; // 一般存储厂商自定义结构体首地址,方便后者被调用 - struct UartHostMethod *method; // 核心层钩子函数,厂商需要实现其成员函数功能并实例化 + void *priv; // 一般存储厂商自定义结构体首地址,方便后者被调用。 + struct UartHostMethod *method; // 核心层钩子函数,厂商需要实现其成员函数功能并实例化。 }; ``` + - UartHost成员回调函数结构体UartHostMethod的实例化,其他成员在Bind函数中初始化。 @@ -267,10 +279,10 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 ... host = (struct UartHost *)OsalMemCalloc(sizeof(*host));//分配内存 ... - host->device = device; // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 - device->service = &(host->service); // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 - host->device->service->Dispatch = UartIoDispatch;// 为service成员的Dispatch方法赋值 - OsalAtomicSet(&host->atom, 0); // 原子量初始化或者原子量设置 + host->device = device; // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 + device->service = &(host->service); // 【必要】使HdfDeviceObject与UartHost可以相互转化的前提 + host->device->service->Dispatch = UartIoDispatch; // 为service成员的Dispatch方法赋值 + OsalAtomicSet(&host->atom, 0); // 原子量初始化或者原子量设置 host->priv = NULL; host->method = NULL; return host; @@ -299,27 +311,27 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct UartHost *host = NULL; HDF_LOGI("%s: entry", __func__); ... - host = UartHostFromDevice(device);// 通过service成员后强制转为UartHost,赋值是在Bind函数中 + host = UartHostFromDevice(device);// 通过service成员后强制转为UartHost,赋值是在Bind函数中。 ... - ret = Hi35xxAttach(host, device); // 完成UartHost对象的初始化,见下 + ret = Hi35xxAttach(host, device); // 完成UartHost对象的初始化,见下。 ... - host->method = &g_uartHostMethod; // UartHostMethod的实例化对象的挂载 + host->method = &g_uartHostMethod; // UartHostMethod的实例化对象的挂载。 return ret; } - // 完成 UartHost 对象的初始化 + // 完成UartHost对象的初始化。 static int32_t Hi35xxAttach(struct UartHost *host, struct HdfDeviceObject *device) { int32_t ret; - // udd和port对象是厂商自定义的结构体对象,可根据需要实现相关功能 + // udd和port对象是厂商自定义的结构体对象,可根据需要实现相关功能。 struct UartDriverData *udd = NULL; struct UartPl011Port *port = NULL; ... - // 【必要】步骤【1】~【7】主要实现对 udd 对象的实例化赋值,然后赋值给核心层UartHost对象 + // 【必要】步骤【1】~【7】主要实现对udd对象的实例化赋值,然后赋值给核心层UartHost对象。 udd = (struct UartDriverData *)OsalMemCalloc(sizeof(*udd));//【1】 ... port = (struct UartPl011Port *)OsalMemCalloc(sizeof(struct UartPl011Port));//【2】 ... - udd->ops = Pl011GetOps(); // 【3】设备开启、关闭、属性设置、发送操作等函数挂载 + udd->ops = Pl011GetOps(); // 【3】设备开启、关闭、属性设置、发送操作等函数挂载。 udd->recv = PL011UartRecvNotify;// 【4】数据接收通知函数(条件锁机制)挂载 udd->count = 0; // 【5】 port->udd = udd; // 【6】使UartPl011Port与UartDriverData可以相互转化的前提 @@ -330,7 +342,7 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 host->priv = udd; // 【必要】使UartHost与UartDriverData可以相互转化的前提 host->num = udd->num; // 【必要】UART设备号 - UartAddDev(host); // 【必要】核心层uart_dev.c 中的函数,作用:注册一个字符设备节点到vfs,这样从用户态可以通过这个虚拟文件节点访问UART + UartAddDev(host); // 【必要】核心层uart_dev.c中的函数,作用:注册一个字符设备节点到vfs,这样从用户态可以通过这个虚拟文件节点访问UART。 return HDF_SUCCESS; } @@ -340,7 +352,7 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct UartDriverData *udd = port->udd; struct DeviceResourceIface *iface = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); ... - // 通过请求参数提取相应的值,并赋值给厂商自定义的结构体 + // 通过请求参数提取相应的值,并赋值给厂商自定义的结构体。 if (iface->GetUint32(node, "num", &udd->num, 0) != HDF_SUCCESS) { HDF_LOGE("%s: read busNum fail", __func__); return HDF_FAILURE; @@ -361,7 +373,10 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 函数说明: - 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 + 该函数需要在驱动入口结构体中赋值给Release接口,当HDF框架调用Init函数初始化驱动失败时,可以调用Release释放驱动资源,该函数中需包含释放内存和删除控制器等操作。 + + > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
+ > 所有强制转换获取相应对象的操作前提是在Init函数中具备对应赋值的操作。 ``` @@ -369,10 +384,10 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 { struct UartHost *host = NULL; ... - host = UartHostFromDevice(device);// 这里有HdfDeviceObject到UartHost的强制转化,通过service成员,赋值见Bind函数 + host = UartHostFromDevice(device);// 这里有HdfDeviceObject到UartHost的强制转化,通过service成员,赋值见Bind函数。 ... if (host->priv != NULL) { - Hi35xxDetach(host); // 厂商自定义的内存释放函数,见下 + Hi35xxDetach(host); // 厂商自定义的内存释放函数,见下。 } UartHostDestroy(host); // 调用核心层函数释放host } @@ -382,10 +397,10 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 struct UartDriverData *udd = NULL; struct UartPl011Port *port = NULL; ... - udd = host->priv; // 这里有UartHost到UartDriverData的转化 + udd = host->priv; // 这里有UartHost到UartDriverData的转化 ... - UartRemoveDev(host);// VFS注销 - port = udd->private;// 这里有UartDriverData到UartPl011Port的转化 + UartRemoveDev(host); // VFS注销 + port = udd->private; // 这里有UartDriverData到UartPl011Port的转化 if (port != NULL) { if (port->physBase != 0) { OsalIoUnmap((void *)port->physBase);// 地址反映射 @@ -393,7 +408,7 @@ UART模块适配HDF框架的三个环节是配置属性文件,实例化驱动 OsalMemFree(port); udd->private = NULL; } - OsalMemFree(udd);// 释放UartDriverData + OsalMemFree(udd); // 释放UartDriverData host->priv = NULL; } ``` diff --git "a/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\346\241\206\346\236\266.png" "b/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\346\241\206\346\236\266.png" new file mode 100644 index 0000000000000000000000000000000000000000..2369adacb1beb70cf7aabbfd9705098d9c18a006 Binary files /dev/null and "b/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\346\241\206\346\236\266.png" differ diff --git "a/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\350\277\220\350\241\214\345\233\276.png" "b/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\350\277\220\350\241\214\345\233\276.png" new file mode 100644 index 0000000000000000000000000000000000000000..336a633e2cb38fc74793c930e95d80aec17c9b9e Binary files /dev/null and "b/zh-cn/device-dev/driver/figures/\346\211\213\345\212\277\350\257\206\345\210\253\351\251\261\345\212\250\350\277\220\350\241\214\345\233\276.png" differ diff --git a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md index a5ef1e1b97839ab25451bd3080c0c91342bd026e..3f22c8ca8805c838933f2a66cead333a6ae34e04 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md +++ b/zh-cn/device-dev/kernel/kernel-mini-basic-ipc-event.md @@ -52,6 +52,7 @@ typedef struct tagEvent { **事件销毁**:销毁指定的事件控制块。 **图1** 轻量系统事件运作原理图 + ![zh-cn_image_0000001200771972](figures/zh-cn_image_0000001200771972.png) diff --git a/zh-cn/device-dev/kernel/kernel-mini-extend-dynamic-loading.md b/zh-cn/device-dev/kernel/kernel-mini-extend-dynamic-loading.md index 22a9c5443e3a6bff91be15c204c33d583e757aba..b54322512502bdae48997ccbcc8f656db40eb0cb 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-extend-dynamic-loading.md +++ b/zh-cn/device-dev/kernel/kernel-mini-extend-dynamic-loading.md @@ -63,6 +63,7 @@ Program Headers: ``` **图3** ELF文件的加载过程 + ![zh-cn_image_0000001245251887](figures/zh-cn_image_0000001245251887.png) diff --git a/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md b/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md index d3efbaeff1c9c45b5d0390bf448070ca47790cd2..daa581a14689a449059bfe53265b7eb3b194f1d0 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md +++ b/zh-cn/device-dev/kernel/kernel-mini-memory-exception.md @@ -15,6 +15,7 @@ OpenHarmony LiteOS-M提供异常接管调测手段,帮助开发者定位分析 堆栈分析原理如下图所示,实际堆栈信息根据不同CPU架构有所差异,此处仅做示意。 **图1** 堆栈分析原理示意图 + ![zh-cn_image_0000001132936268](figures/zh-cn_image_0000001132936268.png) 图中不同颜色的寄存器表示不同的函数。可以看到函数调用过程中,寄存器的保存。通过FP寄存器,栈回溯到异常函数的父函数,继续按照规律对栈进行解析,推出函数调用关系,方便用户定位问题。 diff --git a/zh-cn/device-dev/kernel/kernel-mini-overview.md b/zh-cn/device-dev/kernel/kernel-mini-overview.md index 7c27f39c9230a8443d7ff1d0d4c2000f76e047af..29fcfdf88c8ee2cfe78d2a30ed7fe17837fb6bf0 100644 --- a/zh-cn/device-dev/kernel/kernel-mini-overview.md +++ b/zh-cn/device-dev/kernel/kernel-mini-overview.md @@ -32,4 +32,5 @@ LiteOS-M已经支持ARM Cortex-M3、ARM Cortex-M4、ARM Cortex-M7、ARM Cortex-M 在开发板配置文件target_config.h配置系统时钟、每秒Tick数,可以对任务、内存、IPC、异常处理模块进行裁剪配置。系统启动时,根据配置进行指定模块的初始化。内核启动流程包含外设初始化、系统时钟配置、内核初始化、操作系统启动等,详见下图。 **图2** 内核启动流程 + ![zh-cn_image_0000001160338832](figures/zh-cn_image_0000001160338832.png) diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-memory-physical.md b/zh-cn/device-dev/kernel/kernel-small-basic-memory-physical.md index 55792a35546745f8b8fd06e2d145c4684e49ae71..54ce84098a2f9e5ebb6d21b750f241a87a7b4984 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-memory-physical.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-memory-physical.md @@ -20,6 +20,7 @@ 系统申请12KiB内存,即3个页帧时,9个内存块组中索引为3的链表挂着一块大小为8个页帧的内存块满足要求,分配出12KiB内存后还剩余20KiB内存,即5个页帧,将5个页帧分成2的幂次方之和,即4跟1,尝试查找伙伴进行合并。4个页帧的内存块没有伙伴则直接插到索引为2的链表上,继续查找1个页帧的内存块是否有伙伴,索引为0的链表上此时有1个,如果两个内存块地址连续则进行合并,并将内存块挂到索引为1的链表上,否则不做处理。 **图2** 内存申请示意图 + ![zh-cn_image_0000001189778871](figures/zh-cn_image_0000001189778871.png) - 释放内存 diff --git a/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md b/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md index a1d647c2a1fc841cd3242a0b760ea43629c17725..56737c618168cddd11a50b91dae498ecde549733 100644 --- a/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md +++ b/zh-cn/device-dev/kernel/kernel-small-basic-trans-event.md @@ -64,6 +64,7 @@ typedef struct tagEvent { **事件销毁**:销毁指定的事件控制块。 **图1** 小型系统事件运作原理图 + ![zh-cn_image_0000001180952545](figures/zh-cn_image_0000001180952545.png) diff --git a/zh-cn/device-dev/kernel/kernel-small-debug-trace-other-faqs.md b/zh-cn/device-dev/kernel/kernel-small-debug-trace-other-faqs.md index 525b873132507c485fdaa3245ee2cd3031692e61..4bfca492524d332ef0b0795ae04871a6f7f56ed1 100644 --- a/zh-cn/device-dev/kernel/kernel-small-debug-trace-other-faqs.md +++ b/zh-cn/device-dev/kernel/kernel-small-debug-trace-other-faqs.md @@ -6,6 +6,7 @@ 系统异常被挂起后,会在串口看到一些关键寄存器的信息,如图1所示。可通过这些信息定位到异常所在函数和其调用栈关系,为原因分析提供第一手资料。 **图1** 异常信息 + ![zh-cn_image_0000001153823524](figures/zh-cn_image_0000001153823524.png) 上图中的异常信息主要解释4个标签: diff --git a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md index b02d14e5221fae86cf4479cfc784f746cd984d4e..65cc1ca22807e33a5829c2378e2b428ea2055e04 100644 --- a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md +++ b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md @@ -1172,12 +1172,12 @@ HiviewRegisterHilogProc(HilogProc_Impl); ``` { - "subsystem": "distributedschedule", + "subsystem": "systemabilitymgr", "components": [ { "component": "samgr_lite", "features": [ - "config_ohos_distributedschedule_samgr_lite_shared_task_size = 4096" + "config_ohos_systemabilitymgr_samgr_lite_shared_task_size = 4096" ] } ] diff --git a/zh-cn/device-dev/porting/porting-chip-board-component.md b/zh-cn/device-dev/porting/porting-chip-board-component.md index 555559cd0a9942496560fb9e811e236af7c82efb..285f3d3b146f43308fab18d4bb463ed637b42d66 100644 --- a/zh-cn/device-dev/porting/porting-chip-board-component.md +++ b/zh-cn/device-dev/porting/porting-chip-board-component.md @@ -16,7 +16,7 @@ > 本组件在板级系统移植中必须要使用,否则其他服务组件无法运行。 -**SAMGR使用说明,请参考:[SAMGR 使用指导](https://gitee.com/openharmony/distributedschedule_samgr_lite/blob/master/README_zh.md)** +**SAMGR使用说明,请参考:[SAMGR 使用指导](https://gitee.com/openharmony/systemabilitymgr_samgr_lite/blob/master/README_zh.md)** ## DFX diff --git a/zh-cn/device-dev/porting/porting-chip-prepare-process.md b/zh-cn/device-dev/porting/porting-chip-prepare-process.md index eee8899860e35df47baad80ef1697cf9d04b26f3..cb649cab19f41b0f72a23a2f9537e5422ed15c54 100644 --- a/zh-cn/device-dev/porting/porting-chip-prepare-process.md +++ b/zh-cn/device-dev/porting/porting-chip-prepare-process.md @@ -1,7 +1,7 @@ # 编译构建适配流程 -编译构建的详细介绍请见[编译构建子系统介绍](../subsystems/subsys-build-mini-lite.md)。新增三方芯片时,编译相关的适配流程如下: +编译构建的详细介绍请见[编译构建子系统介绍](../subsystems/subsys-build-all.md)。新增三方芯片时,编译相关的适配流程如下: ## 编译构建适配流程 diff --git a/zh-cn/device-dev/porting/porting-smallchip-kernel-linux.md b/zh-cn/device-dev/porting/porting-smallchip-kernel-linux.md index 87af95951ca85767253b2e7be0000cd010cb77e1..f2d0b59f8c4570e217cdd1a7cafa4aa82985fd37 100644 --- a/zh-cn/device-dev/porting/porting-smallchip-kernel-linux.md +++ b/zh-cn/device-dev/porting/porting-smallchip-kernel-linux.md @@ -61,7 +61,7 @@ Linux内核移植主要涉及基于linux内核基线合入三方芯片补丁后 基于上述流程,推荐按以下步骤完成验证: 1. 制作根文件系统镜像。 - 请参考[新建芯片解决方案和产品解决方案](../subsystems/subsys-build-mini-lite.md)生成根文件系统镜像rootfs.img。从上图可以看到启动过程与产品配置强相关,在制作rootfs.img过程中请完成如下四种配置: + 请参考[新建芯片解决方案和产品解决方案](../subsystems/subsys-build-all.md)生成根文件系统镜像rootfs.img。从上图可以看到启动过程与产品配置强相关,在制作rootfs.img过程中请完成如下四种配置: - 组件配置 产品组件配置文件vendor/{company}/{product}/config.json需配置启动恢复子系统(startup)的init_lite组件和内核子系统的linux_4_1_9组件。 diff --git a/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md b/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md index 1a5c4104231706bbf1e1d133e18ae82504cac47f..9a1463516ad1720c7e7d53a2e755ea40a6d8058a 100644 --- a/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md +++ b/zh-cn/device-dev/porting/porting-smallchip-prepare-building.md @@ -12,7 +12,7 @@ sudo apt-get install gcc-arm-linux-gnueabi ## 编译构建系统介绍 -编译构建流程、编译脚本编写、目录规则、独立编译单个组件、独立编译芯片解决方案等介绍请见[编译构建子系统介绍](../subsystems/subsys-build-mini-lite.md)。 +编译构建流程、编译脚本编写、目录规则、独立编译单个组件、独立编译芯片解决方案等介绍请见[编译构建子系统介绍](../subsystems/subsys-build-all.md)。 ## 新建芯片解决方案 diff --git a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md index 14751be9e570c1358310f745909f635a03532f7e..703676d6ba3b81acc09f5840bb32c230efe7e565 100644 --- a/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md +++ b/zh-cn/device-dev/porting/porting-stm32f407-on-minisystem-eth.md @@ -1081,13 +1081,13 @@ bool HilogProc_Impl(const HiLogContent *hilogContent, uint32_t len) HiviewRegisterHilogProc(HilogProc_Impl); ``` -### 分布式调度子系统适配 +### 系统服务管理子系统适配 -进行分布式调度子系统适配需要添加`samgr_lite`部件,直接在`config.json`配置即可。 +进行系统服务管理子系统适配需要添加`samgr_lite`部件,直接在`config.json`配置即可。 ``` { - "subsystem": "distributedschedule", + "subsystem": "systemabilitymgr", "components": [ { "component": "samgr_lite", @@ -1097,10 +1097,10 @@ HiviewRegisterHilogProc(HilogProc_Impl); } ``` -在轻量系统中,`samgr_lite`配置的共享任务栈大小默认为`2048`。在适配时可以在features中,通过`config_ohos_distributedschedule_samgr_lite_shared_task_size`重新设置共享任务栈大小。 +在轻量系统中,`samgr_lite`配置的共享任务栈大小默认为`2048`。在适配时可以在features中,通过`config_ohos_systemabilitymgr_samgr_lite_shared_task_size`重新设置共享任务栈大小。 ``` -"config_ohos_distributedschedule_samgr_lite_shared_task_size = 4096" +"config_ohos_systemabilitymgr_samgr_lite_shared_task_size = 4096" ``` ### 安全子系统适配 diff --git a/zh-cn/device-dev/porting/porting-w800-combo-demo.md b/zh-cn/device-dev/porting/porting-w800-combo-demo.md index 09a8cce377a411f1f67a1d6cc3abeda035e5596f..e9a7b107a690a6e962f9c844b9dc7cbe441fa181 100755 --- a/zh-cn/device-dev/porting/porting-w800-combo-demo.md +++ b/zh-cn/device-dev/porting/porting-w800-combo-demo.md @@ -636,7 +636,7 @@ HDF驱动框架提供了一套应用访问硬件的统一接口,可以简化 ``` { - "subsystem": "distributedschedule", + "subsystem": "systemabilitymgr", "components": [ { "component": "samgr_lite" diff --git a/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md b/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md index ceef078f3194ff55fc38d0d5e72c186fca77e2d2..765079d9e77c7662a60a411a3172570c2f2ad2f9 100644 --- a/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md +++ b/zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @@ -322,7 +322,7 @@ bash build/prebuilts_download.sh ## 安装编译工具 -想要详细了解OpenHarmony编译构建模块功能的开发者可参考[编译构建指南](../subsystems/subsys-build-mini-lite.md)。 +想要详细了解OpenHarmony编译构建模块功能的开发者可参考[编译构建指导](../subsystems/subsys-build-all.md)。 相关操作在Ubuntu环境下进行。 diff --git a/zh-cn/device-dev/quick-start/quickstart-lite-reference.md b/zh-cn/device-dev/quick-start/quickstart-lite-reference.md index 5252016ce20ad2ad8f7ef02798b665de73a46da1..513f7e8667a3133b4cf81d275b5a38749207beea 100644 --- a/zh-cn/device-dev/quick-start/quickstart-lite-reference.md +++ b/zh-cn/device-dev/quick-start/quickstart-lite-reference.md @@ -21,7 +21,7 @@ 编译所生成的文件都归档在out/{device_name}/目录下,结果镜像输出在out/{device_name}/packages/phone/images/ 目录下。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 其他模块化编译操作,可参见[编译构建指导](../subsystems/subsys-build-mini-lite.md)。 + > 其他模块化编译操作,可参见[编译构建指导](../subsystems/subsys-build-all.md)。 ## 配置代理 diff --git a/zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md b/zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md index e8a0a88b3abc09605eb43d1e10ba23528b05ede5..c6324c073c011fad12242d7992c57fa8f325b55f 100644 --- a/zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md +++ b/zh-cn/device-dev/quick-start/quickstart-standard-env-setup.md @@ -324,7 +324,7 @@ bash build/prebuilts_download.sh ## 安装编译工具 -hb是OpenHarmony的编译工具,可通过以下步骤在Ubuntu下进行安装。想要详细了解OpenHarmony编译构建模块功能的开发者可参考[编译构建指南](../subsystems/subsys-build-standard-large.md)。 +hb是OpenHarmony的编译工具,可通过以下步骤在Ubuntu下进行安装。想要详细了解OpenHarmony编译构建模块功能的开发者可参考[编译构建指导](../subsystems/subsys-build-all.md)。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** diff --git a/zh-cn/device-dev/quick-start/quickstart-standard-reference.md b/zh-cn/device-dev/quick-start/quickstart-standard-reference.md index 8908ded0e2efd7d108be727cb1a3201429fca944..513f7e8667a3133b4cf81d275b5a38749207beea 100644 --- a/zh-cn/device-dev/quick-start/quickstart-standard-reference.md +++ b/zh-cn/device-dev/quick-start/quickstart-standard-reference.md @@ -21,7 +21,7 @@ 编译所生成的文件都归档在out/{device_name}/目录下,结果镜像输出在out/{device_name}/packages/phone/images/ 目录下。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** - > 其他模块化编译操作,可参见[编译构建指南](../subsystems/subsys-build-standard-large.md)。 + > 其他模块化编译操作,可参见[编译构建指导](../subsystems/subsys-build-all.md)。 ## 配置代理 diff --git a/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md b/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md index 84a9d471c65afca1d228083706ac4d352a689826..668a797efccc85c7f98728f8bef7a6569a17589c 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md +++ b/zh-cn/device-dev/reference/hdi-apis/_audio_attribute.md @@ -13,17 +13,20 @@ ### Public 属性 - | Public 属性 | 描述 | +| Public 属性 | 描述 | | -------- | -------- | -| ( [GetFrameSize](#getframesize) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*size) | 获取音频帧(frame)的大小 [更多...](#getframesize) | -| ( [GetFrameCount](#getframecount) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*count) | 获取音频buffer中的音频帧数 [更多...](#getframecount) | -| ( [SetSampleAttributes](#setsampleattributes) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, const struct [AudioSampleAttributes](_audio_sample_attributes.md) \*attrs) | 设置音频采样的属性参数 [更多...](#setsampleattributes) | -| ( [GetSampleAttributes](#getsampleattributes) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, struct [AudioSampleAttributes](_audio_sample_attributes.md) \*attrs) | 获取音频采样的属性参数 [更多...](#getsampleattributes) | -| ( [GetCurrentChannelId](#getcurrentchannelid) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint32_t \*channelId) | 获取音频的数据通道ID [更多...](#getcurrentchannelid) | -| ( [SetExtraParams](#setextraparams) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, const char \*keyValueList) | 设置音频拓展参数 [更多...](#setextraparams) | -| ( [GetExtraParams](#getextraparams) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, char \*keyValueList) | 获取音频拓展参数 [更多...](#getextraparams) | -| ( [ReqMmapBuffer](#reqmmapbuffer) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, int32_t reqSize, struct [AudioMmapBufferDescripter](_audio_mmap_buffer_descripter.md) \*desc) | 请求mmap缓冲区 [更多...](#reqmmapbuffer) | -| ( [GetMmapPosition](#getmmapposition) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*frames, struct [AudioTimeStamp](_audio_time_stamp.md) \*time) | 获取当前mmap的读/写位置 [更多...](#getmmapposition) | +| ( [GetFrameSize](#getframesize) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*size) | 获取音频帧(frame)的大小 [更多...](#getframesize) | +| ( [GetFrameCount](#getframecount) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*count) | 获取音频buffer中的音频帧数 [更多...](#getframecount) | +| ( [SetSampleAttributes](#setsampleattributes) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, const struct [AudioSampleAttributes](_audio_sample_attributes.md) \*attrs) | 设置音频采样的属性参数 [更多...](#setsampleattributes) | +| ( [GetSampleAttributes](#getsampleattributes) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, struct [AudioSampleAttributes](_audio_sample_attributes.md) \*attrs) | 获取音频采样的属性参数 [更多...](#getsampleattributes) | +| ( [GetCurrentChannelId](#getcurrentchannelid) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint32_t \*channelId) | 获取音频的数据通道ID [更多...](#getcurrentchannelid) | +| ( [SetExtraParams](#setextraparams) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, const char \*keyValueList) | 设置音频拓展参数 [更多...](#setextraparams) | +| ( [GetExtraParams](#getextraparams) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, char \*keyValueList) | 获取音频拓展参数 [更多...](#getextraparams) | +| ( [ReqMmapBuffer](#reqmmapbuffer) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, int32_t reqSize, struct [AudioMmapBufferDescripter](_audio_mmap_buffer_descripter.md) \*desc) | 请求mmap缓冲区 [更多...](#reqmmapbuffer) | +| ( [GetMmapPosition](#getmmapposition) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*frames, struct [AudioTimeStamp](_audio_time_stamp.md) \*time) | 获取当前mmap的读/写位置 [更多...](#getmmapposition) | +| ( [AddAudioEffect](#addaudioeffect) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*effectid) |添加音频效果算法实例 [更多...](#addaudioeffect) | +| ( [RemoveAudioEffect](#removeaudioeffect) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t effectid) |移除音频效果算法实例 [更多...](#removeaudioeffect) | +| ( [GetFrameBufferSize](#getframebuffersize) )([AudioHandle](_audio.md#ga18675ddb073465fdeac33a897f675d79) handle, uint64_t \*effectid) |获取播放或录音的缓冲区大小 [更多...](#getframebuffersize) | ## **详细描述** @@ -46,7 +49,7 @@ AudioAttribute音频属性接口 ### GetCurrentChannelId - + ``` int32_t(* AudioAttribute::GetCurrentChannelId) (AudioHandle handle, uint32_t *channelId) ``` @@ -57,19 +60,19 @@ int32_t(* AudioAttribute::GetCurrentChannelId) (AudioHandle handle, uint32_t *ch **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| channelId | 获取的通道ID保存到channelId中 | +| handle | 待操作的音频句柄 | +| channelId | 获取的通道ID保存到channelId中 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetExtraParams - + ``` int32_t(* AudioAttribute::GetExtraParams) (AudioHandle handle, char *keyValueList) ``` @@ -80,10 +83,10 @@ int32_t(* AudioAttribute::GetExtraParams) (AudioHandle handle, char *keyValueLis **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | +| handle | 待操作的音频句柄 | +| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | **返回:** @@ -92,7 +95,7 @@ int32_t(* AudioAttribute::GetExtraParams) (AudioHandle handle, char *keyValueLis ### GetFrameCount - + ``` int32_t(* AudioAttribute::GetFrameCount) (AudioHandle handle, uint64_t *count) ``` @@ -103,19 +106,19 @@ int32_t(* AudioAttribute::GetFrameCount) (AudioHandle handle, uint64_t *count) **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| count | 一个音频buffer中包含的音频帧数,获取后保存到count中 | +| handle | 待操作的音频句柄 | +| count | 一个音频buffer中包含的音频帧数,获取后保存到count中 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetFrameSize - + ``` int32_t(* AudioAttribute::GetFrameSize) (AudioHandle handle, uint64_t *size) ``` @@ -128,19 +131,19 @@ int32_t(* AudioAttribute::GetFrameSize) (AudioHandle handle, uint64_t *size) **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| size | 获取的音频帧大小(字节数)保存到size中 | +| handle | 待操作的音频句柄 | +| size | 获取的音频帧大小(字节数)保存到size中 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetMmapPosition - + ``` int32_t(* AudioAttribute::GetMmapPosition) (AudioHandle handle, uint64_t *frames, struct AudioTimeStamp *time) ``` @@ -151,20 +154,20 @@ int32_t(* AudioAttribute::GetMmapPosition) (AudioHandle handle, uint64_t *frames **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| frames | 获取的音频帧计数保存到frames中 | -| time | 获取的关联时间戳保存到time中 | +| handle | 待操作的音频句柄 | +| frames | 获取的音频帧计数保存到frames中 | +| time | 获取的关联时间戳保存到time中 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### GetSampleAttributes - + ``` int32_t(* AudioAttribute::GetSampleAttributes) (AudioHandle handle, struct AudioSampleAttributes *attrs) ``` @@ -175,14 +178,14 @@ int32_t(* AudioAttribute::GetSampleAttributes) (AudioHandle handle, struct Audio **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| attrs | 获取的音频采样属性(例如采样频率、采样精度、通道)保存到attrs中 | +| handle | 待操作的音频句柄 | +| attrs | 获取的音频采样属性(例如采样频率、采样精度、通道)保存到attrs中 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** @@ -191,7 +194,7 @@ int32_t(* AudioAttribute::GetSampleAttributes) (AudioHandle handle, struct Audio ### ReqMmapBuffer - + ``` int32_t(* AudioAttribute::ReqMmapBuffer) (AudioHandle handle, int32_t reqSize, struct AudioMmapBufferDescripter *desc) ``` @@ -202,20 +205,20 @@ int32_t(* AudioAttribute::ReqMmapBuffer) (AudioHandle handle, int32_t reqSize, s **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| reqSize | 请求缓冲区的大小 | -| desc | 缓冲区描述符 | +| handle | 待操作的音频句柄 | +| reqSize | 请求缓冲区的大小 | +| desc | 缓冲区描述符 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetExtraParams - + ``` int32_t(* AudioAttribute::SetExtraParams) (AudioHandle handle, const char *keyValueList) ``` @@ -226,19 +229,19 @@ int32_t(* AudioAttribute::SetExtraParams) (AudioHandle handle, const char *keyVa **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | +| handle | 待操作的音频句柄 | +| keyValueList | 拓展参数键值对字符串列表,格式为key=value,多个键值对通过分号分割 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 ### SetSampleAttributes - + ``` int32_t(* AudioAttribute::SetSampleAttributes) (AudioHandle handle, const struct AudioSampleAttributes *attrs) ``` @@ -249,15 +252,84 @@ int32_t(* AudioAttribute::SetSampleAttributes) (AudioHandle handle, const struct **参数:** - | 名称 | 描述 | +| 名称 | 描述 | | -------- | -------- | -| handle | 待操作的音频句柄 | -| attrs | 待设置的音频采样属性,例如采样频率、采样精度、通道 | +| handle | 待操作的音频句柄 | +| attrs | 待设置的音频采样属性,例如采样频率、采样精度、通道 | **返回:** -成功返回值0,失败返回负值 +成功返回值0,失败返回负值。 **参见:** [GetSampleAttributes](#getsampleattributes) + + +### AddAudioEffect + + +``` +int32_t (* AudioAttribute::AddAudioEffect)(AudioHandle handle, uint64_t effectid) +``` + +**描述:** + +添加音频效果算法实例。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| handle | 待操作的音频句柄 | +| effectid | 待添加的音频效果算法实例ID | + +**返回:** + +成功返回值0,失败返回负值。 + + +### RemoveAudioEffect + + +``` +int32_t (* AudioAttribute::RemoveAudioEffect)(AudioHandle handle, uint64_t effectid) +``` + +**描述:** + +移除音频效果算法实例。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| handle | 待操作的音频句柄 | +| effectid | 待移除的音频效果算法实例ID | + +**返回:** + +成功返回值0,失败返回负值。 + + +### GetFrameBufferSize + + +``` +int32_t (* AudioAttribute::GetFrameBufferSize)(AudioHandle handle, uint64_t *bufferSize) +``` + +**描述:** + +获取播放或录音的缓冲区大小。 + +**参数:** + +| 名称 | 描述 | +| -------- | -------- | +| handle | 待操作的音频句柄 | +| bufferSize | 获取的缓冲区大小保存到bufferSize中 | + +**返回:** + +成功返回值0,失败返回负值。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md index 58ab8b158a18cc045e658f398061460f0ef07b0b..2f3d3e0c4394801375698db6f2393d5d85de169b 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_controller.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_controller.md @@ -61,7 +61,7 @@ int32_t(* InputController::GetChipInfo) (uint32_t devIndex, char *chipInfo, uint INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetChipName @@ -87,7 +87,7 @@ int32_t(* InputController::GetChipName) (uint32_t devIndex, char *chipName, uint INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetDeviceType @@ -112,7 +112,7 @@ int32_t(* InputController::GetDeviceType) (uint32_t devIndex, uint32_t *deviceTy INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetPowerStatus @@ -139,7 +139,7 @@ int32_t(* InputController::GetPowerStatus) (uint32_t devIndex, uint32_t *status) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetVendorName @@ -165,7 +165,7 @@ int32_t(* InputController::GetVendorName) (uint32_t devIndex, char *vendorName, Returns INPUT_SUCCESS 表示执行成功。 -Returns 其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +Returns 其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### RunCapacitanceTest @@ -194,7 +194,7 @@ int32_t(* InputController::RunCapacitanceTest) (uint32_t devIndex, uint32_t test INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### RunExtraCommand @@ -219,7 +219,7 @@ int32_t(* InputController::RunExtraCommand) (uint32_t devIndex, InputExtraCmd *c INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### SetGestureMode @@ -246,7 +246,7 @@ int32_t(* InputController::SetGestureMode) (uint32_t devIndex, uint32_t gestureM INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### SetPowerStatus @@ -273,4 +273,4 @@ int32_t(* InputController::SetPowerStatus) (uint32_t devIndex, uint32_t status) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md index ac0611a28958d35fe31156a134270a7be2c0ba03..ece5fbf1c79dcc6b3a366c3378c379682389b924 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_manager.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_manager.md @@ -53,7 +53,7 @@ Input服务关闭对应设备的设备文件。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetInputDevice @@ -78,7 +78,7 @@ Input服务获取对应ID的设备信息。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### GetInputDeviceList @@ -97,14 +97,14 @@ Input服务获取所有Input设备列表的设备信息。 | 名称 | 描述 | | -------- | -------- | | devNum | 输出参数,当前已经注册过的所有Input设备的总数。 | -| devInfo | 输出参数,Input设备列表所对应的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 | +| devList | 输出参数,Input设备列表所对应的设备信息,具体参考[InputDeviceInfo](_device_info.md)。 | | size | 输入参数,即指定deviceList数组对应的元素个数。| 返回: INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### OpenInputDevice @@ -128,7 +128,7 @@ Input服务打开对应设备的设备文件。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### ScanInputDevice @@ -153,4 +153,4 @@ Input服务用于扫描所有在线设备。 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md index fb4feb386c944bed951b37290c8711af10e4d28f..a478718b007d1bed0c2646471ec92f383919faa5 100644 --- a/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md +++ b/zh-cn/device-dev/reference/hdi-apis/_input_reporter.md @@ -54,7 +54,7 @@ Input服务通过此接口注册回调函数到hdi中,所有Input设备由此 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### RegisterReportCallback @@ -81,7 +81,7 @@ Input服务通过此接口注册数据回调函数到hdi中,hdi通过此回调 INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### UnregisterHotPlugCallback @@ -99,7 +99,7 @@ int32_t(* InputReporter::UnregisterHotPlugCallback) (void) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 ### UnregisterReportCallback @@ -123,4 +123,4 @@ int32_t(* InputReporter::UnregisterReportCallback) (uint32_t devIndex) INPUT_SUCCESS 表示执行成功。 -其他值表示执行失败,具体错误码查看[RetSatus](_input.md#retstatus)。 +其他值表示执行失败,具体错误码查看[RetStatus](_input.md#retstatus)。 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md index 22c8c7f5fe91b780bcfb6f4624f503ce73c6c700..65dd5a51b14e8b89510ad2677d03fef6ea92082b 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-service.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-service.md @@ -55,7 +55,7 @@ ``` - SA进程按需启动 - 具体参考 **[samgr组件(说明3)](https://gitee.com/openharmony/distributedschedule_samgr/blob/master/README_zh.md)**。 + 具体参考 **[samgr组件(说明3)](https://gitee.com/openharmony/systemabilitymgr_samgr/blob/master/README_zh.md)**。 - socket进程按需启动 1. init进程在pre-fork阶段为socket类进程创建好socket,init进程中监听创建好的socket上的读写事件。 diff --git a/zh-cn/device-dev/subsystems/subsys-data-relational-database-guide.md b/zh-cn/device-dev/subsystems/subsys-data-relational-database-guide.md index 18d44eedce007f87bd76e669dd6f88599e92b9ef..6ee4d0b87bd4814bee203f445818a8b9d2981cd3 100644 --- a/zh-cn/device-dev/subsystems/subsys-data-relational-database-guide.md +++ b/zh-cn/device-dev/subsystems/subsys-data-relational-database-guide.md @@ -206,9 +206,9 @@ c. 创建数据库。 示例代码如下: - ``` + ```c++ const std::string DATABASE_NAME = RDB_TEST_PATH + "RdbStoreTest.db"; - const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + const std::string CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, salary REAL, blobType BLOB)"; class OpenCallback : public RdbOpenCallback { public: @@ -236,7 +236,7 @@ c. 创建数据库。 示例代码如下: - ``` + ```c++ ValuesBucket values; values.PutInt("id", 1); @@ -258,7 +258,7 @@ d. 调用结果集接口,遍历返回结果。 示例代码如下: - ``` + ```c++ std::vector columns = {"id", "name", "age", "salary"}; RdbPredicates predicates("test"); @@ -273,7 +273,7 @@ 示例代码如下: - ``` + ```c++ store->SetDistributedTables("test"); ``` @@ -287,7 +287,7 @@ 示例代码如下: - ``` + ```c++ SyncOption option; option.mode = PUSH; option.isBlock = true; @@ -310,7 +310,7 @@ 示例代码如下: - ``` + ```c++ class MyObserver : public RdbStoreObserver { public: void OnChange(const std::vector& devices) override { @@ -335,7 +335,7 @@ b. 根据指定SQL语句查询数据库中的数据。 示例代码如下: - ``` + ```c++ std::string tableName = store->ObtainDistributedTableName("123456789abcd", "test"); auto resultSet = store->QuerySql("SELECT * from ?;", tableName); ``` @@ -347,7 +347,7 @@ b. 根据指定的数据库备份文件恢复当前数据库。 示例代码如下: - ``` + ```c++ std::string backupName = "backup.db"; // 指定数据库的备份文件名 std::vector key; // 数据库的加密密钥 int errno = store->Backup(backupName, key); diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hilog-lite.md b/zh-cn/device-dev/subsystems/subsys-dfx-hilog-lite.md index cefdcee926126e79d498e549114c36c5ef6a1a32..0aff60913dda95767a7e574cc882987c9148fd84 100755 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hilog-lite.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hilog-lite.md @@ -46,7 +46,7 @@ HILOG_INFO/HILOG_WARN/HILOG_ERROR/HILOG_FATAL HiLogRegisterModule(HILOG_MODULE_SAMGR, "SAMGR"); ``` -3. 在GN文件中添加头文件依赖,文件路径为:“foundation/distributedschedule/samgr_lite/samgr/BUILD.gn“ +3. 在GN文件中添加头文件依赖,文件路径为:“foundation/systemabilitymgr/samgr_lite/samgr/BUILD.gn“ ``` include_dirs = [ @@ -54,7 +54,7 @@ HILOG_INFO/HILOG_WARN/HILOG_ERROR/HILOG_FATAL ] ``` -4. 源文件“foundation/distributedschedule/samgr_lite/samgr/source/message.c“中引用头文件并调用接口。 +4. 源文件“foundation/systemabilitymgr/samgr_lite/samgr/source/message.c“中引用头文件并调用接口。 ``` #include diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md index ed9ee462bc0c7aa0c55077c2e3b0f5991292147e..43b117e43bf1154da0476d90b3840ebff1c16b3d 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md @@ -133,7 +133,7 @@ "hitrace_native", "ipc", "safwk", - "samgr_standard", + "samgr", "utils_base" ], "third_party": [] diff --git a/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md b/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md index 0cfe194a07a4765701f0fa69bc5903057c2f2aaa..e5e065f7dc57ff45c57f3db4a9cb3a167ed9402e 100644 --- a/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md +++ b/zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @@ -34,7 +34,7 @@ OpenHarmony设备安全等级管理(DSLM)模块,负责管理各种不同 - DSLM - DSLM(Device Security Level Managerment), 是OpenHarmony设备安全等级管理的管理模块。负责各OpenHarmony设备之间的设备安全等级信息的同步和验证。并对外提供查询各设备的安全等级的接口。 + DSLM(Device Security Level Management), 是OpenHarmony设备安全等级管理的管理模块。负责各OpenHarmony设备之间的设备安全等级信息的同步和验证。并对外提供查询各设备的安全等级的接口。 ### 运作机制 @@ -44,6 +44,8 @@ OpenHarmony设备安全等级管理(DSLM)模块,负责管理各种不同 OpenHarmony设备的默认安全等级为SL1,设备制造商可以根据设备实际情况定制更高的安全等级。详细请参考章节[设备安全等级定制](#设备安全等级定制)。 +应用开发者在调试分布式业务时,如遇到因设备安全等级过低而导致数据处理或流转失败的情况时,也可以参考章节[工具使用介绍](#工具使用介绍)临时提升相关设备的安全等级。 + ## 开发指导 ### 场景介绍 @@ -109,7 +111,7 @@ OpenHarmony设备的默认安全等级为SL1,设备制造商可以根据设备 - 当目标设备的设备安全等级大于或者等于SL3时,默认允许该文件的传递。 - 当目标设备的设备安全等级小于SL3时,默认拒绝该文件的外传,同时弹框告知用户。 -1. 同步接口使用示例 +同步接口使用示例 ```cpp void CheckDestDeviceSecurityLevel(const DeviceIdentify *device, RequestOption *option) @@ -142,7 +144,7 @@ void CheckDestDeviceSecurityLevel(const DeviceIdentify *device, RequestOption *o } ``` -1. 异步接口使用示例 +异步接口使用示例 ```cpp // 回调函数 @@ -180,7 +182,7 @@ void CheckDestDeviceSecurityLevelAsync(const DeviceIdentify *device, RequestOpti } ``` -## 设备安全等级定制 +## 定制设备安全等级 ### 设备安全等级凭据 @@ -192,7 +194,7 @@ OpenHarmony的设备安全等级管理模块提供了安全等级信息同步与 设备制造商可以根据设备实际情况,参考[基本概念](#基本概念)章节的描述,修改默认的设备安全等级信息。与此同时,设备制造商还可以将OpenHarmony中的默认实现替换为更加严格的验证策略,包括但不限于采用更加精确的一机一凭据策略、从服务器定期下载更新的凭据并严格认证凭据的签发者和有效期、使用TEE(Trusted Execution Environment)甚至SE(Secure Element)对凭据文件进行进一步的签名等流程。 -### 凭据文件生成步骤 +### 生成凭据文件 凭据文件为4段BASE64编码的字符串,中间用"."链接,示例如下: @@ -427,7 +429,7 @@ eyJ0eXAiOiAiRFNMIn0=.eyJ0eXBlIjogImRlYnVnIiwgIm1hbnVmYWN0dXJlIjogIm9ob3MiLCAiYnJ 2. 凭据文件的生成: - 生成一个名为cred.txt的凭据文件,并指定设备型号为rk3568、设备版本号为3.0.0、设备安全等级为SL3等payload信息。 + 生成一个名为cred.txt的凭据文件,并指定设备型号为rk3568、设备版本号为3.0.0、设备安全等级为SL3等payload信息。 ``` undefined ./dslm_cred_tool.py create --field-manufacture OHOS --field-brand rk3568 --field-model rk3568 --field-software-version 3.0.0 --field-security-level SL3 --cred-file cred.txt @@ -467,6 +469,24 @@ eyJ0eXAiOiAiRFNMIn0=.eyJ0eXBlIjogImRlYnVnIiwgIm1hbnVmYWN0dXJlIjogIm9ob3MiLCAiYnJ verify success! ``` +4. 将生成的凭据文件推送到调试设备中并使之生效: + + 临时关闭系统写保护: + ``` undefined + hdc_std target mount + hdc_std shell "setenforce 0" + ``` + + 将刚刚生成的凭据文件推送到设备中: + ``` undefined + hdc_std file send cred.txt /system/etc/dslm_finger.cfg + ``` + + 重启设备使新的凭据文件生效: + ``` undefined + hdc_std reboot + ``` + ## 常见问题 - Q:凭据工具如何在真实的生产环境中使用? @@ -477,6 +497,6 @@ eyJ0eXAiOiAiRFNMIn0=.eyJ0eXBlIjogImRlYnVnIiwgIm1hbnVmYWN0dXJlIjogIm9ob3MiLCAiYnJ A:我们建议设备制造商使用妥善保管的私钥对凭据文件进行签名,同时替换OpenHarmony中对于凭据文件的默认校验流程,增加对凭据签名者的严格校验。例如仅认可信任机构签发的凭据文件、增加凭据和设备ID的一对一强绑定等校验。 -## 参考资料 +- Q:OpenHarmony设备的默认安全等级为SL1,此级别偏低。导致一些分布式业务(如分布式文件系统)在处理部分敏感数据时因权限不足而失败,该如何解决? -无 + A:请参考章节[工具使用介绍](#工具使用介绍)临时提升相关调试设备的安全等级。 diff --git a/zh-cn/device-dev/website.md b/zh-cn/device-dev/website.md index 3554669de0f544e90530523f64e038ffcfad7b69..b62c6d318fb344b03a5f01675b06085279708d20 100644 --- a/zh-cn/device-dev/website.md +++ b/zh-cn/device-dev/website.md @@ -401,11 +401,9 @@ - [Vibrator](driver/driver-peripherals-vibrator-des.md) - [WLAN](driver/driver-peripherals-external-des.md) - 编译构建 - - [轻量和小型系统编译构建指导](subsystems/subsys-build-mini-lite.md) - - [标准系统编译构建指导](subsystems/subsys-build-standard-large.md) + - [编译构建指导](subsystems/subsys-build-all.md) - [构建系统编码规范和最佳实践指导](subsystems/subsys-build-gn-coding-style-and-best-practice.md) - [编译构建Kconfig可视化配置指导](subsystems/subsys-build-gn-kconfig-visual-config-guide.md) - - [HAP编译构建指导](subsystems/subsys-build-gn-hap-compilation-guide.md) - [分布式远程启动](subsystems/subsys-remote-start.md) - 图形图像 - [图形图像概述](subsystems/subsys-graphics-overview.md) diff --git "a/zh-cn/readme/AI\344\270\232\345\212\241\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/AI\344\270\232\345\212\241\345\255\220\347\263\273\347\273\237.md" index 50fa8c9cec1fdda474e58ebd020eaf85343af346..8e062d1450bace80dad9f071044b54c3a64b94a4 100644 --- "a/zh-cn/readme/AI\344\270\232\345\212\241\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/AI\344\270\232\345\212\241\345\255\220\347\263\273\347\273\237.md" @@ -424,7 +424,7 @@ AI业务子系统是OpenHarmony提供原生的分布式AI能力的子系统。 [build\_lite](https://gitee.com/openharmony/build_lite/blob/master/README_zh.md) -[distributedschedule\_samgr\_lite](https://gitee.com/openharmony/distributedschedule_samgr_lite/blob/master/README_zh.md) +[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite/blob/master/README_zh.md) [startup\_init\_lite](https://gitee.com/openharmony/startup_init_lite/blob/master/README_zh.md) diff --git "a/zh-cn/readme/\347\263\273\347\273\237\346\234\215\345\212\241\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237.md" "b/zh-cn/readme/\347\263\273\347\273\237\346\234\215\345\212\241\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237.md" index 1e588345a38e90405827fb135df023923e2bb30f..26b7704d75d1c3ebfba4954a3cb01540528f5e66 100755 --- "a/zh-cn/readme/\347\263\273\347\273\237\346\234\215\345\212\241\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237.md" +++ "b/zh-cn/readme/\347\263\273\347\273\237\346\234\215\345\212\241\347\256\241\347\220\206\345\255\220\347\263\273\347\273\237.md" @@ -21,7 +21,7 @@ ## 目录 ``` -/foundation/distributedschedule +/foundation/systemabilitymgr ├── safwk # 系统服务框架模块 ├── samgr # 系统服务管理模块 ├── safwk_lite # 轻量foundation进程 @@ -32,10 +32,10 @@ **系统服务管理子系统** -[distributedschedule\_safwk](https://gitee.com/openharmony/distributedschedule_safwk) +[systemabilitymgr\_safwk](https://gitee.com/openharmony/systemabilitymgr_safwk) -[distributedschedule\_samgr](https://gitee.com/openharmony/distributedschedule_samgr) +[systemabilitymgr\_samgr](https://gitee.com/openharmony/systemabilitymgr_samgr) -[distributedschedule\_safwk\_lite](https://gitee.com/openharmony/distributedschedule_safwk_lite) +[systemabilitymgr\_safwk\_lite](https://gitee.com/openharmony/systemabilitymgr_safwk_lite) -[distributedschedule\_samgr\_lite](https://gitee.com/openharmony/distributedschedule_samgr_lite) +[systemabilitymgr\_samgr\_lite](https://gitee.com/openharmony/systemabilitymgr_samgr_lite) diff --git a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md index 27f8d8ffcd02f187c1af8cc722dffa2ff4f84777..0dc8c7ad6f995952b1565f942676c5ed83b43568 100644 --- a/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md +++ b/zh-cn/release-notes/OpenHarmony-v3.2-beta2.md @@ -148,9 +148,9 @@ | 泛Sensor服务子系统 | - 支持更多类型的传感器上报。
- 支持SELinux。
主要涉及如下需求:
I53SFI 【DFX打点】【泛Sensor服务子系统】提供系统事件、SA dump、trace打点
I537CB 【新增规格】泛Sensor能力持续集成-旋转矢量传感器
I537AN 【新增规格】泛Sensor能力持续集成-重力传感器
I5379T 【新增规格】泛Sensor能力持续集成-地磁传感器
I5379C 【新增规格】泛Sensor能力持续集成-方向传感器
I53784 【新增规格】泛Sensor能力持续集成-环境光传感器
I53SFS 【新增规格】【泛Sensor服务】SELinux策略配置 | NA | | 分布式数据管理子系统 | data_share支持多种数据类型。
主要涉及如下需求:
I5EHGF 【DataShare】DataShare支持多种数据储存类型 | NA | | web子系统 | - 新增支持JS相关交互能力。
- 新增支持网络、键鼠、webstorage、SELinux策略等能力。
主要涉及如下需求:
I5DM1E 【新增规格】web组件的JS窗口管理
I5DNG2 【新增规格】JS侧提供全量hittest接口以及DefaultUserAgent获取
I5EK53 【新增规格】【web子系统】web组件http验证管理
I5EGBB 【新增规格】【web子系统】【web部件】web子系统的SELinux策略配置
I5EBG1 【新增规格】【web子系统】web子系统适配w3c network information api
I5EVEC 【新增规格】【web子系统】web内核对接鼠标、键盘等外设能力
I5FF2L 【新增规格】【web子系统】web组件支持webstorage | NA | -| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。
- 提供Codec2.0接口及codec驱动模型。
- Camera、Display、Audio、Sensor、WLAN等模块驱动能力增强。
主要涉及如下需求:
I536FN 【新增特性】【驱动子系统】支持HDI passthrough模式
I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能
I550OL 【新增特性】提供DFX跟踪定位,获取信息能力
I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统
I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度
I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一
I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力
I5B0C5 【新增特性】Camera支持实现Mate类型的流
I5B0BR 【新增特性】录像模式自拍镜像功能
I5AJW1 【新增特性】支持Linux libALSA音频接口兼容
I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发
I5F411 【增强特性】马达效果能力增强 | NA | +| 驱动子系统 | - 支持内核态驱动动态加载及DFX能力。
- 提供Codec2.0接口及codec驱动模型。
- Camera、Display、Audio、Sensor、WLAN等模块驱动能力增强。
主要涉及如下需求:
I536FN 【新增特性】【驱动子系统】支持HDI passthrough模式
I5DJE5 【增强特性】兼容Linux uevent事件上报机制,增强设备即插即用功能
I550OL 【新增特性】提供DFX跟踪定位,获取信息能力
I544XP 【新增特性】支持HDF服务SELinux权限检查 标准系统
I528DG 【新增特性】支持Codec 2.0参考实现,简化适配难度
I50I6S 【新增特性】Audio新增IPC模式与直调模式接口调用统一
I5A6H6 【增强特性】增强显示设备管理,支持多屏显示能力
I5B0C5 【新增特性】Camera支持实现Meta类型的流
I5B0BR 【新增特性】录像模式自拍镜像功能
I5AJW1 【新增特性】支持Linux libALSA音频接口兼容
I56V2N 【新增特性】HDF WLAN DAL HDI功率模式相关接口的定义与开发
I5F411 【增强特性】马达效果能力增强 | NA | | USB服务子系统 | - 支持USB服务广播消息。
- 增加SELinux安全策略。
主要涉及如下需求:
I59MYK 【新增特性】USB服务广播消息
I5AR8N 【新增规格】【USB服务子系统】USB服务子系统的SELinux策略配置 | NA | -| 内核子系统 | - 新增支持内存精细化管控特性。
- 新增支持关联服务adj调整机制。
主要涉及如下需求:
I58LOD 【新增特性】支持关联服务adj调整机制
I54Y5J 【新增特性】支持memtrack内存占用和进程维度adj查询接口特性
I56B3Q 【新增特性】支持OnMemoryLevel特性
I5B694 【新增特性】支持新型内存精细化管控特性
I59O8H 【新增特性】支持purgable memory特性
I5CXOK 【新增特性】支持hyperhold可靠性提升特性 | NA | +| 内核子系统 | - 新增支持内存精细化管控特性。
- 新增支持关联服务adj调整机制。
主要涉及如下需求:
I58LOD 【新增特性】支持关联服务adj调整机制
I54Y5J 【新增特性】支持memtrack内存占用和进程维度adj查询接口特性
I56B3Q 【新增特性】支持OnMemoryLevel特性
I5B694 【新增特性】支持新型内存精细化管控特性
I59O8H 【新增特性】支持purgeable memory特性
I5CXOK 【新增特性】支持hyperhold可靠性提升特性 | NA | ### diff --git a/zh-cn/website.md b/zh-cn/website.md index 1edc4cf36f5c38ac154fac3af0336e2c89ab9a03..e686f85221b05a2e0628d98ec756348e770a714d 100644 --- a/zh-cn/website.md +++ b/zh-cn/website.md @@ -127,8 +127,8 @@ - [Native API差异报告](release-notes/api-change/v3.1-Release/native-apidiff-v3.1-release.md) - 变更说明 - OpenHamrony 3.2 Beta2 - - [3.2 beta2相对3.2 beta1变更详细说明](release-notes\changelog\v3.2-beta2\changelog-v3.2-beta2.md) - - [OpenHarmony启用应用沙箱机制-适配指导](release-notes\changelog\v3.2-beta2\application-sandbox-adaptation-guide.md) + - [3.2 beta2相对3.2 beta1变更详细说明](release-notes/changelog/v3.2-beta2/changelog-v3.2-beta2.md) + - [OpenHarmony启用应用沙箱机制-适配指导](release-notes/changelog/v3.2-beta2/application-sandbox-adaptation-guide.md) - OpenHarmony三方组件 - [OpenHarmony三方组件简介](third-party-components/third-party-components-introduction.md) - [OpenHarmony JS/TS三方组件使用指导](third-party-components/npm-third-party-guide.md)