提交 0aac27e4 编写于 作者: IT_newip's avatar IT_newip

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

# Buffer # Buffer
> **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.
A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data.
You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, receive and upload files, and use network protocols. You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files.
## Modules to Import ## Modules to Import
...@@ -52,7 +53,7 @@ let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ...@@ -52,7 +53,7 @@ let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
allocUninitializedFromPool(size: number): Buffer allocUninitializedFromPool(size: number): Buffer
Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it.
To initialize the **Buffer** instance, call the **fill()** function. To initialize the **Buffer** instance, call **fill()**.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -108,7 +109,7 @@ buf.fill(0); ...@@ -108,7 +109,7 @@ buf.fill(0);
### byteLength ### byteLength
byteLength(string: string | Buffer | TypeArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number
Obtains the number of bytes of a string based on the encoding format. Obtains the number of bytes of a string based on the encoding format.
...@@ -118,7 +119,7 @@ Obtains the number of bytes of a string based on the encoding format. ...@@ -118,7 +119,7 @@ Obtains the number of bytes of a string based on the encoding format.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| string | string \| Buffer \| TypeArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.|
| encoding | BufferEncoding | No| Encoding format. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format. The default value is **utf-8**.|
**Return value** **Return value**
...@@ -133,15 +134,15 @@ Obtains the number of bytes of a string based on the encoding format. ...@@ -133,15 +134,15 @@ Obtains the number of bytes of a string based on the encoding format.
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let str = '\u00bd + \u00bc = \u00be'; let str = '\u00bd + \u00bc = \u00be';
console.log('${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes'); console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes`);
// Print: ½ + ¼ = ¾: 9 characters, 12 bytes // Print: ½ + ¼ = ¾: 9 characters, 12 bytes
``` ```
### compare ### compare
compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): number compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1
Compares two **Buffer** instances. Compares two **Buffer** instances. This API is used for sorting **Buffer** instances.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -157,7 +158,7 @@ Compares two **Buffer** instances. ...@@ -157,7 +158,7 @@ Compares two **Buffer** instances.
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | Returns **0** if **buf1** is the same as **buf2**.<br>Returns **1** if **buf1** comes after **buf2** when sorted.<br>Returns **-1** if **buf1** comes before **buf2** when sorted.| | -1&nbsp;\|&nbsp;0&nbsp;\|&nbsp;1 | Returns **0** if **buf1** is the same as **buf2**.<br>Returns **1** if **buf1** comes after **buf2** when sorted.<br>Returns **-1** if **buf1** comes before **buf2** when sorted.|
**Example** **Example**
...@@ -166,8 +167,9 @@ import buffer from '@ohos.buffer'; ...@@ -166,8 +167,9 @@ import buffer from '@ohos.buffer';
let buf1 = buffer.from('1234'); let buf1 = buffer.from('1234');
let buf2 = buffer.from('0123'); let buf2 = buffer.from('0123');
let res = buf1.compare(buf2);
console.log(buf1.compare(buf2)); console.log(Number(res).toString());
// Print 1 // Print 1
``` ```
...@@ -200,12 +202,12 @@ import buffer from '@ohos.buffer'; ...@@ -200,12 +202,12 @@ import buffer from '@ohos.buffer';
let buf1 = buffer.from("1234"); let buf1 = buffer.from("1234");
let buf2 = buffer.from("abcd"); let buf2 = buffer.from("abcd");
let buf = buffer.concat([buf1, buf2]); let buf = buffer.concat([buf1, buf2]);
console.log(buf); // <Buffer 31 32 33 34 61 62 63 64> console.log(buf.toString('hex')); // 3132333461626364
``` ```
### from ### from
from(array: number[]): Buffer from(array: number[]): Buffer;
Creates a **Buffer** instance with the specified array. Creates a **Buffer** instance with the specified array.
...@@ -228,11 +230,8 @@ Creates a **Buffer** instance with the specified array. ...@@ -228,11 +230,8 @@ Creates a **Buffer** instance with the specified array.
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let arrayList = new ArrayList();
let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
console.log(buf); console.log(buf.toString('hex')); // 627566666572
// Print: <Buffer 62 75 66 66 65 72>
``` ```
### from ### from
...@@ -268,7 +267,7 @@ let buf = buffer.from(ab, 0, 2); ...@@ -268,7 +267,7 @@ let buf = buffer.from(ab, 0, 2);
### from ### from
from(data: Buffer | Uint8Array): Buffer from(buffer: Buffer | Uint8Array): Buffer
Creates a **Buffer** instance with the copy of another instance. Creates a **Buffer** instance with the copy of another instance.
...@@ -278,7 +277,7 @@ Creates a **Buffer** instance with the copy of another instance. ...@@ -278,7 +277,7 @@ Creates a **Buffer** instance with the copy of another instance.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| data | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Instance to copy.| | buffer | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| **Buffer** instance to copy. |
**Return value** **Return value**
...@@ -327,7 +326,7 @@ let buf = buffer.from(new String('this is a test')); ...@@ -327,7 +326,7 @@ let buf = buffer.from(new String('this is a test'));
### from ### from
from(string: string, encoding?: BufferEncoding): Buffer from(string: String, encoding?: BufferEncoding): Buffer
Creates a **Buffer** instance based on a string in the given encoding format. Creates a **Buffer** instance based on a string in the given encoding format.
...@@ -337,7 +336,7 @@ Creates a **Buffer** instance based on a string in the given encoding format. ...@@ -337,7 +336,7 @@ Creates a **Buffer** instance based on a string in the given encoding format.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| string | string | Yes| String.| | string | String | Yes| String.|
| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.|
**Return value** **Return value**
...@@ -403,7 +402,7 @@ Checks whether the encoding format is supported. ...@@ -403,7 +402,7 @@ Checks whether the encoding format is supported.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| encoding | string | Yes| Encoding format.| | encoding | string | Yes| Encoding format to check. |
**Return value** **Return value**
...@@ -416,10 +415,10 @@ Checks whether the encoding format is supported. ...@@ -416,10 +415,10 @@ Checks whether the encoding format is supported.
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
console.log (Buffer.isEncoding ('utf-8')); // Print: true console.log(buffer.isEncoding('utf-8').toString()); // Print: true
console.log (Buffer.isEncoding ('hex')); // Print: true console.log(buffer.isEncoding('hex').toString()); // Print: true
console.log (Buffer.isEncoding ('utf/8')); // Print: false console.log(buffer.isEncoding('utf/8').toString()); // Print: false
console.log (Buffer.isEncoding ('')); // Print: false console.log(buffer.isEncoding('').toString()); // Print: false
``` ```
### compare ### compare
...@@ -436,13 +435,15 @@ Compares this **Buffer** instance with another instance. ...@@ -436,13 +435,15 @@ Compares this **Buffer** instance with another instance.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| target | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Target **Buffer** instance to compare.| | target | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Target **Buffer** instance to compare.|
| targetStart | number | No| Offset to the start of the data to compare in the target **Buffer** instance. The default value is **0**.| | targetStart | number | No| Offset to the start of the data to compare in the target **Buffer** instance. The default value is **0**.|
| targetEnd | number | No| Offset to the end of the data to compare in the target **Buffer** instance (not inclusive). The default value is length of the target **Buffer** instance.| | targetEnd | number | No| Offset to the end of the data to compare in the target **Buffer** instance (not inclusive). The default value is the length of the target **Buffer** instance.|
| sourceStart | number | No| Offset to the start of the data to compare in this **Buffer** instance. The default value is **0**.| | sourceStart | number | No| Offset to the start of the data to compare in this **Buffer** instance. The default value is **0**.|
| sourceEnd | number | No| Offset to the end of the data to compare in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| | sourceEnd | number | No| Offset to the end of the data to compare in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.|
**Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | Returns **0** if the two **Buffer** instances are the same.<br>Returns **1** if the target instance comes before this instance when sorted.<br>Returns **-1** if the target instance comes after this instance when sorted.| | number | Returns **0** if the two **Buffer** instances are the same.<br>Returns **1** if this instance comes after the target instance when sorted.<br>Returns **-1** if this instance comes before the target instance when sorted. |
**Example** **Example**
...@@ -452,9 +453,9 @@ import buffer from '@ohos.buffer'; ...@@ -452,9 +453,9 @@ import buffer from '@ohos.buffer';
let buf1 = buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); let buf1 = buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log (buf1.compare (buf2, 5, 9, 0, 4); // Print: 0 console.log(buf1.compare(buf2, 5, 9, 0, 4).toString()); // Print: 0
console.log (buf1.compare (buf2, 0, 6, 4); // Print: -1 console.log(buf1.compare(buf2, 0, 6, 4).toString()); // Print: -1
console.log (buf1.compare (buf2, 5, 6, 5)); // Print: 1 console.log(buf1.compare(buf2, 5, 6, 5).toString()); // Print: 1
``` ```
### copy ### copy
...@@ -512,13 +513,13 @@ import buffer from '@ohos.buffer'; ...@@ -512,13 +513,13 @@ import buffer from '@ohos.buffer';
let buf = buffer.from('buffer'); let buf = buffer.from('buffer');
for (let pair of buf.entries()) { for (let pair of buf.entries()) {
console.log(pair); console.log(pair.toString());
} }
``` ```
### equals ### equals
equals(otherBuffer: Buffer | Uint8Array): boolean equals(otherBuffer: Uint8Array | Buffer): boolean
Checks whether this **Buffer** instance is the same as another **Buffer** instance. Checks whether this **Buffer** instance is the same as another **Buffer** instance.
...@@ -528,7 +529,7 @@ Checks whether this **Buffer** instance is the same as another **Buffer** instan ...@@ -528,7 +529,7 @@ Checks whether this **Buffer** instance is the same as another **Buffer** instan
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| otherBuffer | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| **Buffer** instance to compare.| | otherBuffer | Uint8Array&nbsp;\|&nbsp;Buffer | Yes| **Buffer** instance to compare.|
**Return value** **Return value**
...@@ -545,8 +546,8 @@ let buf1 = buffer.from('ABC'); ...@@ -545,8 +546,8 @@ let buf1 = buffer.from('ABC');
let buf2 = buffer.from('414243', 'hex'); let buf2 = buffer.from('414243', 'hex');
let buf3 = buffer.from('ABCD'); let buf3 = buffer.from('ABCD');
console.log (buf1.equals (buf2)); // Print: true console.log(buf1.equals(buf2).toString()); // Print: true
console.log (buf1.equals (buf3)); // Print: false console.log(buf1.equals(buf3).toString()); // Print: false
``` ```
...@@ -596,7 +597,7 @@ Checks whether this **Buffer** instance contains the specified value. ...@@ -596,7 +597,7 @@ Checks whether this **Buffer** instance contains the specified value.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.| | value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.|
| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. |
| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.|
**Return value** **Return value**
...@@ -611,8 +612,8 @@ Checks whether this **Buffer** instance contains the specified value. ...@@ -611,8 +612,8 @@ Checks whether this **Buffer** instance contains the specified value.
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from('this is a buffer'); let buf = buffer.from('this is a buffer');
console.log (buf.includes ('this')); // Print: true console.log(buf.includes('this').toString()); // Print: true
console.log (buf.includes ('be')); // Print: false console.log(buf.includes('be').toString()); // Print: false
``` ```
### indexOf ### indexOf
...@@ -628,7 +629,7 @@ Obtains the index of the first occurrence of the specified value in this **Buffe ...@@ -628,7 +629,7 @@ Obtains the index of the first occurrence of the specified value in this **Buffe
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.| | value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.|
| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. |
| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.|
**Return value** **Return value**
...@@ -643,8 +644,8 @@ Obtains the index of the first occurrence of the specified value in this **Buffe ...@@ -643,8 +644,8 @@ Obtains the index of the first occurrence of the specified value in this **Buffe
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from('this is a buffer'); let buf = buffer.from('this is a buffer');
console.log (buf.indexOf('this')); // Print: 0 console.log(buf.indexOf('this').toString()); // Print: 0
console.log(buf.indexOf('is')); // Print: 2 console.log(buf.indexOf('is').toString()); // Print: 2
``` ```
### keys ### keys
...@@ -668,7 +669,7 @@ import buffer from '@ohos.buffer'; ...@@ -668,7 +669,7 @@ import buffer from '@ohos.buffer';
let buf = buffer.from('buffer'); let buf = buffer.from('buffer');
for (const key of buf.keys()) { for (const key of buf.keys()) {
console.log(key); console.log(key.toString());
} }
``` ```
...@@ -685,7 +686,7 @@ Obtains the index of the last occurrence of the specified value in this **Buffer ...@@ -685,7 +686,7 @@ Obtains the index of the last occurrence of the specified value in this **Buffer
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.| | value | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Value to match.|
| byteOffset | number | No| Number of bytes to skip before checking data. If the offset is a negative number, data is searched from the end of the **Buffer** instance. The default value is **0**.| | byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. |
| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.|
**Return value** **Return value**
...@@ -700,16 +701,16 @@ Obtains the index of the last occurrence of the specified value in this **Buffer ...@@ -700,16 +701,16 @@ Obtains the index of the last occurrence of the specified value in this **Buffer
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from('this buffer is a buffer'); let buf = buffer.from('this buffer is a buffer');
console.log(buf.lastIndexOf('this')); // Print: 0 console.log(buf.lastIndexOf('this').toString()); // Print: 0
console.log(buf.lastIndexOf('buffer')); // Print:17 console.log(buf.lastIndexOf('buffer').toString()); // Print: 17
``` ```
### readBigInt64BE ### readBigInt64BE
readBigInt64BE(offset: number): number readBigInt64BE(offset?: number): bigint
Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -717,13 +718,13 @@ Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the s ...@@ -717,13 +718,13 @@ Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the s
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A signed, big-endian 64-bit integer.| | bigint | A signed, big-endian 64-bit Big integer. |
**Example** **Example**
...@@ -732,14 +733,14 @@ import buffer from '@ohos.buffer'; ...@@ -732,14 +733,14 @@ import buffer from '@ohos.buffer';
let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]);
console.log(buf.readBigInt64BE(0)); console.log(buf.readBigInt64BE(0).toString());
``` ```
### readBigInt64LE ### readBigInt64LE
readBigInt64LE(offset: number): number readBigInt64LE(offset?: number): bigint
Reads a signed, little-endian 64-bit integer from this **Buffer** instance at the specified offset. Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -747,13 +748,13 @@ Reads a signed, little-endian 64-bit integer from this **Buffer** instance at th ...@@ -747,13 +748,13 @@ Reads a signed, little-endian 64-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A signed, little-endian 64-bit integer.| | bigint | A signed, little-endian 64-bit Big integer. |
**Example** **Example**
...@@ -762,14 +763,14 @@ import buffer from '@ohos.buffer'; ...@@ -762,14 +763,14 @@ import buffer from '@ohos.buffer';
let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]);
console.log(buf.readBigInt64LE(0)); console.log(buf.readBigInt64LE(0).toString());
``` ```
### readBigUInt64BE ### readBigUInt64BE
readBigUInt64BE(offset: number): number readBigUInt64BE(offset?: number): bigint
Reads an unsigned, big-endian 64-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -777,13 +778,13 @@ Reads an unsigned, big-endian 64-bit integer from this **Buffer** instance at th ...@@ -777,13 +778,13 @@ Reads an unsigned, big-endian 64-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | An unsigned, big-endian 64-bit integer.| | bigint | An unsigned, big-endian 64-bit Big integer. |
**Example** **Example**
...@@ -792,14 +793,14 @@ import buffer from '@ohos.buffer'; ...@@ -792,14 +793,14 @@ import buffer from '@ohos.buffer';
let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]);
console.log(buf.readBigUInt64BE(0)); console.log(buf.readBigUInt64BE(0).toString());
``` ```
### readBigUInt64LE ### readBigUInt64LE
readBigUInt64LE(offset: number): number readBigUInt64LE(offset?: number): bigint
Reads an unsigned, little-endian 64-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -807,13 +808,13 @@ Reads an unsigned, little-endian 64-bit integer from this **Buffer** instance at ...@@ -807,13 +808,13 @@ Reads an unsigned, little-endian 64-bit integer from this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | An unsigned, little-endian 64-bit integer.| | bigint | An unsigned, little-endian 64-bit Big integer. |
**Example** **Example**
...@@ -822,14 +823,14 @@ import buffer from '@ohos.buffer'; ...@@ -822,14 +823,14 @@ import buffer from '@ohos.buffer';
let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]);
console.log(buf.readBigUInt64LE(0)); console.log(buf.readBigUInt64LE(0).toString());
``` ```
### readDoubleBE ### readDoubleBE
readDoubleBE(offset: number): number readDoubleBE(offset?: number): number
Reads a 64-bit, big-endian double-precision floating-point number from this **Buffer** instance at the specified offset. Reads a big-endian double-precision floating-point number from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -837,13 +838,13 @@ Reads a 64-bit, big-endian double-precision floating-point number from this **Bu ...@@ -837,13 +838,13 @@ Reads a 64-bit, big-endian double-precision floating-point number from this **Bu
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A 64-bit, big-endian double-precision floating-point number.| | number | A big-endian double-precision floating-point number. |
**Example** **Example**
...@@ -851,14 +852,14 @@ Reads a 64-bit, big-endian double-precision floating-point number from this **Bu ...@@ -851,14 +852,14 @@ Reads a 64-bit, big-endian double-precision floating-point number from this **Bu
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleBE(0)); console.log(buf.readDoubleBE(0).toString());
``` ```
### readDoubleLE ### readDoubleLE
readDoubleLE(offset: number): number readDoubleLE(offset?: number): number
Reads a 64-bit, little-endian double-precision floating-point number from this **Buffer** instance at the specified offset. Reads a little-endian double-precision floating-point number from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -866,13 +867,13 @@ Reads a 64-bit, little-endian double-precision floating-point number from this * ...@@ -866,13 +867,13 @@ Reads a 64-bit, little-endian double-precision floating-point number from this *
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A 64-bit, little-endian double-precision floating-point number.| | number | A little-endian double-precision floating-point number. |
**Example** **Example**
...@@ -880,14 +881,14 @@ Reads a 64-bit, little-endian double-precision floating-point number from this * ...@@ -880,14 +881,14 @@ Reads a 64-bit, little-endian double-precision floating-point number from this *
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readDoubleLE(0)); console.log(buf.readDoubleLE(0).toString());
``` ```
### readFloatBE ### readFloatBE
readFloatBE(offset: number): number readFloatBE(offset?: number): number
Reads a 32-bit, big-endian floating-point number from this **Buffer** instance at the specified offset. Reads a big-endian single-precision floating-point number from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -895,13 +896,13 @@ Reads a 32-bit, big-endian floating-point number from this **Buffer** instance a ...@@ -895,13 +896,13 @@ Reads a 32-bit, big-endian floating-point number from this **Buffer** instance a
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A 32-bit, big-endian floating-point number.| | number | A big-endian single-precision floating-point number. |
**Example** **Example**
...@@ -909,14 +910,14 @@ Reads a 32-bit, big-endian floating-point number from this **Buffer** instance a ...@@ -909,14 +910,14 @@ Reads a 32-bit, big-endian floating-point number from this **Buffer** instance a
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readFloatBE(0)); console.log(buf.readFloatBE(0).toString());
``` ```
### readFloatLE ### readFloatLE
readFloatLE(offset: number): number readFloatLE(offset?: number): number
Reads a 32-bit, little-endian floating-point number from this **Buffer** instance at the specified offset. Reads a little-endian single-precision floating-point number from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -924,13 +925,13 @@ Reads a 32-bit, little-endian floating-point number from this **Buffer** instanc ...@@ -924,13 +925,13 @@ Reads a 32-bit, little-endian floating-point number from this **Buffer** instanc
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A 32-bit, little-endian floating-point number.| | number | A little-endian single-precision floating-point number. |
**Example** **Example**
...@@ -938,12 +939,12 @@ Reads a 32-bit, little-endian floating-point number from this **Buffer** instanc ...@@ -938,12 +939,12 @@ Reads a 32-bit, little-endian floating-point number from this **Buffer** instanc
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]);
console.log(buf.readFloatLE(0)); console.log(buf.readFloatLE(0).toString());
``` ```
### readInt8 ### readInt8
readInt8(offset: number): number readInt8(offset?: number): number
Reads a signed 8-bit integer from this **Buffer** instance at the specified offset. Reads a signed 8-bit integer from this **Buffer** instance at the specified offset.
...@@ -953,13 +954,13 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs ...@@ -953,13 +954,13 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| number | A signed 8-bit integer.| | number | A signed 8-bit integer. |
**Example** **Example**
...@@ -967,13 +968,13 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs ...@@ -967,13 +968,13 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([-1, 5]); let buf = buffer.from([-1, 5]);
console.log (buf.readInt8(0)); // Print: -1 console.log(buf.readInt8(0).toString()); // Print: -1
console.log (buf.readInt8(1); // Print: 5 console.log(buf.readInt8(1).toString()); // Print: 5
``` ```
### readInt16BE ### readInt16BE
readInt16BE(offset: number): number readInt16BE(offset?: number): number
Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset. Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset.
...@@ -983,7 +984,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s ...@@ -983,7 +984,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -996,13 +997,13 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s ...@@ -996,13 +997,13 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = Buffer.from([0, 5]); let buf = buffer.from([0, 5]);
console.log (buf.readInt16BE(0)); // Print: 5 console.log(buf.readInt16BE(0).toString()); // Print: 5
``` ```
### readInt16LE ### readInt16LE
readInt16LE(offset: number): number readInt16LE(offset?: number): number
Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset. Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset.
...@@ -1012,7 +1013,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th ...@@ -1012,7 +1013,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1025,13 +1026,13 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th ...@@ -1025,13 +1026,13 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = Buffer.from([0, 5]); let buf = buffer.from([0, 5]);
console.log (buf.readInt16BE(0)); // Print: 1280 console.log(buf.readInt16LE(0).toString()); // Print: 1280
``` ```
### readInt32BE ### readInt32BE
readInt32BE(offset: number): number readInt32BE(offset?: number): number
Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset. Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset.
...@@ -1041,7 +1042,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s ...@@ -1041,7 +1042,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1055,12 +1056,12 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s ...@@ -1055,12 +1056,12 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([0, 0, 0, 5]); let buf = buffer.from([0, 0, 0, 5]);
console.log(buf.readInt32BE(0)); // Print: 5 console.log(buf.readInt32BE(0).toString()); // Print: 5
``` ```
### readInt32LE ### readInt32LE
readInt32LE(offset: number): number readInt32LE(offset?: number): number
Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset. Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset.
...@@ -1070,7 +1071,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th ...@@ -1070,7 +1071,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | Yes| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1084,7 +1085,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th ...@@ -1084,7 +1085,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([0, 0, 0, 5]); let buf = buffer.from([0, 0, 0, 5]);
console.log (buf.readInt32LE(0)); // Print: 83886080 console.log(buf.readInt32LE(0).toString()); // Print: 83886080
``` ```
### readIntBE ### readIntBE
...@@ -1099,8 +1100,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi ...@@ -1099,8 +1100,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.|
| byteLength | number | No| Number of bytes to read.| | byteLength | number | Yes| Number of bytes to read.|
**Return value** **Return value**
...@@ -1114,9 +1115,9 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi ...@@ -1114,9 +1115,9 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = Buffer.from("ab"); let buf = buffer.from("ab");
let num = buf.readIntBE(0, 1); let num = buf.readIntBE(0, 1);
console.log(num); // 97 console.log(num.toString()); // 97
``` ```
...@@ -1132,8 +1133,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi ...@@ -1132,8 +1133,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.|
| byteLength | number | No| Number of bytes to read.| | byteLength | number | Yes| Number of bytes to read.|
**Return value** **Return value**
...@@ -1153,7 +1154,7 @@ console.log(buf.readIntLE(0, 6).toString(16)); ...@@ -1153,7 +1154,7 @@ console.log(buf.readIntLE(0, 6).toString(16));
### readUInt8 ### readUInt8
readUInt8(offset: number): number readUInt8(offset?: number): number
Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset.
...@@ -1163,7 +1164,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o ...@@ -1163,7 +1164,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1178,13 +1179,13 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o ...@@ -1178,13 +1179,13 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.from([1, -2]); let buf = buffer.from([1, -2]);
console.log(buf.readUInt8(0)); console.log(buf.readUInt8(0).toString());
console.log(buf.readUInt8(1)); console.log(buf.readUInt8(1).toString());
``` ```
### readUInt16BE ### readUInt16BE
readUInt16BE(offset: number): number readUInt16BE(offset?: number): number
Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset.
...@@ -1194,7 +1195,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th ...@@ -1194,7 +1195,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1215,7 +1216,7 @@ console.log(buf.readUInt16BE(1).toString(16)); ...@@ -1215,7 +1216,7 @@ console.log(buf.readUInt16BE(1).toString(16));
### readUInt16LE ### readUInt16LE
readUInt16LE(offset: number): number readUInt16LE(offset?: number): number
Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset.
...@@ -1225,7 +1226,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at ...@@ -1225,7 +1226,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1246,7 +1247,7 @@ console.log(buf.readUInt16LE(1).toString(16)); ...@@ -1246,7 +1247,7 @@ console.log(buf.readUInt16LE(1).toString(16));
### readUInt32BE ### readUInt32BE
readUInt32BE(offset: number): number readUInt32BE(offset?: number): number
Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset.
...@@ -1256,7 +1257,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th ...@@ -1256,7 +1257,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1276,7 +1277,7 @@ console.log(buf.readUInt32BE(0).toString(16)); ...@@ -1276,7 +1277,7 @@ console.log(buf.readUInt32BE(0).toString(16));
### readUInt32LE ### readUInt32LE
readUInt32LE(offset: number): number readUInt32LE(offset?: number): number
Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset. Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset.
...@@ -1286,7 +1287,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at ...@@ -1286,7 +1287,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.|
**Return value** **Return value**
...@@ -1316,8 +1317,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi ...@@ -1316,8 +1317,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.|
| byteLength | number | No| Number of bytes to read.| | byteLength | number | Yes| Number of bytes to read.|
**Return value** **Return value**
...@@ -1347,8 +1348,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi ...@@ -1347,8 +1348,8 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| offset | number | No| Number of bytes to skip before reading data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.|
| byteLength | number | No| Number of bytes to read.| | byteLength | number | Yes| Number of bytes to read.|
**Return value** **Return value**
...@@ -1423,10 +1424,10 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and ...@@ -1423,10 +1424,10 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1); // Print: <Buffer 01 02 03 04 05 06 07 08> console.log(buf1.toString('hex')); // Print: 0102030405060708
buf1.swap16(); buf1.swap16();
console.log(buf1); // Print: <Buffer 02 01 04 03 06 05 08 07> console.log(buf1.toString('hex')); // Print: 0201040306050807
``` ```
### swap32 ### swap32
...@@ -1450,10 +1451,10 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and ...@@ -1450,10 +1451,10 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1); // Print: <Buffer 01 02 03 04 05 06 07 08> console.log(buf1.toString('hex')); // Print: 0102030405060708
buf1.swap32(); buf1.swap32();
console.log(buf1); // Print: <Buffer 04 03 02 01 08 07 06 05> console.log(buf1.toString('hex')); // Print: 0403020108070605
``` ```
### swap64 ### swap64
...@@ -1477,9 +1478,9 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and ...@@ -1477,9 +1478,9 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]);
console.log(buf1); // Print: <Buffer 01 02 03 04 05 06 07 08> console.log(buf1.toString('hex')); // Print: 0102030405060708
buf1.swap64(); buf1.swap64();
console.log(buf1); // Print: <Buffer 08 07 06 05 04 03 02 01> console.log(buf1.toString('hex')); // Print: 0807060504030201
``` ```
### toJSON ### toJSON
...@@ -1503,9 +1504,8 @@ Converts this **Buffer** instance into a JSON object. ...@@ -1503,9 +1504,8 @@ Converts this **Buffer** instance into a JSON object.
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]);
let buf2 = buffer.from(buf1.toJSON()) let obj = buf1.toJSON();
let json = JSON.stringify(buf2); console.log(JSON.stringify(obj))
console.log(json);
// Print: {"type":"Buffer","data":[1,2,3,4,5]} // Print: {"type":"Buffer","data":[1,2,3,4,5]}
``` ```
...@@ -1564,8 +1564,8 @@ Creates and returns an iterator that contains the values of this **Buffer** inst ...@@ -1564,8 +1564,8 @@ Creates and returns an iterator that contains the values of this **Buffer** inst
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf1 = buffer.from('buffer'); let buf1 = buffer.from('buffer');
for (const value of buf.values()) { for (let value of buf1.values()) {
console.log(value); console.log(value.toString());
} }
``` ```
...@@ -1582,7 +1582,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci ...@@ -1582,7 +1582,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| str | string | Yes| String to write.| | str | string | Yes| String to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
| length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.| | length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.|
| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| | encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.|
...@@ -1603,15 +1603,15 @@ let len = buf.write('\u00bd + \u00bc = \u00be', 0); ...@@ -1603,15 +1603,15 @@ let len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf-8', 0, len)}`); console.log(`${len} bytes: ${buf.toString('utf-8', 0, len)}`);
// Print: 12 bytes: ½ + ¼ = ¾ // Print: 12 bytes: ½ + ¼ = ¾
let buffer = Buffer.alloc(10); let buffer1 = buffer.alloc(10);
let length = buffer.write('abcd', 8); let length = buffer1.write('abcd', 8);
``` ```
### writeBigInt64BE ### writeBigInt64BE
writeBigInt64BE(value: number, offset?: number): number writeBigInt64BE(value: bigint, offset?: number): number
Writes a signed, big-endian 64-bit integer to this **Buffer** instance at the specified offset. Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1619,8 +1619,8 @@ Writes a signed, big-endian 64-bit integer to this **Buffer** instance at the sp ...@@ -1619,8 +1619,8 @@ Writes a signed, big-endian 64-bit integer to this **Buffer** instance at the sp
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | bigint | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1640,9 +1640,9 @@ buf.writeBigInt64BE(0x0102030405060708n, 0); ...@@ -1640,9 +1640,9 @@ buf.writeBigInt64BE(0x0102030405060708n, 0);
### writeBigInt64LE ### writeBigInt64LE
writeBigInt64LE(value : number, offset? : number): number writeBigInt64LE(value: bigint, offset?: number): number
Writes a signed, little-endian 64-bit integer to this **Buffer** instance at the specified offset. Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1650,8 +1650,8 @@ Writes a signed, little-endian 64-bit integer to this **Buffer** instance at the ...@@ -1650,8 +1650,8 @@ Writes a signed, little-endian 64-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | bigint | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1671,9 +1671,9 @@ buf.writeBigInt64LE(0x0102030405060708n, 0); ...@@ -1671,9 +1671,9 @@ buf.writeBigInt64LE(0x0102030405060708n, 0);
### writeBigUInt64BE ### writeBigUInt64BE
writeBigUInt64BE(value : number, offset? : number): number writeBigUInt64BE(value: bigint, offset?: number): number
Writes an unsigned, big-endian 64-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1681,8 +1681,8 @@ Writes an unsigned, big-endian 64-bit integer to this **Buffer** instance at the ...@@ -1681,8 +1681,8 @@ Writes an unsigned, big-endian 64-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | bigint | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1702,9 +1702,9 @@ buf.writeBigUInt64BE(0xdecafafecacefaden, 0); ...@@ -1702,9 +1702,9 @@ buf.writeBigUInt64BE(0xdecafafecacefaden, 0);
### writeBigUInt64LE ### writeBigUInt64LE
writeBigUInt64LE(value : number, offset? : number): number writeBigUInt64LE(value: bigint, offset?: number): number
Writes an unsigned, little-endian 64-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1712,8 +1712,8 @@ Writes an unsigned, little-endian 64-bit integer to this **Buffer** instance at ...@@ -1712,8 +1712,8 @@ Writes an unsigned, little-endian 64-bit integer to this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | bigint | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1733,9 +1733,9 @@ buf.writeBigUInt64LE(0xdecafafecacefaden, 0); ...@@ -1733,9 +1733,9 @@ buf.writeBigUInt64LE(0xdecafafecacefaden, 0);
### writeDoubleBE ### writeDoubleBE
writeDoubleBE(value : number, offset? : number): number writeDoubleBE(value: number, offset?: number): number
Writes a 64-bit, big-endian double-precision floating-point number to this **Buffer** instance at the specified offset. Writes a big-endian double-precision floating-point number to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1744,7 +1744,7 @@ Writes a 64-bit, big-endian double-precision floating-point number to this **Buf ...@@ -1744,7 +1744,7 @@ Writes a 64-bit, big-endian double-precision floating-point number to this **Buf
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1764,9 +1764,9 @@ buf.writeDoubleBE(123.456, 0); ...@@ -1764,9 +1764,9 @@ buf.writeDoubleBE(123.456, 0);
### writeDoubleLE ### writeDoubleLE
writeDoubleLE(value : number, offset? : number): number writeDoubleLE(value: number, offset?: number): number
Writes a 64-bit, little-endian double-precision floating-point number to this **Buffer** instance at the specified offset. Writes a little-endian double-precision floating-point number to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1775,7 +1775,7 @@ Writes a 64-bit, little-endian double-precision floating-point number to this ** ...@@ -1775,7 +1775,7 @@ Writes a 64-bit, little-endian double-precision floating-point number to this **
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1795,9 +1795,9 @@ buf.writeDoubleLE(123.456, 0); ...@@ -1795,9 +1795,9 @@ buf.writeDoubleLE(123.456, 0);
### writeFloatBE ### writeFloatBE
writeFloatBE(value : number, offset? : number): number writeFloatBE(value: number, offset?: number): number
Writes a 32-bit, big-endian floating-point number to this **Buffer** instance at the specified offset. Writes a big-endian single-precision floating-point number to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1806,7 +1806,7 @@ Writes a 32-bit, big-endian floating-point number to this **Buffer** instance at ...@@ -1806,7 +1806,7 @@ Writes a 32-bit, big-endian floating-point number to this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1827,9 +1827,9 @@ buf.writeFloatBE(0xcafebabe, 0); ...@@ -1827,9 +1827,9 @@ buf.writeFloatBE(0xcafebabe, 0);
### writeFloatLE ### writeFloatLE
writeFloatLE(value : number, offset? : number): number writeFloatLE(value: number, offset?: number): number
Writes a 32-bit, little-endian floating-point number to this **Buffer** instance at the specified offset. Writes a little-endian single-precision floating-point number to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -1838,7 +1838,7 @@ Writes a 32-bit, little-endian floating-point number to this **Buffer** instance ...@@ -1838,7 +1838,7 @@ Writes a 32-bit, little-endian floating-point number to this **Buffer** instance
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1858,7 +1858,7 @@ buf.writeFloatLE(0xcafebabe, 0); ...@@ -1858,7 +1858,7 @@ buf.writeFloatLE(0xcafebabe, 0);
### writeInt8 ### writeInt8
writeInt8(value : number, offset? : number): number writeInt8(value: number, offset?: number): number
Writes a signed 8-bit integer to this **Buffer** instance at the specified offset. Writes a signed 8-bit integer to this **Buffer** instance at the specified offset.
...@@ -1869,7 +1869,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse ...@@ -1869,7 +1869,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1891,7 +1891,7 @@ buf.writeInt8(-2, 1); ...@@ -1891,7 +1891,7 @@ buf.writeInt8(-2, 1);
### writeInt16BE ### writeInt16BE
writeInt16BE(value : number, offset? : number): number writeInt16BE(value: number, offset?: number): number
Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset. Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset.
...@@ -1902,7 +1902,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp ...@@ -1902,7 +1902,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1923,7 +1923,7 @@ buf.writeInt16BE(0x0102, 0); ...@@ -1923,7 +1923,7 @@ buf.writeInt16BE(0x0102, 0);
### writeInt16LE ### writeInt16LE
writeInt16LE(value : number, offset : number): number writeInt16LE(value: number, offset?: number): number
Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset. Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset.
...@@ -1934,7 +1934,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the ...@@ -1934,7 +1934,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1954,7 +1954,7 @@ buf.writeInt16LE(0x0304, 0); ...@@ -1954,7 +1954,7 @@ buf.writeInt16LE(0x0304, 0);
### writeInt32BE ### writeInt32BE
writeInt32BE(value : number, offset : number): number writeInt32BE(value: number, offset?: number): number
Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset. Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset.
...@@ -1965,7 +1965,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp ...@@ -1965,7 +1965,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -1986,7 +1986,7 @@ buf.writeInt32BE(0x01020304, 0); ...@@ -1986,7 +1986,7 @@ buf.writeInt32BE(0x01020304, 0);
### writeInt32LE ### writeInt32LE
writeInt32LE(value : number, offset : number): number writeInt32LE(value: number, offset?: number): number
Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset. Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset.
...@@ -1997,7 +1997,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the ...@@ -1997,7 +1997,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2017,7 +2017,7 @@ buf.writeInt32LE(0x05060708, 0); ...@@ -2017,7 +2017,7 @@ buf.writeInt32LE(0x05060708, 0);
### writeIntBE ### writeIntBE
writeIntBE(value : number, offset : number, byteLength : number): number writeIntBE(value: number, offset: number, byteLength: number): number
Writes a big-endian signed value of the specified length to this **Buffer** instance at the specified offset. Writes a big-endian signed value of the specified length to this **Buffer** instance at the specified offset.
...@@ -2028,8 +2028,8 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst ...@@ -2028,8 +2028,8 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.|
| byteLength | number | No| Number of bytes to write.| | byteLength | number | Yes| Number of bytes to write.|
**Return value** **Return value**
...@@ -2050,7 +2050,7 @@ buf.writeIntBE(0x1234567890ab, 0, 6); ...@@ -2050,7 +2050,7 @@ buf.writeIntBE(0x1234567890ab, 0, 6);
### writeIntLE ### writeIntLE
writeIntLE(value : number, offset : number, byteLength : number): number writeIntLE(value: number, offset: number, byteLength: number): number
Writes a little-endian signed value of the specified length to this **Buffer** instance at the specified offset. Writes a little-endian signed value of the specified length to this **Buffer** instance at the specified offset.
...@@ -2061,8 +2061,8 @@ Writes a little-endian signed value of the specified length to this **Buffer** i ...@@ -2061,8 +2061,8 @@ Writes a little-endian signed value of the specified length to this **Buffer** i
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.|
| byteLength | number | No| Number of bytes to write.| | byteLength | number | Yes| Number of bytes to write.|
**Return value** **Return value**
...@@ -2082,7 +2082,7 @@ buf.writeIntLE(0x1234567890ab, 0, 6); ...@@ -2082,7 +2082,7 @@ buf.writeIntLE(0x1234567890ab, 0, 6);
### writeUInt8 ### writeUInt8
writeUInt8(value : number, offset : number): number writeUInt8(value: number, offset?: number): number
Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset.
...@@ -2093,7 +2093,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of ...@@ -2093,7 +2093,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2116,7 +2116,7 @@ buf.writeUInt8(0x42, 3); ...@@ -2116,7 +2116,7 @@ buf.writeUInt8(0x42, 3);
### writeUInt16BE ### writeUInt16BE
writeUInt16BE(value : number, offset : number): number writeUInt16BE(value: number, offset?: number): number
Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset.
...@@ -2127,7 +2127,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the ...@@ -2127,7 +2127,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2148,7 +2148,7 @@ buf.writeUInt16BE(0xbeef, 2); ...@@ -2148,7 +2148,7 @@ buf.writeUInt16BE(0xbeef, 2);
### writeUInt16LE ### writeUInt16LE
writeUInt16LE(value : number, offset : number): number writeUInt16LE(value: number, offset?: number): number
Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset.
...@@ -2159,7 +2159,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at ...@@ -2159,7 +2159,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2180,7 +2180,7 @@ buf.writeUInt16LE(0xbeef, 2); ...@@ -2180,7 +2180,7 @@ buf.writeUInt16LE(0xbeef, 2);
### writeUInt32BE ### writeUInt32BE
writeUInt32BE(value : number, offset : number): number writeUInt32BE(value: number, offset?: number): number
Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset.
...@@ -2191,7 +2191,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the ...@@ -2191,7 +2191,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2211,7 +2211,7 @@ buf.writeUInt32BE(0xfeedface, 0); ...@@ -2211,7 +2211,7 @@ buf.writeUInt32BE(0xfeedface, 0);
### writeUInt32LE ### writeUInt32LE
writeUInt32LE(value : number, offset : number): number writeUInt32LE(value: number, offset?: number): number
Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset. Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset.
...@@ -2221,8 +2221,8 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at ...@@ -2221,8 +2221,8 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Number to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.|
**Return value** **Return value**
...@@ -2242,9 +2242,9 @@ buf.writeUInt32LE(0xfeedface, 0); ...@@ -2242,9 +2242,9 @@ buf.writeUInt32LE(0xfeedface, 0);
### writeUIntBE ### writeUIntBE
writeUIntBE(value : number, offset : number, byteLength : number): number writeUIntBE(value: number, offset: number, byteLength: number): number
Writes a big-endian unsigned value of the specified length to this **Buffer** instance at the specified offset. Writes an unsigned big-endian value of the specified length to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -2253,8 +2253,8 @@ Writes a big-endian unsigned value of the specified length to this **Buffer** in ...@@ -2253,8 +2253,8 @@ Writes a big-endian unsigned value of the specified length to this **Buffer** in
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.|
| byteLength | number | No| Number of bytes to write.| | byteLength | number | Yes| Number of bytes to write.|
**Return value** **Return value**
...@@ -2274,9 +2274,9 @@ buf.writeUIntBE(0x1234567890ab, 0, 6); ...@@ -2274,9 +2274,9 @@ buf.writeUIntBE(0x1234567890ab, 0, 6);
### writeUIntLE ### writeUIntLE
writeUIntLE(value : number, offset : number, byteLength : number): number writeUIntLE(value: number, offset: number, byteLength: number): number
Writes a little-endian unsigned value of the specified length to this **Buffer** instance at the specified offset. Writes an unsigned little-endian value of the specified length to this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
...@@ -2285,8 +2285,8 @@ Writes a little-endian unsigned value of the specified length to this **Buffer** ...@@ -2285,8 +2285,8 @@ Writes a little-endian unsigned value of the specified length to this **Buffer**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Data to write.| | value | number | Yes| Data to write.|
| offset | number | No| Number of bytes to skip before writing data. The default value is **0**.| | offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.|
| byteLength | number | No| Number of bytes to write.| | byteLength | number | Yes| Number of bytes to write.|
**Return value** **Return value**
...@@ -2306,7 +2306,7 @@ buf.writeUIntLE(0x1234567890ab, 0, 6); ...@@ -2306,7 +2306,7 @@ buf.writeUIntLE(0x1234567890ab, 0, 6);
### transcode ### transcode
transcode(source : Buffer | Uint8Array, fromEnc : string, toEnc : string): Buffer transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer
Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another.
...@@ -2316,7 +2316,7 @@ Transcodes the given **Buffer** or **Uint8Array** instance from one encoding for ...@@ -2316,7 +2316,7 @@ Transcodes the given **Buffer** or **Uint8Array** instance from one encoding for
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| source | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Instance to encode.| | source | Buffer&nbsp;\|&nbsp;Uint8Array | Yes| Instance to transcode. |
| fromEnc | string | Yes| Current encoding format.| | fromEnc | string | Yes| Current encoding format.|
| toEnc | string | Yes| Target encoding format.| | toEnc | string | Yes| Target encoding format.|
...@@ -2332,7 +2332,7 @@ Transcodes the given **Buffer** or **Uint8Array** instance from one encoding for ...@@ -2332,7 +2332,7 @@ Transcodes the given **Buffer** or **Uint8Array** instance from one encoding for
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let buf = buffer.alloc(50); let buf = buffer.alloc(50);
let newBuf = buf.transcode(buffer.from(''), 'utf8', 'ascii'); let newBuf = buffer.transcode(buffer.from(''), 'utf-8', 'ascii');
console.log(newBuf.toString('ascii')); console.log(newBuf.toString('ascii'));
``` ```
...@@ -2349,7 +2349,7 @@ console.log(newBuf.toString('ascii')); ...@@ -2349,7 +2349,7 @@ console.log(newBuf.toString('ascii'));
### constructor ### constructor
constructor(sources: string[] | ArrayBuffer[] | TypedArray[] | DataView[] | Blob[] , options: Object) constructor(sources: string[] | ArrayBuffer[] | TypedArray[] | DataView[] | Blob[] , options?: Object)
A constructor used to create a **Blob** instance. A constructor used to create a **Blob** instance.
...@@ -2368,7 +2368,7 @@ A constructor used to create a **Blob** instance. ...@@ -2368,7 +2368,7 @@ A constructor used to create a **Blob** instance.
```ts ```ts
import buffer from '@ohos.buffer'; import buffer from '@ohos.buffer';
let blob1 = new buffer.Blob(['a', 'b', 'c']); let blob = new buffer.Blob(['a', 'b', 'c']);
let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'});
``` ```
...@@ -2390,7 +2390,8 @@ Puts the **Blob** data into an **ArrayBuffer** instance. This API uses a promise ...@@ -2390,7 +2390,8 @@ Puts the **Blob** data into an **ArrayBuffer** instance. This API uses a promise
let blob = new buffer.Blob(['a', 'b', 'c']); let blob = new buffer.Blob(['a', 'b', 'c']);
let pro = blob.arrayBuffer(); let pro = blob.arrayBuffer();
pro.then(val => { pro.then(val => {
console.log(val) let uintarr = new Uint8Array(val);
console.log(uintarr.toString());
}); });
``` ```
### slice ### slice
...@@ -2412,7 +2413,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc ...@@ -2412,7 +2413,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Blob | New **Blob** instance created.| | Blob | **Blob** instance created. |
**Example** **Example**
```ts ```ts
......
...@@ -36,9 +36,16 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul ...@@ -36,9 +36,16 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
**Example** **Example**
FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db"} const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
...@@ -47,6 +54,28 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { ...@@ -47,6 +54,28 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
}) })
``` ```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
```
## data_rdb.getRdbStore ## data_rdb.getRdbStore
getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt; getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt;
...@@ -71,9 +100,38 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -71,9 +100,38 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
**Example** **Example**
FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db" } const STORE_CONFIG = { name: "RdbTest.db" }
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
// Call getRdbStore.
const STORE_CONFIG = { name: "RdbTest.db" }
let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -90,6 +148,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul ...@@ -90,6 +148,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
...@@ -97,8 +156,38 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul ...@@ -97,8 +156,38 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
FA model:
```js ```js
data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
return return
...@@ -116,19 +205,29 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -116,19 +205,29 @@ Deletes an RDB store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
FA model:
```js ```js
let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
...@@ -136,6 +235,26 @@ promise.then(()=>{ ...@@ -136,6 +235,26 @@ promise.then(()=>{
}) })
``` ```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
```
## RdbPredicates ## RdbPredicates
...@@ -152,11 +271,13 @@ A constructor used to create an **RdbPredicates** object. ...@@ -152,11 +271,13 @@ A constructor used to create an **RdbPredicates** object.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Database table name.| | name | string | Yes| Database table name.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
``` ```
...@@ -166,21 +287,24 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -166,21 +287,24 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
inDevices(devices: Array&lt;string&gt;): RdbPredicates inDevices(devices: Array&lt;string&gt;): RdbPredicates
Connects to the specified remote devices on the network during distributed database synchronization. Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| devices | Array&lt;string&gt; | Yes| IDs of the remote devices in the same network.| | devices | Array&lt;string&gt; | Yes| IDs of the remote devices in the same network.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.inDevices(['12345678abcde']) predicates.inDevices(['12345678abcde'])
...@@ -191,16 +315,18 @@ predicates.inDevices(['12345678abcde']) ...@@ -191,16 +315,18 @@ predicates.inDevices(['12345678abcde'])
inAllDevices(): RdbPredicates inAllDevices(): RdbPredicates
Connects to all remote devices on the network during distributed database synchronization. Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.inAllDevices() predicates.inAllDevices()
...@@ -216,17 +342,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va ...@@ -216,17 +342,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi") predicates.equalTo("NAME", "lisi")
...@@ -243,17 +372,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va ...@@ -243,17 +372,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notEqualTo("NAME", "lisi") predicates.notEqualTo("NAME", "lisi")
...@@ -270,11 +402,13 @@ Adds a left parenthesis to the **RdbPredicates**. ...@@ -270,11 +402,13 @@ Adds a left parenthesis to the **RdbPredicates**.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi") predicates.equalTo("NAME", "lisi")
...@@ -285,22 +419,22 @@ predicates.equalTo("NAME", "lisi") ...@@ -285,22 +419,22 @@ predicates.equalTo("NAME", "lisi")
.endWrap() .endWrap()
``` ```
### endWrap ### endWrap
endWrap(): RdbPredicates endWrap(): RdbPredicates
Adds a right parenthesis to the **RdbPredicates**. Adds a right parenthesis to the **RdbPredicates**.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi") predicates.equalTo("NAME", "lisi")
...@@ -311,22 +445,22 @@ predicates.equalTo("NAME", "lisi") ...@@ -311,22 +445,22 @@ predicates.equalTo("NAME", "lisi")
.endWrap() .endWrap()
``` ```
### or ### or
or(): RdbPredicates or(): RdbPredicates
Adds the OR condition to the **RdbPredicates**. Adds the OR condition to the **RdbPredicates**.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
...@@ -334,22 +468,22 @@ predicates.equalTo("NAME", "Lisa") ...@@ -334,22 +468,22 @@ predicates.equalTo("NAME", "Lisa")
.equalTo("NAME", "Rose") .equalTo("NAME", "Rose")
``` ```
### and ### and
and(): RdbPredicates and(): RdbPredicates
Adds the AND condition to the **RdbPredicates**. Adds the AND condition to the **RdbPredicates**.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
...@@ -357,7 +491,6 @@ predicates.equalTo("NAME", "Lisa") ...@@ -357,7 +491,6 @@ predicates.equalTo("NAME", "Lisa")
.equalTo("SALARY", 200.5) .equalTo("SALARY", 200.5)
``` ```
### contains ### contains
contains(field: string, value: string): RdbPredicates contains(field: string, value: string): RdbPredicates
...@@ -367,193 +500,200 @@ Sets an **RdbPredicates** to match a string containing the specified value. ...@@ -367,193 +500,200 @@ Sets an **RdbPredicates** to match a string containing the specified value.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | string | Yes| Value to match the **RdbPredicates**.| | value | string | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.contains("NAME", "os") predicates.contains("NAME", "os")
``` ```
### beginsWith ### beginsWith
beginsWith(field: string, value: string): RdbPredicates beginsWith(field: string, value: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | string | Yes| Value to match the **RdbPredicates**.| | value | string | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.beginsWith("NAME", "os") predicates.beginsWith("NAME", "os")
``` ```
### endsWith ### endsWith
endsWith(field: string, value: string): RdbPredicates endsWith(field: string, value: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | string | Yes| Value to match the **RdbPredicates**.| | value | string | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.endsWith("NAME", "se") predicates.endsWith("NAME", "se")
``` ```
### isNull ### isNull
isNull(field: string): RdbPredicates isNull(field: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
- Example **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNull("NAME") predicates.isNull("NAME")
``` ```
### isNotNull ### isNotNull
isNotNull(field: string): RdbPredicates isNotNull(field: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNotNull("NAME") predicates.isNotNull("NAME")
``` ```
### like ### like
like(field: string, value: string): RdbPredicates like(field: string, value: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | string | Yes| Value to match the **RdbPredicates**.| | value | string | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.like("NAME", "%os%") predicates.like("NAME", "%os%")
``` ```
### glob ### glob
glob(field: string, value: string): RdbPredicates glob(field: string, value: string): RdbPredicates
Sets an **RdbPredicates** to match the specified string. Sets an **RdbPredicates** to match the specified string.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | string | Yes| Value to match the **RdbPredicates**.<br><br>Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| | value | string | Yes| Value to match the **RdbPredicates**.<br><br>Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.glob("NAME", "?h*g") predicates.glob("NAME", "?h*g")
``` ```
### between ### between
between(field: string, low: ValueType, high: ValueType): RdbPredicates between(field: string, low: ValueType, high: ValueType): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
...@@ -561,27 +701,28 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va ...@@ -561,27 +701,28 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va
| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.between("AGE", 10, 50) predicates.between("AGE", 10, 50)
``` ```
### notBetween ### notBetween
notBetween(field: string, low: ValueType, high: ValueType): 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. Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
...@@ -589,17 +730,18 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va ...@@ -589,17 +730,18 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va
| high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notBetween("AGE", 10, 50) predicates.notBetween("AGE", 10, 50)
``` ```
### greaterThan ### greaterThan
greaterThan(field: string, value: ValueType): RdbPredicates greaterThan(field: string, value: ValueType): RdbPredicates
...@@ -609,259 +751,265 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va ...@@ -609,259 +751,265 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThan("AGE", 18) predicates.greaterThan("AGE", 18)
``` ```
### lessThan ### lessThan
lessThan(field: string, value: ValueType): 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. Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThan("AGE", 20) predicates.lessThan("AGE", 20)
``` ```
### greaterThanOrEqualTo ### greaterThanOrEqualTo
greaterThanOrEqualTo(field: string, value: ValueType): 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. 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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThanOrEqualTo("AGE", 18) predicates.greaterThanOrEqualTo("AGE", 18)
``` ```
### lessThanOrEqualTo ### lessThanOrEqualTo
lessThanOrEqualTo(field: string, value: ValueType): 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. 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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThanOrEqualTo("AGE", 20) predicates.lessThanOrEqualTo("AGE", 20)
``` ```
### orderByAsc ### orderByAsc
orderByAsc(field: string): RdbPredicates orderByAsc(field: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByAsc("NAME") predicates.orderByAsc("NAME")
``` ```
### orderByDesc ### orderByDesc
orderByDesc(field: string): RdbPredicates orderByDesc(field: string): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByDesc("AGE") predicates.orderByDesc("AGE")
``` ```
### distinct ### distinct
distinct(): RdbPredicates distinct(): RdbPredicates
Sets an **RdbPredicates** to filter out duplicate records. Sets an **RdbPredicates** to filter out duplicate records.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct("NAME") predicates.equalTo("NAME", "Rose").distinct()
``` ```
### limitAs ### limitAs
limitAs(value: number): RdbPredicates limitAs(value: number): RdbPredicates
Sets an **RdbPredicates** to specify the maximum number of records. Sets an **RdbPredicates** to specify the maximum number of records.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| value | number | Yes| Maximum number of records.| | value | number | Yes| Maximum number of records.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").limitAs(3) predicates.equalTo("NAME", "Rose").limitAs(3)
``` ```
### offsetAs ### offsetAs
offsetAs(rowOffset: number): RdbPredicates offsetAs(rowOffset: number): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").offsetAs(3) predicates.equalTo("NAME", "Rose").offsetAs(3)
``` ```
### groupBy ### groupBy
groupBy(fields: Array&lt;string&gt;): RdbPredicates groupBy(fields: Array&lt;string&gt;): RdbPredicates
Sets an **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 **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fields | Array&lt;string&gt; | Yes| Names of columns to group.| | fields | Array&lt;string&gt; | Yes| Names of columns to group.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.groupBy(["AGE", "NAME"]) predicates.groupBy(["AGE", "NAME"])
``` ```
### indexedBy ### indexedBy
indexedBy(field: string): RdbPredicates indexedBy(field: string): RdbPredicates
...@@ -871,86 +1019,87 @@ Sets an **RdbPredicates** object to specify the index column. ...@@ -871,86 +1019,87 @@ Sets an **RdbPredicates** object to specify the index column.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Name of the index column.| | field | string | Yes| Name of the index column.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.indexedBy("SALARY_INDEX") predicates.indexedBy("SALARY_INDEX")
``` ```
### in ### in
in(field: string, value: Array&lt;ValueType&gt;): RdbPredicates in(field: string, value: Array&lt;ValueType&gt;): RdbPredicates
Sets an **RdbPredicates** to match the field with data type **Array&#60;ValueType&#62;** and value within the specified range. Sets an **RdbPredicates** to match the field with data type **Array&#60;ValueType&#62;** and value within the specified range.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | Array&lt;[ValueType](#valuetype)&gt; | Yes| Array of **ValueType**s to match.| | value | Array&lt;[ValueType](#valuetype)&gt; | Yes| Array of **ValueType**s to match.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.in("AGE", [18, 20]) predicates.in("AGE", [18, 20])
``` ```
### notIn ### notIn
notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicates notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicates
Sets an **RdbPredicates** to match the field with data type **Array&#60;ValueType&#62;** and value out of the specified range. Sets an **RdbPredicates** to match the field with data type **Array&#60;ValueType&#62;** and value out of the specified range.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| field | string | Yes| Column name in the database table.| | field | string | Yes| Column name in the database table.|
| value | Array&lt;[ValueType](#valuetype)&gt; | Yes| Array of **ValueType**s to match.| | value | Array&lt;[ValueType](#valuetype)&gt; | Yes| Array of **ValueType**s to match.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notIn("NAME", ["Lisa", "Rose"]) predicates.notIn("NAME", ["Lisa", "Rose"])
``` ```
## RdbStore ## RdbStore
Provides methods to manage an RDB store. Provides methods to manage an RDB store.
Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md).
### insert ### insert
insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void
...@@ -960,6 +1109,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re ...@@ -960,6 +1109,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -967,6 +1117,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re ...@@ -967,6 +1117,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
**Example** **Example**
```js ```js
const valueBucket = { const valueBucket = {
"NAME": "Lisa", "NAME": "Lisa",
...@@ -983,7 +1134,6 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { ...@@ -983,7 +1134,6 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) {
}) })
``` ```
### insert ### insert
insert(table: string, values: ValuesBucket):Promise&lt;number&gt; insert(table: string, values: ValuesBucket):Promise&lt;number&gt;
...@@ -993,17 +1143,20 @@ Inserts a row of data into a table. This API uses a promise to return the result ...@@ -993,17 +1143,20 @@ Inserts a row of data into a table. This API uses a promise to return the result
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| | Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.|
**Example** **Example**
```js ```js
const valueBucket = { const valueBucket = {
"NAME": "Lisa", "NAME": "Lisa",
...@@ -1028,6 +1181,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur ...@@ -1028,6 +1181,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1035,6 +1189,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur ...@@ -1035,6 +1189,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| | callback | AsyncCallback&lt;number&gt; | 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** **Example**
```js ```js
const valueBucket1 = { const valueBucket1 = {
"NAME": "Lisa", "NAME": "Lisa",
...@@ -1074,17 +1229,20 @@ Batch inserts data into a table. This API uses a promise to return the result. ...@@ -1074,17 +1229,20 @@ Batch inserts data into a table. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | Yes| An array of data to insert.| | values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | Yes| An array of data to insert.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| | Promise&lt;number&gt; | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.|
**Example** **Example**
```js ```js
const valueBucket1 = { const valueBucket1 = {
"NAME": "Lisa", "NAME": "Lisa",
...@@ -1123,13 +1281,15 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T ...@@ -1123,13 +1281,15 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
const valueBucket = { const valueBucket = {
"NAME": "Rose", "NAME": "Rose",
...@@ -1148,7 +1308,6 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { ...@@ -1148,7 +1308,6 @@ rdbStore.update(valueBucket, predicates, function (err, ret) {
}) })
``` ```
### update ### update
update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt; update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt;
...@@ -1158,17 +1317,20 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr ...@@ -1158,17 +1317,20 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
const valueBucket = { const valueBucket = {
"NAME": "Rose", "NAME": "Rose",
...@@ -1191,9 +1353,12 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data ...@@ -1191,9 +1353,12 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data
Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1202,6 +1367,7 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj ...@@ -1202,6 +1367,7 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
const valueBucket = { const valueBucket = {
...@@ -1220,15 +1386,19 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { ...@@ -1220,15 +1386,19 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
console.log("Updated row count: " + ret) console.log("Updated row count: " + ret)
}) })
``` ```
### update<sup>9+</sup> ### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt; update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1236,11 +1406,13 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj ...@@ -1236,11 +1406,13 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
const valueBucket = { const valueBucket = {
...@@ -1263,18 +1435,19 @@ promise.then(async (ret) => { ...@@ -1263,18 +1435,19 @@ promise.then(async (ret) => {
delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
...@@ -1287,7 +1460,6 @@ rdbStore.delete(predicates, function (err, rows) { ...@@ -1287,7 +1460,6 @@ rdbStore.delete(predicates, function (err, rows) {
}) })
``` ```
### delete ### delete
delete(predicates: RdbPredicates):Promise&lt;number&gt; delete(predicates: RdbPredicates):Promise&lt;number&gt;
...@@ -1297,16 +1469,19 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. ...@@ -1297,16 +1469,19 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
...@@ -1322,12 +1497,14 @@ promise.then((rows) => { ...@@ -1322,12 +1497,14 @@ promise.then((rows) => {
delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1335,6 +1512,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o ...@@ -1335,6 +1512,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates() let predicates = new dataSharePredicates.DataSharePredicates()
...@@ -1347,26 +1525,32 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { ...@@ -1347,26 +1525,32 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) {
console.log("Deleted rows: " + rows) console.log("Deleted rows: " + rows)
}) })
``` ```
### delete<sup>9+</sup> ### delete<sup>9+</sup>
delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt; delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates() let predicates = new dataSharePredicates.DataSharePredicates()
...@@ -1388,6 +1572,7 @@ Queries data from the RDB store based on specified conditions. This API uses an ...@@ -1388,6 +1572,7 @@ Queries data from the RDB store based on specified conditions. This API uses an
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.|
...@@ -1395,6 +1580,7 @@ Queries data from the RDB store based on specified conditions. This API uses an ...@@ -1395,6 +1580,7 @@ Queries data from the RDB store based on specified conditions. This API uses an
| callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose") predicates.equalTo("NAME", "Rose")
...@@ -1408,7 +1594,6 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e ...@@ -1408,7 +1594,6 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e
}) })
``` ```
### query ### query
query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
...@@ -1418,17 +1603,20 @@ Queries data from the RDB store based on specified conditions. This API uses a p ...@@ -1418,17 +1603,20 @@ Queries data from the RDB store based on specified conditions. This API uses a p
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.|
| columns | Array&lt;string&gt; | No| Columns to query. If this parameter is not specified, the query applies to all columns.| | columns | Array&lt;string&gt; | No| Columns to query. If this parameter is not specified, the query applies to all columns.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| | Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose") predicates.equalTo("NAME", "Rose")
...@@ -1447,9 +1635,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column ...@@ -1447,9 +1635,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column
Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1479,9 +1670,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column ...@@ -1479,9 +1670,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column
Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
...@@ -1495,6 +1689,7 @@ Queries data from the RDB store based on specified conditions. This API uses a p ...@@ -1495,6 +1689,7 @@ Queries data from the RDB store based on specified conditions. This API uses a p
| Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| | Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Example** **Example**
```js ```js
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates'
let predicates = new dataSharePredicates.DataSharePredicates() let predicates = new dataSharePredicates.DataSharePredicates()
...@@ -1529,9 +1724,10 @@ Queries data from the RDB store of a remote device based on specified conditions ...@@ -1529,9 +1724,10 @@ Queries data from the RDB store of a remote device based on specified conditions
**Example** **Example**
```js ```js
let predicates = new rdb.RdbPredicates('EMPLOYEE') let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0)
rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, function(err, resultSet){ rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
function(err, resultSet){
if (err) { if (err) {
console.info("Failed to remoteQuery, err: " + err) console.info("Failed to remoteQuery, err: " + err)
return return
...@@ -1567,9 +1763,9 @@ Queries data from the RDB store of a remote device based on specified conditions ...@@ -1567,9 +1763,9 @@ Queries data from the RDB store of a remote device based on specified conditions
**Example** **Example**
```js ```js
let predicates = new rdb.RdbPredicates('EMPLOYEE') let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0)
let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates) let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"])
promise.then((resultSet) => { promise.then((resultSet) => {
console.info("ResultSet column names: " + resultSet.columnNames) console.info("ResultSet column names: " + resultSet.columnNames)
console.info("ResultSet column count: " + resultSet.columnCount) console.info("ResultSet column count: " + resultSet.columnCount)
...@@ -1587,6 +1783,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ...@@ -1587,6 +1783,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sql | string | Yes| SQL statement to run.| | sql | string | Yes| SQL statement to run.|
...@@ -1594,6 +1791,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ...@@ -1594,6 +1791,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a
| callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | callback | AsyncCallback&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Example** **Example**
```js ```js
rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) {
if (err) { if (err) {
...@@ -1605,7 +1803,6 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ...@@ -1605,7 +1803,6 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?",
}) })
``` ```
### querySql<sup>8+</sup> ### querySql<sup>8+</sup>
querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt;
...@@ -1615,17 +1812,20 @@ Queries data in the RDB store using the specified SQL statement. This API uses a ...@@ -1615,17 +1812,20 @@ Queries data in the RDB store using the specified SQL statement. This API uses a
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sql | string | Yes| SQL statement to run.| | sql | string | Yes| SQL statement to run.|
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | No| Arguments in the SQL statement.| | bindArgs | Array&lt;[ValueType](#valuetype)&gt; | No| Arguments in the SQL statement.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| | Promise&lt;[ResultSet](js-apis-data-resultset.md)&gt; | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.|
**Example** **Example**
```js ```js
let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'])
promise.then((resultSet) => { promise.then((resultSet) => {
...@@ -1636,7 +1836,6 @@ promise.then((resultSet) => { ...@@ -1636,7 +1836,6 @@ promise.then((resultSet) => {
}) })
``` ```
### executeSql ### executeSql
executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void
...@@ -1646,6 +1845,7 @@ Executes an SQL statement that contains specified arguments but returns no value ...@@ -1646,6 +1845,7 @@ Executes an SQL statement that contains specified arguments but returns no value
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sql | string | Yes| SQL statement to run.| | sql | string | Yes| SQL statement to run.|
...@@ -1653,6 +1853,7 @@ Executes an SQL statement that contains specified arguments but returns no value ...@@ -1653,6 +1853,7 @@ Executes an SQL statement that contains specified arguments but returns no value
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
```js ```js
const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)"
rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) {
...@@ -1664,7 +1865,6 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { ...@@ -1664,7 +1865,6 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) {
}) })
``` ```
### executeSql ### executeSql
executeSql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;void&gt; executeSql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;void&gt;
...@@ -1674,17 +1874,20 @@ Executes an SQL statement that contains specified arguments but returns no value ...@@ -1674,17 +1874,20 @@ Executes an SQL statement that contains specified arguments but returns no value
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| sql | string | Yes| SQL statement to run.| | sql | string | Yes| SQL statement to run.|
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | No| Arguments in the SQL statement.| | bindArgs | Array&lt;[ValueType](#valuetype)&gt; | No| Arguments in the SQL statement.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)"
let promise = rdbStore.executeSql(SQL_CREATE_TABLE) let promise = rdbStore.executeSql(SQL_CREATE_TABLE)
...@@ -1704,19 +1907,24 @@ Starts the transaction before executing an SQL statement. ...@@ -1704,19 +1907,24 @@ Starts the transaction before executing an SQL statement.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Example** **Example**
```js ```js
rdbStore.beginTransaction() import featureAbility from '@ohos.ability.featureAbility'
const valueBucket = { var context = featureAbility.getContext()
const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
rdbStore.beginTransaction()
const valueBucket = {
"name": "lisi", "name": "lisi",
"age": 18, "age": 18,
"salary": 100.5, "salary": 100.5,
"blobType": new Uint8Array([1, 2, 3]), "blobType": new Uint8Array([1, 2, 3]),
} }
await rdbStore.insert("test", valueBucket) await rdbStore.insert("test", valueBucket)
rdbStore.commit() rdbStore.commit()
})
``` ```
### commit<sup>8+</sup> ### commit<sup>8+</sup>
commit():void commit():void
...@@ -1726,20 +1934,24 @@ Commits the executed SQL statements. ...@@ -1726,20 +1934,24 @@ Commits the executed SQL statements.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Example** **Example**
```js ```js
rdbStore.beginTransaction() import featureAbility from '@ohos.ability.featureAbility'
const valueBucket = { var context = featureAbility.getContext()
const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
rdbStore.beginTransaction()
const valueBucket = {
"name": "lisi", "name": "lisi",
"age": 18, "age": 18,
"salary": 100.5, "salary": 100.5,
"blobType": new Uint8Array([1, 2, 3]), "blobType": new Uint8Array([1, 2, 3]),
} }
await rdbStore.insert("test", valueBucket)
await rdbStore.insert("test", valueBucket) rdbStore.commit()
rdbStore.commit() })
``` ```
### rollBack<sup>8+</sup> ### rollBack<sup>8+</sup>
rollBack():void rollBack():void
...@@ -1749,8 +1961,13 @@ Rolls back the SQL statements that have been executed. ...@@ -1749,8 +1961,13 @@ Rolls back the SQL statements that have been executed.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Example** **Example**
```js ```js
try { import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
try {
rdbStore.beginTransaction() rdbStore.beginTransaction()
const valueBucket = { const valueBucket = {
"id": 1, "id": 1,
...@@ -1761,9 +1978,10 @@ try { ...@@ -1761,9 +1978,10 @@ try {
} }
await rdbStore.insert("test", valueBucket) await rdbStore.insert("test", valueBucket)
rdbStore.commit() rdbStore.commit()
} catch (e) { } catch (e) {
rdbStore.rollBack() rdbStore.rollBack()
} }
})
``` ```
### backup<sup>9+</sup> ### backup<sup>9+</sup>
...@@ -1775,12 +1993,14 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu ...@@ -1775,12 +1993,14 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the RDB store backup file.| | destName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
```js ```js
rdbStore.backup("dbBackup.db", function(err) { rdbStore.backup("dbBackup.db", function(err) {
if (err) { if (err) {
...@@ -1800,16 +2020,19 @@ Backs up an RDB store. This API uses a promise to return the result. ...@@ -1800,16 +2020,19 @@ Backs up an RDB store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the RDB store backup file.| | destName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(()=>{ promiseBackup.then(()=>{
...@@ -1828,12 +2051,14 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback ...@@ -1828,12 +2051,14 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the RDB store backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
```js ```js
rdbStore.restore("dbBackup.db", function(err) { rdbStore.restore("dbBackup.db", function(err) {
if (err) { if (err) {
...@@ -1853,16 +2078,19 @@ Restores an RDB store from a backup file. This API uses a promise to return the ...@@ -1853,16 +2078,19 @@ Restores an RDB store from a backup file. This API uses a promise to return the
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the RDB store backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(()=>{ promiseRestore.then(()=>{
...@@ -1883,12 +2111,14 @@ Sets distributed tables. This API uses an asynchronous callback to return the re ...@@ -1883,12 +2111,14 @@ Sets distributed tables. This API uses an asynchronous callback to return the re
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| tables | Array&lt;string&gt; | Yes| Names of the distributed tables to set.| | tables | Array&lt;string&gt; | Yes| Names of the distributed tables to set.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
```js ```js
rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
if (err) { if (err) {
...@@ -1899,7 +2129,6 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { ...@@ -1899,7 +2129,6 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
}) })
``` ```
### setDistributedTables<sup>8+</sup> ### setDistributedTables<sup>8+</sup>
setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt; setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt;
...@@ -1911,22 +2140,25 @@ Sets distributed tables. This API uses a promise to return the result. ...@@ -1911,22 +2140,25 @@ Sets distributed tables. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| tables | Array&lt;string&gt; | Yes| Names of the distributed tables to set.| | tables | Array&lt;string&gt; | Yes| Names of the distributed tables to set.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) let promise = rdbStore.setDistributedTables(["EMPLOYEE"])
promise.then(() => { promise.then(() => {
console.info("Set distributed tables successfully.") console.info("Set distributed tables successfully.")
}).catch((err) => { }).catch((err) => {
console.info('Failed to set distributed tables, err: ' + err) console.info("Failed to set distributed tables, err: " + err)
}) })
``` ```
...@@ -1941,6 +2173,7 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1941,6 +2173,7 @@ Obtains the distributed table name for a remote device based on the local table
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| device | string | Yes| Remote device.| | device | string | Yes| Remote device.|
...@@ -1948,6 +2181,7 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1948,6 +2181,7 @@ Obtains the distributed table name for a remote device based on the local table
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| | callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.|
**Example** **Example**
```js ```js
rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) {
if (err) { if (err) {
...@@ -1958,7 +2192,6 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, ...@@ -1958,7 +2192,6 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err,
}) })
``` ```
### obtainDistributedTableName<sup>8+</sup> ### obtainDistributedTableName<sup>8+</sup>
obtainDistributedTableName(device: string, table: string): Promise&lt;string&gt; obtainDistributedTableName(device: string, table: string): Promise&lt;string&gt;
...@@ -1970,17 +2203,20 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1970,17 +2203,20 @@ Obtains the distributed table name for a remote device based on the local table
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| device | string | Yes| Remote device.| | device | string | Yes| Remote device.|
| table | string | Yes| Local table name.| | table | string | Yes| Local table name.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| | Promise&lt;string&gt; | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.|
**Example** **Example**
```js ```js
let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE")
promise.then((tableName) => { promise.then((tableName) => {
...@@ -2001,6 +2237,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret ...@@ -2001,6 +2237,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.|
...@@ -2008,6 +2245,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret ...@@ -2008,6 +2245,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret
| callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | Yes| Callback invoked to send the synchronization result to the caller. <br>**string** indicates the device ID. <br>**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | | callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | Yes| Callback invoked to send the synchronization result to the caller. <br>**string** indicates the device ID. <br>**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. |
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates('EMPLOYEE') let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.inDevices(['12345678abcde']) predicates.inDevices(['12345678abcde'])
...@@ -2023,7 +2261,6 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul ...@@ -2023,7 +2261,6 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul
}) })
``` ```
### sync<sup>8+</sup> ### sync<sup>8+</sup>
sync(mode: SyncMode, predicates: RdbPredicates): Promise&lt;Array&lt;[string, number]&gt;&gt; sync(mode: SyncMode, predicates: RdbPredicates): Promise&lt;Array&lt;[string, number]&gt;&gt;
...@@ -2035,6 +2272,7 @@ Synchronizes data between devices. This API uses a promise to return the result. ...@@ -2035,6 +2272,7 @@ Synchronizes data between devices. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.|
...@@ -2047,6 +2285,7 @@ Synchronizes data between devices. This API uses a promise to return the result. ...@@ -2047,6 +2285,7 @@ Synchronizes data between devices. This API uses a promise to return the result.
| Promise&lt;Array&lt;[string, number]&gt;&gt; | Promise used to return the synchronization result to the caller. <br>**string** indicates the device ID. <br>**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | | Promise&lt;Array&lt;[string, number]&gt;&gt; | Promise used to return the synchronization result to the caller. <br>**string** indicates the device ID. <br>**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. |
**Example** **Example**
```js ```js
let predicates = new data_rdb.RdbPredicates('EMPLOYEE') let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.inDevices(['12345678abcde']) predicates.inDevices(['12345678abcde'])
...@@ -2080,6 +2319,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes ...@@ -2080,6 +2319,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes| Observer that listens for the data changes in the RDB store.| | observer | Callback&lt;Array&lt;string&gt;&gt; | Yes| Observer that listens for the data changes in the RDB store.|
**Example** **Example**
```js ```js
function storeObserver(devices) { function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
...@@ -2112,6 +2352,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses ...@@ -2112,6 +2352,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses
| observer | Callback&lt;Array&lt;string&gt;&gt; | Yes| Data change observer registered.| | observer | Callback&lt;Array&lt;string&gt;&gt; | Yes| Data change observer registered.|
**Example** **Example**
```js ```js
function storeObserver(devices) { function storeObserver(devices) {
for (let i = 0; i < devices.length; i++) { for (let i = 0; i < devices.length; i++) {
...@@ -2127,14 +2368,14 @@ try { ...@@ -2127,14 +2368,14 @@ try {
## StoreConfig ## StoreConfig
Manages the configuration of an RDB store. Defines the RDB store configuration.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Database file name.| | name | string | Yes| Database file name.|
| encrypt<sup>9+</sup> | boolean | No| Whether to encrypt the RDB store.<br>The value **true** means to encrypt the RDB store, and the value **false** means the opposite.|
## ValueType ## ValueType
......
...@@ -59,8 +59,8 @@ Enumerates the error codes. ...@@ -59,8 +59,8 @@ Enumerates the error codes.
| HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| | HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.|
| HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| | HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.|
| HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| | HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.|
| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the current user.| | HUKS_ERROR_GET_USERIAM_SECINFO_FAILED<sup>9+</sup> | -40 |Failed to obtain the security attribute information of the user.|
| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the current user.| | HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED<sup>9+</sup> | -41 |Failed to obtain the authentication information of the user.|
| HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.| | HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT<sup>9+</sup> | -42 |The access control of the current authentication type is not supported.|
| HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.| | HUKS_ERROR_KEY_AUTH_FAILED<sup>9+</sup> | -43 |The access control authentication has failed.|
| HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.| | HUKS_ERROR_DEVICE_NO_CREDENTIAL<sup>9+</sup> | -44 |No credential has been enrolled for the device.|
...@@ -154,7 +154,7 @@ Enumerates the cipher modes. ...@@ -154,7 +154,7 @@ Enumerates the cipher modes.
| Name | Value | Description | | Name | Value | Description |
| ------------- | ---- | --------------------- | | ------------- | ---- | --------------------- |
| HUKS_MODE_ECB | 1 | Electronic Code bLock (ECB) mode| | HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode|
| HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| | HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode|
| HUKS_MODE_CTR | 3 | Counter (CTR) mode| | HUKS_MODE_CTR | 3 | Counter (CTR) mode|
| HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| | HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode|
...@@ -297,7 +297,7 @@ Enumerates the user authentication types. ...@@ -297,7 +297,7 @@ Enumerates the user authentication types.
## HuksAuthAccessType<sup>9+</sup> ## HuksAuthAccessType<sup>9+</sup>
Enumerates access control types. Enumerates the access control types.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -320,7 +320,7 @@ Enumerates the types of the challenges generated when a key is used. ...@@ -320,7 +320,7 @@ Enumerates the types of the challenges generated when a key is used.
## HuksChallengePosition<sup>9+</sup> ## HuksChallengePosition<sup>9+</sup>
Enumerates the positions of the 8-byte custom challenges. Enumerates the positions of the 8-byte valid value in a custom challenge generated.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -364,7 +364,7 @@ Enumerates the tags used to invoke parameters. ...@@ -364,7 +364,7 @@ Enumerates the tags used to invoke parameters.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Value | Description | | Name | Value | Description |
| -------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------ | | -------------------------------------------- | ---------------------------------------- | -------------------------------------- |
| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | | HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. |
| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | | HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. |
| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | | HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. |
...@@ -399,13 +399,13 @@ Enumerates the tags used to invoke parameters. ...@@ -399,13 +399,13 @@ Enumerates the tags used to invoke parameters.
| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | | HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. |
| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | | HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. |
| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | | HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. |
| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE**. | | HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.|
| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | | HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. |
| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | | HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. |
| HUKS_TAG_KEY_AUTH_ACCESS_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9). | | HUKS_TAG_KEY_AUTH_ACCESS_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).|
| HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported. | | HUKS_TAG_KEY_SECURE_SIGN_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.|
| HUKS_TAG_CHALLENGE_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9). | | HUKS_TAG_CHALLENGE_TYPE<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).|
| HUKS_TAG_CHALLENGE_POS<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-bypte custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9). | | HUKS_TAG_CHALLENGE_POS<sup>9+</sup> | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).|
| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | | HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. |
| HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | | HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | | HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. |
...@@ -421,7 +421,7 @@ Enumerates the tags used to invoke parameters. ...@@ -421,7 +421,7 @@ Enumerates the tags used to invoke parameters.
| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | | HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. |
| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | | HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. |
| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | | HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. |
| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation. | | HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.|
| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | | HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. |
| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | | HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. |
| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | | HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. |
...@@ -502,7 +502,7 @@ huks.generateKey(keyAlias, options, function (err, data){}); ...@@ -502,7 +502,7 @@ huks.generateKey(keyAlias, options, function (err, data){});
generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Generates a key. This API uses a promise to return the result asynchronously. Generates a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -580,7 +580,7 @@ huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); ...@@ -580,7 +580,7 @@ huks.deleteKey(keyAlias, emptyOptions, function (err, data) {});
deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Deletes a key. This API uses a promise to return the result asynchronously. Deletes a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -700,7 +700,7 @@ huks.importKey(keyAlias, options, function (err, data){}); ...@@ -700,7 +700,7 @@ huks.importKey(keyAlias, options, function (err, data){});
importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Imports a key in plaintext. This API uses a promise to return the result asynchronously. Imports a key in plaintext. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -798,6 +798,51 @@ function printLog(...data) { ...@@ -798,6 +798,51 @@ function printLog(...data) {
console.error(data.toString()); console.error(data.toString());
} }
async function generateKey(alias) {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
await huks.generateKey(alias, options).then(async (data) => {
console.error(`generateKey data ${JSON.stringify(data)}`);
}).catch((err) => {
console.error(`generateKey err: " + ${JSON.stringify(err)}`);
});;
}
async function attestKey() { async function attestKey() {
let aliasString = keyAliasString; let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString); let aliasUint8 = stringToUint8Array(aliasString);
...@@ -821,7 +866,7 @@ async function attestKey() { ...@@ -821,7 +866,7 @@ async function attestKey() {
let options = { let options = {
properties: properties properties: properties
}; };
generateKey(aliasString); await generateKey(aliasString);
huks.attestKey(aliasString, options, function (err, data) { huks.attestKey(aliasString, options, function (err, data) {
printLog(`key attest result : ${JSON.stringify(data)}`); printLog(`key attest result : ${JSON.stringify(data)}`);
}); });
...@@ -870,6 +915,51 @@ function printLog(...data) { ...@@ -870,6 +915,51 @@ function printLog(...data) {
console.error(data.toString()); console.error(data.toString());
} }
async function generateKey(alias) {
let properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_RSA
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG,
value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY
};
properties[4] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256
};
properties[5] = {
tag: huks.HuksTag.HUKS_TAG_PADDING,
value: huks.HuksKeyPadding.HUKS_PADDING_PSS
};
properties[6] = {
tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE,
value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT
};
properties[7] = {
tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE,
value: huks.HuksCipherMode.HUKS_MODE_ECB
};
let options = {
properties: properties
};
await huks.generateKey(alias, options).then(async (data) => {
console.error(`generateKey data ${JSON.stringify(data)}`);
}).catch((err) => {
console.error(`generateKey err: " + ${JSON.stringify(err)}`);
});;
}
async function attestKey() { async function attestKey() {
let aliasString = keyAliasString; let aliasString = keyAliasString;
let aliasUint8 = stringToUint8Array(aliasString); let aliasUint8 = stringToUint8Array(aliasString);
...@@ -893,7 +983,7 @@ async function attestKey() { ...@@ -893,7 +983,7 @@ async function attestKey() {
let options = { let options = {
properties: properties properties: properties
}; };
generateKey(aliasString); await generateKey(aliasString);
huks.attestKey(aliasString, options) huks.attestKey(aliasString, options)
.then((data) => { .then((data) => {
console.log(`test attestKey data: ${JSON.stringify(data)}`); console.log(`test attestKey data: ${JSON.stringify(data)}`);
...@@ -1096,7 +1186,7 @@ function huksImportWrappedKey() { ...@@ -1096,7 +1186,7 @@ function huksImportWrappedKey() {
importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<HuksResult> importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Imports a wrapped key. This API uses a promise to return the result asynchronously. Imports a wrapped key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1159,7 +1249,7 @@ huks.exportKey(keyAlias, emptyOptions, function (err, data){}); ...@@ -1159,7 +1249,7 @@ huks.exportKey(keyAlias, emptyOptions, function (err, data){});
exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Exports a key. This API uses a promise to return the result asynchronously. Exports a key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1218,7 +1308,7 @@ huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); ...@@ -1218,7 +1308,7 @@ huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){});
getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Obtains key properties. This API uses a promise to return the result asynchronously. Obtains key properties. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1277,7 +1367,7 @@ huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); ...@@ -1277,7 +1367,7 @@ huks.isKeyExist(keyAlias, emptyOptions, function (err, data){});
isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
Checks whether a key exists. This API uses a promise to return the result asynchronously. Checks whether a key exists. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1311,7 +1401,7 @@ var result = huks.isKeyExist(keyAlias, emptyOptions); ...@@ -1311,7 +1401,7 @@ var result = huks.isKeyExist(keyAlias, emptyOptions);
init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle>) : void
Initializes a key. This API uses an asynchronous callback to return the result. Initializes the data for a key operation. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1328,7 +1418,7 @@ Initializes a key. This API uses an asynchronous callback to return the result. ...@@ -1328,7 +1418,7 @@ Initializes a key. This API uses an asynchronous callback to return the result.
init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle> init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle>
Initializes a key. This API uses a promise to return the result asynchronously. Initializes the data for a key operation. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1345,9 +1435,9 @@ Initializes a key. This API uses a promise to return the result asynchronously. ...@@ -1345,9 +1435,9 @@ Initializes a key. This API uses a promise to return the result asynchronously.
update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Updates a key. This API uses an asynchronous callback to return the result. Updates the key operation data by segment. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>]. > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1364,9 +1454,9 @@ Updates a key. This API uses an asynchronous callback to return the result. ...@@ -1364,9 +1454,9 @@ Updates a key. This API uses an asynchronous callback to return the result.
update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult> update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult>
Updates a key. This API uses a promise to return the result asynchronously. Updates the key operation data by segment. This API uses a promise to return the result.
> **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9). > **NOTE**<br>This API is discarded since API version 9. You are advised to use [huks.update<sup>9+</sup>](#huksupdate9-2).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1383,7 +1473,7 @@ Updates a key. This API uses a promise to return the result asynchronously. ...@@ -1383,7 +1473,7 @@ Updates a key. This API uses a promise to return the result asynchronously.
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Updates a key. This API uses an asynchronous callback to return the result. Updates the key operation by segment. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1400,7 +1490,7 @@ Updates a key. This API uses an asynchronous callback to return the result. ...@@ -1400,7 +1490,7 @@ Updates a key. This API uses an asynchronous callback to return the result.
update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void
Updates a key. This API uses an asynchronous callback to return the result. Updates the key operation by segment. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1417,7 +1507,7 @@ Updates a key. This API uses an asynchronous callback to return the result. ...@@ -1417,7 +1507,7 @@ Updates a key. This API uses an asynchronous callback to return the result.
update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>
Updates a key. This API uses a promise to return the result asynchronously. Updates the key operation by segment. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1451,7 +1541,7 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -1451,7 +1541,7 @@ Completes the key operation and releases resources. This API uses an asynchronou
finish(handle: number, options: HuksOptions) : Promise\<HuksResult> finish(handle: number, options: HuksOptions) : Promise\<HuksResult>
Completes the key operation and releases resources. This API uses a promise to return the result asynchronously. Completes the key operation and releases resources. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1485,7 +1575,7 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -1485,7 +1575,7 @@ Completes the key operation and releases resources. This API uses an asynchronou
finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult>
Completes the key operation and releases resources. This API uses a promise to return the result asynchronously. Completes the key operation and releases resources. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1722,7 +1812,7 @@ struct Index { ...@@ -1722,7 +1812,7 @@ struct Index {
abort(handle: number, options: HuksOptions) : Promise\<HuksResult>; abort(handle: number, options: HuksOptions) : Promise\<HuksResult>;
Aborts the use of the key. This API uses a promise to return the result asynchronously. Aborts the use of the key. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1976,7 +2066,7 @@ Defines the HUKS handle structure. ...@@ -1976,7 +2066,7 @@ Defines the HUKS handle structure.
| ---------- | ---------------- | ---- | -------- | | ---------- | ---------------- | ---- | -------- |
| errorCode | number | Yes | Error code.| | errorCode | number | Yes | Error code.|
| handle | number | Yes| Value of the handle.| | handle | number | Yes| Value of the handle.|
| token | Uint8Array | No| Challenge information obtained after the [init](#huksinit) operation.| | token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.|
## HuksResult ## HuksResult
......
# Standard NFC Tag # NFC Tags
The **nfcTag** module provides methods for managing Near-Field Communication (NFC) tags. The **nfcTag** module provides methods for managing Near-Field Communication (NFC) tags.
......
# Standard NFC Tag Technologies # NFC Tag Technologies
The **nfctech** module provides methods for reading and writing tags that use different Near-Field Communication (NFC) technologies. The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies.
> **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## **Modules to Import**
...@@ -14,7 +13,7 @@ import tag from '@ohos.nfc.tag'; ...@@ -14,7 +13,7 @@ import tag from '@ohos.nfc.tag';
## NfcATag ## NfcATag
Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. **NfcATag** inherits from **TagSession**. Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -74,7 +73,7 @@ console.log("atqa:" +atqa); ...@@ -74,7 +73,7 @@ console.log("atqa:" +atqa);
## NfcBTag ## NfcBTag
Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. **NfcBTag** inherits from **TagSession**. Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -110,7 +109,7 @@ console.log("appData:" +appData); ...@@ -110,7 +109,7 @@ console.log("appData:" +appData);
getRespProtocol(): number[] getRespProtocol(): number[]
Obtains protocol information of this NFC-B tag. Obtains the protocol information of this NFC-B tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -134,7 +133,7 @@ console.log("appData:" +protocol); ...@@ -134,7 +133,7 @@ console.log("appData:" +protocol);
## NfcFTag ## NfcFTag
Provides access to NFC-F(JIS 6319-4) properties and I/O operations. **NfcFTag** inherits from **TagSession**. Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -144,7 +143,7 @@ The following describes the unique interfaces of **NfcFTag**. ...@@ -144,7 +143,7 @@ The following describes the unique interfaces of **NfcFTag**.
getSystemCode(): number[] getSystemCode(): number[]
Obtains the system code from the tag instance. Obtains the system code from this NFC-F tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -170,7 +169,7 @@ console.log("systemCode:" +systemCode); ...@@ -170,7 +169,7 @@ console.log("systemCode:" +systemCode);
getPmm(): number[] getPmm(): number[]
Obtains the PMm (consisting of the IC code and manufacturer parameters) information from the tag instance. Obtains the PMm (consisting of the IC code and manufacturer parameters) information from this NFC-F tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -194,7 +193,7 @@ console.log("pmm:" +pmm); ...@@ -194,7 +193,7 @@ console.log("pmm:" +pmm);
## NfcVTag ## NfcVTag
Provides access to NFC-V (ISO 15693) properties and I/O operations. **NfcVTag** inherits from **TagSession**. Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -204,7 +203,7 @@ The following describes the unique interfaces of **NfcVTag**. ...@@ -204,7 +203,7 @@ The following describes the unique interfaces of **NfcVTag**.
getResponseFlags(): number getResponseFlags(): number
Obtains the response flags from the tag instance. Obtains the response flags from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -230,7 +229,7 @@ console.log("flags:" +flags); ...@@ -230,7 +229,7 @@ console.log("flags:" +flags);
getDsfId(): number getDsfId(): number
Obtains the data storage format identifier (DSFID) from the tag instance. Obtains the data storage format identifier (DSFID) from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -254,7 +253,7 @@ console.log("dsfId:" +dsfId); ...@@ -254,7 +253,7 @@ console.log("dsfId:" +dsfId);
## IsoDepTag<sup>9+</sup> ## IsoDepTag<sup>9+</sup>
Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. **IsoDepTag** inherits from **TagSession**. Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -343,7 +342,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { ...@@ -343,7 +342,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) {
isExtendedApduSupported(callback: AsyncCallback\<boolean>): void isExtendedApduSupported(callback: AsyncCallback\<boolean>): void
Checks whether an extended application protocol data unit (APDU) is supported. This API uses an asynchronous callback to return the result. Checks whether an extended APDU is supported. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -367,7 +366,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { ...@@ -367,7 +366,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) {
## NdefTag<sup>9+</sup> ## NdefTag<sup>9+</sup>
Provides access to the tags in the NFC Data Exchange Format (NDEF). **NdefTag** inherits from **TagSession**. Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -596,7 +595,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu ...@@ -596,7 +595,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu
| **Type**| **Description** | | **Type**| **Description** |
| ------------------ | --------------------------| | ------------------ | --------------------------|
| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the NDEF message read.|
**Example** **Example**
...@@ -641,7 +640,7 @@ tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { ...@@ -641,7 +640,7 @@ tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) {
writeNdef(msg: NdefMessage): Promise\<number>; writeNdef(msg: NdefMessage): Promise\<number>;
Write an NDEF message to this tag. This API uses a promise to return the result. Writes an NDEF message to this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -674,7 +673,7 @@ NdefTag.writeNdef(msg).then(function (netHandle) { ...@@ -674,7 +673,7 @@ NdefTag.writeNdef(msg).then(function (netHandle) {
writeNdef(msg: NdefMessage, callback: AsyncCallback\<number>): void writeNdef(msg: NdefMessage, callback: AsyncCallback\<number>): void
Write an NDEF message to this tag. This API uses an asynchronous callback to return the result. Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -728,7 +727,7 @@ tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { ...@@ -728,7 +727,7 @@ tag.NdefTag(taginfo).canSetReadOnly().then(function (has) {
### NdefTag.canSetReadOnly<sup>9+</sup> ### NdefTag.canSetReadOnly<sup>9+</sup>
canSetReadOnly()(callback: AsyncCallback&lt;boolean&gt;): void; canSetReadOnly(callback: AsyncCallback&lt;boolean&gt;): void;
Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result. Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result.
...@@ -813,7 +812,7 @@ tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { ...@@ -813,7 +812,7 @@ tag.NdefTag(taginfo).setReadOnly(function (error, errcode) {
getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string
Converts the NFC Forum Type to a byte array defined in the NFC Forum. Converts an NFC Forum Type to a byte array defined in the NFC Forum.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -852,7 +851,7 @@ let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); ...@@ -852,7 +851,7 @@ let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type);
## MifareClassicTag <sup>9+</sup> ## MifareClassicTag <sup>9+</sup>
Provides access to MIFARE Classic properties and I/O operations. **MifareClassicTag** inherits from **TagSession**. Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -928,7 +927,7 @@ tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (err ...@@ -928,7 +927,7 @@ tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (err
readSingleBlock(blockIndex: number): Promise\<string> readSingleBlock(blockIndex: number): Promise\<string>
Reads a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. Reads a block (16 bytes) on the tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -962,7 +961,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ ...@@ -962,7 +961,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){
readSingleBlock(blockIndex: number, callback: AsyncCallback\<string>): void readSingleBlock(blockIndex: number, callback: AsyncCallback\<string>): void
Reads a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -992,7 +991,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) ...@@ -992,7 +991,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data)
writeSingleBlock(blockIndex: number, data: string): Promise\<number> writeSingleBlock(blockIndex: number, data: string): Promise\<number>
Writes data to a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. Writes data to a block on the tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1027,7 +1026,7 @@ tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function ( ...@@ -1027,7 +1026,7 @@ tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function (
writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\<number>): void writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\<number>): void
Writes data to a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. Writes data to a block on the tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1427,10 +1426,10 @@ let size = tag.MifareClassicTag(taginfo).getTagSize(); ...@@ -1427,10 +1426,10 @@ let size = tag.MifareClassicTag(taginfo).getTagSize();
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| MC_SIZE_MINI | 320 | Each tag has five sectors, and each sector has four blocks.| | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.|
| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has four blocks.| | MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.|
| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has four blocks.| | MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.|
| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has four blocks.| | MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.|
### MifareClassicTag.isEmulatedTag<sup>9+</sup> ### MifareClassicTag.isEmulatedTag<sup>9+</sup>
...@@ -1521,7 +1520,7 @@ let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); ...@@ -1521,7 +1520,7 @@ let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex);
## MifareUltralightTag<sup>9+</sup> ## MifareUltralightTag<sup>9+</sup>
Provides access to MIFARE Ultralight properties and I/O operations. **MifareUltralightTag** inherits from **TagSession**. Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -1531,7 +1530,7 @@ The following describes the unique interfaces of **MifareUltralightTag**. ...@@ -1531,7 +1530,7 @@ The following describes the unique interfaces of **MifareUltralightTag**.
readMultiplePages(pageIndex: number): Promise\<string> readMultiplePages(pageIndex: number): Promise\<string>
Reads multiple pages. The size of each page is 4 bytes. This API uses a promise to return the result. Reads multiple pages (4 bytes per page). This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1565,7 +1564,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (dat ...@@ -1565,7 +1564,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (dat
readMultiplePages(pageIndex: number, callback: AsyncCallback\<string>): void readMultiplePages(pageIndex: number, callback: AsyncCallback\<string>): void
Reads multiple pages. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1594,7 +1593,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, d ...@@ -1594,7 +1593,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, d
writeSinglePages(pageIndex: number, data: string): Promise\<number> writeSinglePages(pageIndex: number, data: string): Promise\<number>
Writes a page of data. The size of each page is 4 bytes. This API uses a promise to return the result. Writes a page of data. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1628,7 +1627,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function ...@@ -1628,7 +1627,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function
writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\<number>): void writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\<number>): void
Writes a page of data. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. Writes a page of data. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1658,7 +1657,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (err ...@@ -1658,7 +1657,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (err
getType(): MifareUltralightType getType(): MifareUltralightType
Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](#mifareultralighttype9). Obtains the MIFARE Ultralight tag type, in bytes.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -1689,7 +1688,7 @@ let type = tag.MifareUltralightType(taginfo).getType(); ...@@ -1689,7 +1688,7 @@ let type = tag.MifareUltralightType(taginfo).getType();
## NdefFormatableTag<sup>9+</sup> ## NdefFormatableTag<sup>9+</sup>
Provides methods for operating NDEF formattable tags. **NdefFormatableTag** inherits from **TagSession**. Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**.
**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md).
...@@ -1709,7 +1708,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ...@@ -1709,7 +1708,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).|
**Return value** **Return value**
...@@ -1742,8 +1741,8 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ...@@ -1742,8 +1741,8 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.|
| callback: AsyncCallback\<number> | Callback invoked to return the result.| | callback | AsyncCallback\<number> |Yes|Callback invoked to return the result.|
**Example** **Example**
...@@ -1771,7 +1770,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ...@@ -1771,7 +1770,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).|
**Return value** **Return value**
...@@ -1804,8 +1803,8 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ...@@ -1804,8 +1803,8 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| | message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.|
| callback: AsyncCallback\<number> | Callback invoked to return the result.| | callback | AsyncCallback\<number> |Yes|Callback invoked to return the result.|
**Example** **Example**
......
# Standard NFC Tag Session # NFC Tag Session
The **tagSession** module provides common APIs for establishing connections and transferring data. The **tagSession** module provides common APIs for establishing connections and transferring data.
> **NOTE** > **NOTE**<br>
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## **Modules to Import**
...@@ -18,7 +17,7 @@ Provides common APIs for establishing connections and transferring data. **tagSe ...@@ -18,7 +17,7 @@ Provides common APIs for establishing connections and transferring data. **tagSe
A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance.
The specific method varies with the NFC tag technology in use. For details, see [nfcTag](js-apis-nfcTag.md). The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md).
### tagSession.connectTag ### tagSession.connectTag
...@@ -26,7 +25,7 @@ connectTag(): boolean; ...@@ -26,7 +25,7 @@ connectTag(): boolean;
Connects to this tag. Connects to this tag.
Call this method to set up a connection before reading data from or writing data to a tag. Call this API to set up a connection before reading data from or writing data to a tag.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -95,7 +94,7 @@ Checks whether the tag is connected. ...@@ -95,7 +94,7 @@ Checks whether the tag is connected.
```js ```js
import tag from '@ohos.nfc.tag'; import tag from '@ohos.nfc.tag';
// tagInfo is an Object given by nfc service when tag is dispatched. // tagInfo is an object given by the NFC service when a tag is dispatched.
let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); let isTagConnected = tag.getXXXTag(taginfo).isTagConnected();
console.log("isTagConnected:" +isTagConnected); console.log("isTagConnected:" +isTagConnected);
``` ```
......
...@@ -4,33 +4,33 @@ ...@@ -4,33 +4,33 @@
### Function ### Function
The motion recognition module provides motion recognition and control capabilities. Currently, OpenHarmony supports recognition of pick-up, flip, shake, and rotation. The motion module provides motion recognition and control capabilities. Currently, OpenHarmony supports recognition of pick-up, flip, shake, and rotation.
The motion recognition driver is developed based on the hardware driver foundation (HDF). It shields hardware differences and provides APIs for the Multimodal Sensor Data Platform (MSDP) to implement capabilities such as enabling or disabling motion recognition, and subscribing to or unsubscribing from motion recognition data. The motion driver is developed based on the hardware driver foundation (HDF). It shields hardware differences and provides APIs for the Multimodal Sensor Data Platform (MSDP) to implement capabilities such as enabling or disabling motion recognition, and subscribing to or unsubscribing from motion recognition data.
The figure below shows the motion recognition driver architecture. The framework layer provides MSDP services, and interacts with the Motion Stub through the Motion Proxy in the User Hardware Driver Foundation (UHDF). The Motion Stub calls the Motion HDI Impl APIs to provide motion recognition capabilities for upper-layer services. The figure below shows the motion driver architecture. The framework layer provides MSDP services, and interacts with the Motion Stub through the Motion Proxy in the User Hardware Driver Foundation (UHDF). The Motion Stub calls the Motion HDI Impl APIs to provide motion recognition capabilities for upper-layer services.
**Figure 1** Motion recognition driver architecture **Figure 1** Motion driver architecture
![](figures/motion_recognition_driver_architecture.png) ![](figures/motion_driver_architecture.png)
### Working Principles ### Working Principles
The figure below illustrates how a motion recognition driver works. The figure below illustrates how a motion driver works.
**Figure 2** How a motion recognition driver works **Figure 2** How a motion driver works
![](figures/motion_recognition_driver_work.png) ![](figures/motion_driver_work.png)
1. MSDP: The MSDP service obtains a Motion HDI service instance from the Motion Proxy and calls the Motion HDI API. 1. MSDP: The MSDP service obtains a Motion HDI service instance from the Motion Proxy and calls the Motion HDI API.
2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor. 2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor.
3. HDI Service: HDI Service consists of Motion Interface Driver, Motion Service, and Motion Impl. Motion Interface Driver provides the motion recognition driver code. A **HdfDriverEntry** structure is defined to implement the **Init**, **Bind**, and **Release** functions. The **HDF_INIT** macro is used to load the driver in the functions. Motion Service provides the motion recognition service interface class. The specific implementation is described in Motion Impl. The code of HDI Service must be developed by the component vendor. 3. HDI Service: HDI Service consists of Motion Interface Driver, Motion Service, and Motion Impl. Motion Interface Driver provides the motion driver code. A **HdfDriverEntry** structure is defined to implement the **Init**, **Bind**, and **Release** functions. The **HDF_INIT** macro is used to load the driver in the functions. Motion Service provides the motion recognition service interface class. The specific implementation is described in Motion Impl. The code of HDI Service must be developed by the component vendor.
## Development Guidelines ## Development Guidelines
### When to Use ### When to Use
The motion recognition driver provides capabilities for the MSDP service to enable or disable motion recognition and subscribe to or unsubscribe from motion recognition data. It can be used for motion recognition when a user picks up, flips, shakes, and rotates a device. The motion driver provides capabilities for the MSDP service to enable or disable motion recognition and subscribe to or unsubscribe from motion recognition data. It can be used for motion recognition when a user picks up, flips, shakes, and rotates a device.
### Available APIs ### Available APIs
...@@ -59,7 +59,7 @@ The motion recognition directory structure is as follows: ...@@ -59,7 +59,7 @@ The motion recognition directory structure is as follows:
│ └── unittest\hdi # HDI unit test code for the motion recognition module. │ └── unittest\hdi # HDI unit test code for the motion recognition module.
``` ```
The following describes how to develop a user-mode motion recognition driver based on the HDF. For details, see [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp). The following describes how to develop a user-mode motion driver based on the HDF. For details, see [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp).
To develop the user-mode driver for motion recognition, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. The **Bind** function provides service capabilities. The **Init** function initializes the driver before the driver is loaded. The **Release** function releases resources when the **Init** function fails. To develop the user-mode driver for motion recognition, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. The **Bind** function provides service capabilities. The **Init** function initializes the driver before the driver is loaded. The **Release** function releases resources when the **Init** function fails.
...@@ -99,7 +99,7 @@ int HdfMotionInterfaceDriverInit(struct HdfDeviceObject *deviceObject) ...@@ -99,7 +99,7 @@ int HdfMotionInterfaceDriverInit(struct HdfDeviceObject *deviceObject)
return HDF_SUCCESS; return HDF_SUCCESS;
} }
// Bind the services provided by the motion recognition driver to the HDF. // Bind the services provided by the motion driver to the HDF.
int HdfMotionInterfaceDriverBind(struct HdfDeviceObject *deviceObject) int HdfMotionInterfaceDriverBind(struct HdfDeviceObject *deviceObject)
{ {
HDF_LOGI("HdfMotionInterfaceDriverBind enter"); HDF_LOGI("HdfMotionInterfaceDriverBind enter");
...@@ -131,7 +131,7 @@ int HdfMotionInterfaceDriverBind(struct HdfDeviceObject *deviceObject) ...@@ -131,7 +131,7 @@ int HdfMotionInterfaceDriverBind(struct HdfDeviceObject *deviceObject)
return HDF_SUCCESS; return HDF_SUCCESS;
} }
// Release the resources used by the motion recognition driver. // Release the resources used by the motion driver.
void HdfMotionInterfaceDriverRelease(struct HdfDeviceObject *deviceObject) void HdfMotionInterfaceDriverRelease(struct HdfDeviceObject *deviceObject)
{ {
HDF_LOGI("HdfMotionInterfaceDriverRelease enter"); HDF_LOGI("HdfMotionInterfaceDriverRelease enter");
......
...@@ -4,6 +4,20 @@ ...@@ -4,6 +4,20 @@
- [Compilation and Building Guide](subsys-build-all.md) - [Compilation and Building Guide](subsys-build-all.md)
- [Build System Coding Specifications and Best Practices](subsys-build-gn-coding-style-and-best-practice.md) - [Build System Coding Specifications and Best Practices](subsys-build-gn-coding-style-and-best-practice.md)
- [Building the Kconfig Visual Configuration](subsys-build-gn-kconfig-visual-config-guide.md) - [Building the Kconfig Visual Configuration](subsys-build-gn-kconfig-visual-config-guide.md)
- Related Operations
- [Building a Product](subsys-build-product.md)
- [Building a Subsystem](subsys-build-subsystem.md)
- [Building a Component](subsys-build-component.md)
- [Building a Module](subsys-build-module.md)
- [Building a Chipset Solution](subsys-build-chip_solution.md)
- [Configuring Features](subsys-build-feature.md)
- [Configuring System Capabilities](subsys-build-syscap.md)
- [Setting deps and external_deps](subsys-build-reference.md#deps-and-external_deps)
- [Information Collected by the Open Source Software Notice](subsys-build-reference.md#information-collected-by-the-open-source-software-notice)
- [Configuring Parameters for Accelerating Local Build](subsys-build-reference.md#parameters-for-accelerating-local-build)
- [Viewing Ninja Build Information](subsys-build-reference.md#viewing-ninja-build-information)
- [HAP Build Guide](subsys-build-gn-hap-compilation-guide.md)
- [FAQs](subsys-build-FAQ.md)
- [Distributed Remote Startup](subsys-remote-start.md) - [Distributed Remote Startup](subsys-remote-start.md)
- Graphics - Graphics
- [Graphics Overview](subsys-graphics-overview.md) - [Graphics Overview](subsys-graphics-overview.md)
...@@ -70,6 +84,7 @@ ...@@ -70,6 +84,7 @@
- [Development on Application Permission Management](subsys-security-rightmanagement.md) - [Development on Application Permission Management](subsys-security-rightmanagement.md)
- [Development on IPC Authentication](subsys-security-communicationverify.md) - [Development on IPC Authentication](subsys-security-communicationverify.md)
- [Development on Device Security Level Management](subsys-security-devicesecuritylevel.md) - [Development on Device Security Level Management](subsys-security-devicesecuritylevel.md)
- [Development on HUKS](subsys-security-huks-guide.md)
- Startup - Startup
- [Startup](subsys-boot-overview.md) - [Startup](subsys-boot-overview.md)
- init Module - init Module
......
# Development on HUKS
## Overview
### Introduction
OpenHarmony Universal KeyStore (HUKS) provides system-level key management capabilities, ensuring secure management and use of keys throughout their entire lifecycle (generation, storage, use, and destruction). The environment where a key is stored and used is of the most importance to key security. For example, a key in plaintext must be used in a secure environment, such as a Trusted Execution Environment (TEE) or a security chip.
This document describes how to adapt Hardware Device Interface (HDI) APIs for secure key storage and use environment based on the OpenHarmony HUKS architecture and how to verify these APIs.
HUKS supports key lifecycle management, which covers the following:
1. Generation and import of the key
2. Storage of the key
3. Use of the key (including encryption and decryption, signing and verification, key derivation and agreement, hash, and key access control)
4. Destruction of the key
### Basic Concepts
- HUKS Service
An independent OpenHarmony service that supports key management. It belongs to the huks_service process. Instead of handling key calculation, the HUKS Service depends on the HUKS Core to provide services for the upper layer.
- HUKS Core
A functional module that provides the key management service. This module must run in a secure environment, and the keys in plaintext must be kept inside the HUKS Core module throughout the lifecycle.
- TEE
A secure area created by isolating software and hardware resources to protect the applications and data in the secure area from unauthorized access. This isolation mechanism yields two execution environments: TEE and Rich Execution Environment (REE). Each execution environment has independent internal data path and memory, protecting the data inside the TEEs from being disclosed. The applications in an REE cannot access resources in a TEE. The applications in a TEE cannot access resources in another TEE without authorization.
- Init-Update-Finish
**Init**: initializes data for a key operation.
**Update**: operates data by segment and returns the result, or appends data.
**Finish**: stops operating data by segment or appending data, and returns the result.
### Working Principles
The following uses the key generation process as an example to describe the communication between the HUKS Service and HUKS Core. Other key operations are similar.
The upper-layer application invokes the HUKS Service through the key management SDK. The HUKS Service invokes the HUKS Core, which invokes the key management module to generate a key. The HUKS Core uses a work key derived from the root key to encrypt the generated key and sends the encrypted key to the HUKS Service. The HUKS Service stores the encrypted key in a file.
![](figure/HUKS-GenerateKey1.png)
### Constraints
* HUKS must be implemented in a TEE for security purposes.
* The certificate chain returned by **HuksHdiAttestKey** must be in the sequence of the application certificate, device certificate, CA certificate, and root certificate, with the certificate length added before each certificate. The certificate chain and its length are assembled in the binary large object (BLOB) format. If you want to define the certificate format, the format must be the same as that parsed by the server.
![CertChain format](figure/HUKS-CertChain.png)
* The key returned by the API must be assembled into a **KeyBlob** based on the key storage status. For details about the APIs that must comply with this constraint, see [Available APIs](#available-apis).
The **KeyBlob** stores both the key and its attributes. The figure below shows the **KeyBlob** structure. For details about how to construct a **KeyBlob**, see [hks_keyblob.c/HksBuildKeyBlob](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c).
![KeyBlob format](figure/HUKS-KeyBlob.png)
## Development Guidelines
### When to Use
The HUKS Core provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. If you want to replace the HUKS Core with your own implementation, you need to implement the following APIs:
### Available APIs
**Table 1** Available APIs
| API | Description | Constraints | Corresponding JS API |
| ------------------------------------------------------------ | ---------------------------------------- | ----------------------------- | ------------------------------------------------------------ |
| [HuksHdiModuleInit()](#hukshdimoduleinit) | Initializes the HUKS Core. | – | –|
| [HuksHdiRefresh()](#hukshdirefresh) | Refreshes the root key. | – | –|
| [HuksHdiGenerateKey()](#hukshdigeneratekey) | Generates a key. | The key generated must be in the **KeyBlob** format. |generateKey(keyAlias: string, options: HuksOptions)|
| [HuksHdiImportKey()](#hukshdiimportkey) | Import a key in plaintext. | The output parameter must be in the **KeyBlob** format. | importKey(keyAlias: string, options: HuksOptions)|
| [HuksHdiImportWrappedKey()](#hukshdiimportwrappedkey) |Import an encrypted key. | The output parameter must be in the **KeyBlob** format. | importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions)|
| [HuksHdiExportPublicKey()](#hukshdiexportpublickey) | Exports a public key. |– | exportKey(keyAlias: string, options: HuksOptions) |
| [HuksHdiInit()](#hukshdiinit) | Initializes data for a key operation. This API is of the Init-Update-Final model. |– | init(keyAlias: string, options: HuksOptions) |
| [HuksHdiUpdate()](#hukshdiupdate) | Operates data by segment or appends data for the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the raw data. | update(handle: number, token?: Uint8Array, options: HuksOptions) |
| [HuksHdiFinish()](#hukshdifinish) | Finishes the key operation. This API is of the Init-Update-Final model. |The input parameter for signing and signature verification must be the signed data. | finish(handle: number, options: HuksOptions) |
| [HuksHdiAbort()](#hukshdiabort) | Aborts Init-Update-Finish. |– | abort(handle: number, options: HuksOptions) |
| [HuksHdiGetKeyProperties()](#hukshdigetkeyproperties) | Obtains key properties. |– | getKeyProperties(keyAlias: string, options: HuksOptions)|
| [HuksHdiAttestKey()](#hukshdiattestkey) | Obtain the key certificate. |The output parameter must be in the **certChain** format. | attestKey(keyAlias: string, options: HuksOptions)|
- - -
#### HuksHdiModuleInit
**API description**
Initializes the HUKS Core, including the lock, encryption algorithm library, authtoken key, and root key.
**Prototype**
<pre><code>int32_t HuksHdiModuleInit();</code></pre>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiRefresh
**API description**
Refreshes the root key.
**Prototype**
<pre><code>int32_t HuksHdiRefresh();</code></pre>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiGenerateKey
**API description**
Generates a key based on **paramSet**.
**Prototype**
<pre><code>int32_t HuksHdiGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, const struct HksBlob *keyIn, struct HksBlob *keyOut);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *keyAlias</strong>
Pointer to the alias of the key to generate. The value must meet the following requirements:
1. keyAlias != null
2. keyAlias -> data != null
3. keyAlias -> size != 0
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters for generating the key.
<br></br>
<strong>const struct HksBlob *keyIn</strong>
This parameter is used in key agreement.
<br></br>
<strong>struct HksBlob *keyOut</strong>
Pointer to the output parameter, which holds **paramSet** and the key generated.
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. Check parameters in the API. For example, check for null pointers and whether the key algorithm is supported.
2. **keyOut** must be in the **KeyBlob** format.
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiImportKey
**API description**
Imports a key in plaintext.
**Prototype**
<pre><code>int32_t HuksHdiImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *msg</strong>
Pointer to the alias of the key to import. The value must meet the following requirements:
1. keyAlias != null
2. keyAlias -> data != null
3. keyAlias -> size != 0
<br></br>
<strong>const struct HksBlob *key</strong>
Pointer to the key to import. The value must meet the following requirements:
1. key != null
2. key -> data != null
3. key -> size != 0
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters for importing the key.
<br></br>
<strong>struct HksBlob *keyOut</strong>
Pointer to the output parameter, which holds **paramSet** and the key.
<br></br>
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. Check parameters in the API. For example, check for null pointers and whether the key algorithm is supported.
2. **keyOut** must be in the **KeyBlob** format.
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiImportWrappedKey
**API description**
Imports an encrypted key.
**Prototype**
<pre><code>int32_t HuksHdiImportWrappedKey(const struct HksBlob *keyAlias, const struct HksBlob *wrappingUsedkey, const struct HksBlob *wrappedKeyData, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *KeyAlias</strong>
Pointer to the alias of the key to import. The value must meet the following requirements:
1. keyAlias != null
2. keyAlias -> data != null
3. keyAlias -> size != 0
<br></br>
<strong>const struct HksBlob *key</strong>
Pointer to the key used to encrypt the key to import. The value must meet the following requirements:
1. wrappingUsedkey != null
2. wrappingUsedkey -> data != null
3. wrappingUsedkey -> size != 0
<br></br>
<strong>const struct HksBlob *wrappedKeyData</strong>
Pointer to the encrypted data of the key to import. The value must meet the following requirements:
1. wrappedKeyData != null
2. wrappedKeyData -> data != null
3. wrappedKeyData -> size != 0
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters for importing the key.
<br></br>
<strong>struct HksBlob *keyOut</strong>
Pointer to the output parameter, which holds **paramSet** and the key imported.
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. Check parameters in the API. For example, check for null pointers and whether the key algorithm is supported.
2. **keyOut** must be in the **KeyBlob** format.
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiExportPublicKey
**API description**
Exports a public key.
**Prototype**
<pre><code>int32_t HuksHdiExportPublicKey(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *key</strong>
Pointer to the private key corresponding to the public key to export. The value must meet the following requirements:
1. key != null
2. key -> data != null
3. key -> size != 0
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameter set, which is empty.
<br></br>
<strong>struct HksBlob *keyOut</strong>
Pointer to the output parameter, which holds the public key exported.
</pre>
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiInit
**API description**
Initializes data for a key operation. This API is of the Init-Update-Final model.
**Prototype**
<pre><code>int32_t HuksHdiInit(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle, struct HksBlob *token);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *key</strong>
Pointer to the key, on which the **Init** operation is to perform. The value must meet the following requirements:
1. key != null
2. key -> data != null
3. key -> size != 0
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters of the **Init** operation.
<br></br>
<strong>struct HksBlob *handle</strong>
Pointer to the handle of Init-Update-Finish.
<br></br>
<strong>struct HksBlob *token</strong>
Pointer to the challenge used for secure access control.
</pre>
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiUpdate
**API description**
Operates data by segment or appends data for the key operation. This API is of the Init-Update-Final model.
**Prototype**
<pre><code>int32_t HuksHdiUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *handle</strong>
Pointer to the handle of Init-Update-Finish.
<br></br>
<strong> const struct HksParamSet *paramSet</strong>
Pointer to the parameters of the **Update** operation.
<br></br>
<strong> const struct HksBlob *inData</strong>
Pointer to the input of the **Update** operation.
<br></br>
<strong> struct HksBlob *outData</strong>
Pointer to the result of the **Update** operation.
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. **inData** must pass in the raw data when signing and signature verification are performed.
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiFinish
**API description**
Finishes the key operation. This API is of the Init-Update-Final model.
**Prototype**
<pre><code>int32_t HuksHdiFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData, struct HksBlob *outData);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *handle</strong>
Pointer to the handle of Init-Update-Finish.
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters of the **Finish** operation.
<br></br>
<strong>const struct HksBlob *inData</strong>
Pointer to the input of the **Finish** operation.
<br></br>
<strong>struct HksBlob *outData</strong>
Pointer to the result of the **Finish** operation.
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. In signing and signature verification, **inData** must pass in the signature data to be verified. The return value indicates whether the operation is successful.
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiAbort
**API description**
Aborts Init-Update-Finish. When an error occurs in any of the **Init**, **Update**, and **Finish** operations, call this API to terminate the use of the key.
**Prototype**
<pre><code>int32_t HuksHdiAbort(const struct HksBlob *handle, const struct HksParamSet *paramSet);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *handle</strong>
Pointer to the handle of Init-Update-Finish.
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters of the **Abort** operation.
</pre>
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiGetKeyProperties
**API description**
Obtains key properties.
**Prototype**
<pre><code>int32_t HuksHdiGetKeyProperties(const struct HksParamSet *paramSet, const struct HksBlob *key);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameter set, which is empty.
<br></br>
<strong>const struct HksBlob *key</strong>
Pointer to the target key.
</pre>
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
#### HuksHdiAttestKey
**API description**
Obtains the key certificate.
**Prototype**
<pre><code>int32_t (*HuksHdiAttestKey)(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *certChain);</code></pre>
<details>
<summary><strong>Parameters</strong></summary>
<pre>
<strong>const struct HksBlob *key</strong>
Pointer to the target key.
<br></br>
<strong>const struct HksParamSet *paramSet</strong>
Pointer to the parameters for the operation.
<br></br>
<strong>struct HksBlob *certChain</strong>
Pointer to the output parameter, which holds the certificate obtained.
</pre>
</details>
<br></br>
<details>
<summary><strong>Constraints</strong></summary>
1. **certChain** must comply with the certificate chain described in [Constraints](#constraints).
</details>
<br></br>
<details>
<summary><strong>Return value</strong></summary>
- **HKS_SUCCESS**: The operation is successful.
- Other value: The operation failed.
</details>
- - -
### Development Procedure
The directory structure is as follows:
```undefined
// base/security/user_auth/services/huks_standard/huks_engine/main
├── BUILD.gn # Build script
├── core_dependency # Dependencies of the implementation
└── core # Software implementation of the HUKS Core
├── BUILD.gn # Build script
├── include
└── src
├── hks_core_interfaces.c # Adaptation of the HDI to the HUKS Core
└── hks_core_service.c # Specific implementation
└── ... # Other function code
```
Init-Update-Finish must be used to implement HUKS Core APIs. The following provides the development procedure of Init-Update-Finish and sample code of the HUKS Core. You can refer to the following code to implement all HDI APIs.
For the code of other HUKS Core APIs, see [hks_core_service.c](https://gitee.com/openharmony/security_huks/blob/master/services/huks_standard/huks_engine/main/core/src/hks_core_service.c).
1. Create a handle to enable the information about the operations on a key to be stored in a session. With this handle, multiple operations on the same key can be performed.
```c
// Implement Init().
int32_t HksCoreInit(const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *handle,
struct HksBlob *token)
{
HKS_LOG_D("HksCoreInit in Core start");
uint32_t pur = 0;
uint32_t alg = 0;
// Check parameters.
if (key == NULL || paramSet == NULL || handle == NULL || token == NULL) {
HKS_LOG_E("the pointer param entered is invalid");
return HKS_FAILURE;
}
if (handle->size < sizeof(uint64_t)) {
HKS_LOG_E("handle size is too small, size : %u", handle->size);
return HKS_ERROR_INSUFFICIENT_MEMORY;
}
// Decrypt the key file.
struct HuksKeyNode *keyNode = HksCreateKeyNode(key, paramSet);
if (keyNode == NULL || handle == NULL) {
HKS_LOG_E("the pointer param entered is invalid");
return HKS_ERROR_BAD_STATE;
}
// Store information in a session based on the handle. The information stored can be used for the Update and Finish operations on the key.
handle->size = sizeof(uint64_t);
(void)memcpy_s(handle->data, handle->size, &(keyNode->handle), handle->size);
// Obtain the algorithm from the parameters.
int32_t ret = GetPurposeAndAlgorithm(paramSet, &pur, &alg);
if (ret != HKS_SUCCESS) {
HksDeleteKeyNode(keyNode->handle);
return ret;
}
// Check the key parameters.
ret = HksCoreSecureAccessInitParams(keyNode, paramSet, token);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("init secure access params failed");
HksDeleteKeyNode(keyNode->handle);
return ret;
}
// Obtain the initialization handler from the algorithm library based on the usage of the key.
uint32_t i;
uint32_t size = HKS_ARRAY_SIZE(g_hksCoreInitHandler);
for (i = 0; i < size; i++) {
if (g_hksCoreInitHandler[i].pur == pur) {
HKS_LOG_E("Core HksCoreInit [pur] = %d, pur = %d", g_hksCoreInitHandler[i].pur, pur);
ret = g_hksCoreInitHandler[i].handler(keyNode, paramSet, alg);
break;
}
}
// Check exception results.
if (ret != HKS_SUCCESS) {
HksDeleteKeyNode(keyNode->handle);
HKS_LOG_E("CoreInit failed, ret : %d", ret);
return ret;
}
if (i == size) {
HksDeleteKeyNode(keyNode->handle);
HKS_LOG_E("don't found purpose, pur : %u", pur);
return HKS_FAILURE;
}
HKS_LOG_D("HksCoreInit in Core end");
return ret;
}
```
2. Obtain the context based on the handle, and pass in data slices to obtain the operation result or append data.
```c
// Implement Update().
int32_t HksCoreUpdate(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData,
struct HksBlob *outData)
{
HKS_LOG_D("HksCoreUpdate in Core start");
uint32_t pur = 0;
uint32_t alg = 0;
// Check parameters.
if (handle == NULL || paramSet == NULL || inData == NULL) {
HKS_LOG_E("the pointer param entered is invalid");
return HKS_FAILURE;
}
uint64_t sessionId;
struct HuksKeyNode *keyNode = NULL;
// Obtain the context based on the handle.
int32_t ret = GetParamsForUpdateAndFinish(handle, &sessionId, &keyNode, &pur, &alg);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("GetParamsForCoreUpdate failed");
return ret;
}
// Verify key parameters.
ret = HksCoreSecureAccessVerifyParams(keyNode, paramSet);
if (ret != HKS_SUCCESS) {
HksDeleteKeyNode(sessionId);
HKS_LOG_E("HksCoreUpdate secure access verify failed");
return ret;
}
// Call the key handler from the corresponding algorithm library.
uint32_t i;
uint32_t size = HKS_ARRAY_SIZE(g_hksCoreUpdateHandler);
for (i = 0; i < size; i++) {
if (g_hksCoreUpdateHandler[i].pur == pur) {
struct HksBlob appendInData = { 0, NULL };
ret = HksCoreAppendAuthInfoBeforeUpdate(keyNode, pur, paramSet, inData, &appendInData);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("before update: append auth info failed");
break;
}
ret = g_hksCoreUpdateHandler[i].handler(keyNode, paramSet,
appendInData.data == NULL ? inData : &appendInData, outData, alg);
if (appendInData.data != NULL) {
HKS_FREE_BLOB(appendInData);
}
break;
}
}
// Check exception results.
if (ret != HKS_SUCCESS) {
HksDeleteKeyNode(keyNode->handle);
HKS_LOG_E("CoreUpdate failed, ret : %d", ret);
return ret;
}
if (i == size) {
HksDeleteKeyNode(sessionId);
HKS_LOG_E("don't found purpose, pur : %u", pur);
return HKS_FAILURE;
}
return ret;
}
```
3. Finish the key operation to obtain the result, and destroy the handle.
```c
// Implement Finish().
int32_t HksCoreFinish(const struct HksBlob *handle, const struct HksParamSet *paramSet, const struct HksBlob *inData,
struct HksBlob *outData)
{
HKS_LOG_D("HksCoreFinish in Core start");
uint32_t pur = 0;
uint32_t alg = 0;
// Check parameters.
if (handle == NULL || paramSet == NULL || inData == NULL) {
HKS_LOG_E("the pointer param entered is invalid");
return HKS_FAILURE;
}
uint64_t sessionId;
struct HuksKeyNode *keyNode = NULL;
// Obtain the context based on the handle.
int32_t ret = GetParamsForUpdateAndFinish(handle, &sessionId, &keyNode, &pur, &alg);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("GetParamsForCoreUpdate failed");
return ret;
}
// Verify key parameters.
ret = HksCoreSecureAccessVerifyParams(keyNode, paramSet);
if (ret != HKS_SUCCESS) {
HksDeleteKeyNode(sessionId);
HKS_LOG_E("HksCoreFinish secure access verify failed");
return ret;
}
// Call the key handler from the corresponding algorithm library.
uint32_t i;
uint32_t size = HKS_ARRAY_SIZE(g_hksCoreFinishHandler);
for (i = 0; i < size; i++) {
if (g_hksCoreFinishHandler[i].pur == pur) {
uint32_t outDataBufferSize = (outData == NULL) ? 0 : outData->size;
struct HksBlob appendInData = { 0, NULL };
ret = HksCoreAppendAuthInfoBeforeFinish(keyNode, pur, paramSet, inData, &appendInData);
if (ret != HKS_SUCCESS) {
HKS_LOG_E("before finish: append auth info failed");
break;
}
ret = g_hksCoreFinishHandler[i].handler(keyNode, paramSet,
appendInData.data == NULL ? inData : &appendInData, outData, alg);
if (appendInData.data != NULL) {
HKS_FREE_BLOB(appendInData);
}
if (ret != HKS_SUCCESS) {
break;
}
// Append the end label of the key operation.
ret = HksCoreAppendAuthInfoAfterFinish(keyNode, pur, paramSet, outDataBufferSize, outData);
break;
}
}
if (i == size) {
HKS_LOG_E("don't found purpose, pur : %d", pur);
ret = HKS_FAILURE;
}
// Delete the session.
HksDeleteKeyNode(sessionId);
HKS_LOG_D("HksCoreFinish in Core end");
return ret;
}
```
### Verification
Use the [HUKS JS APIs](https://gitee.com/openharmony/security_huks/blob/master/interfaces/kits/js/@ohos.security.huks.d.ts) to develop a JavaScript application to verify HUKS capabilities.
The JS API corresponding to each HDI API is provided in [Available APIs](#available-apis). You can invoke the JS APIs to verify the capabilities of the corresponding HDI APIs or perform complete key operations to verify the capabilities of the APIs.
The JS test code is as follows. If the entire process is successful, the HDI APIs are functioning. For more information about key operations, see [HUKS Development](../../application-dev/security/huks-guidelines.md).
**Generating and Encrypting an AES Key**
1. Import the HUKS module.
```js
import huks from '@ohos.security.huks'
```
2. Call **generateKey()** to generate a key.
```js
var alias = 'testAlias';
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_ECC
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_ECC_KEY_SIZE_224
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[3] = {
tag: huks.HuksTag.HUKS_TAG_DIGEST,
value: huks.HuksKeyDigest.HUKS_DIGEST_NONE
};
var options = {
properties: properties
}
var resultA = huks.generateKey(alias, options);
```
3. Call **Init()** to perform initialization.
```js
var alias = 'test001'
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DH
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
huks.init(alias, options, function(err, data) {
if (err.code !== 0) {
console.log("test init err information: " + JSON.stringify(err));
} else {
console.log(`test init data: ${JSON.stringify(data)}`);
}
})
```
4. Call **update()** to perform the **Update** operation.
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DH
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.update(handle, options)
```
5. Call **finish()** to finish the operation.
```js
var properties = new Array();
properties[0] = {
tag: huks.HuksTag.HUKS_TAG_ALGORITHM,
value: huks.HuksKeyAlg.HUKS_ALG_DH
};
properties[1] = {
tag: huks.HuksTag.HUKS_TAG_PURPOSE,
value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_AGREE
};
properties[2] = {
tag: huks.HuksTag.HUKS_TAG_KEY_SIZE,
value: huks.HuksKeySize.HUKS_DH_KEY_SIZE_4096
};
var options = {
properties: properties
};
var result = huks.finish(handle, options)
```
...@@ -4,17 +4,14 @@ ...@@ -4,17 +4,14 @@
HUAWEI DevEco Studio For OpenHarmony(以下简称DevEco Studio)是基于IntelliJ IDEA Community开源版本打造,面向OpenHarmony全场景多设备的一站式集成开发环境(IDE),为开发者提供工程模板创建、开发、编译、调试、发布等E2E的OpenHarmony应用/服务开发。 HUAWEI DevEco Studio For OpenHarmony(以下简称DevEco Studio)是基于IntelliJ IDEA Community开源版本打造,面向OpenHarmony全场景多设备的一站式集成开发环境(IDE),为开发者提供工程模板创建、开发、编译、调试、发布等E2E的OpenHarmony应用/服务开发。
[DevEco Studio 3.0 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) 作为支撑OpenHarmony应用和服务开发的IDE,具有以下能力特点: [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio/) 作为支撑OpenHarmony应用和服务开发的IDE,具有以下能力特点:
- 支持一站式的信息获取平台 - **高效智能代码编辑**:支持eTS、JavaScript、C/C++等语言的代码高亮、代码智能补齐、代码错误检查、代码自动跳转、代码格式化、代码查找等功能,提升代码编写效率。更多详细信息,请参考[编辑器使用技巧](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493)
- 提供多设备工程模板 - **低代码可视化开发**:丰富的UI界面编辑能力,支持自由拖拽组件和可视化数据绑定,可快速预览效果,所见即所得;同时支持卡片的零代码开发,降低开发门槛和提升界面开发效率。更多详细信息,请参考使用[低代码开发应用/服务](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)
- 高效的代码编辑 - **多端双向实时预览**:支持UI界面代码的双向预览、实时预览、动态预览、组件预览以及多端设备预览,便于快速查看代码运行效果。更多详细信息,请参考[使用预览器预览应用/服务界面效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596)
- 支持可视化的界面UI开发 - **全新构建体系**:通过Hvigor编译构建工具,一键完成应用及服务的编译和打包,更好地支持eTS/JS开发。
- 双向、极速的界面UI预览 - **一站式信息获取**:基于开发者了解、学习、开发、求助的用户旅程,在DevEco Studio中提供一站式的信息获取平台,高效支撑开发者活动。
- 全新的编译工具Hvigor - **高效代码调试**:提供TS、JS 、C/C++代码的断点设置,单步执行、变量查看等调试能力,提升应用及服务的问题分析效率。
- 支持基于设备系统能力集Syscap进行应用开发
- 支持全自动化的应用签名机制
- 丰富的代码调试调优能力
更多工具体验和使用指导请见:[DevEco Studio (OpenHarmony) 使用指南](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421) 更多工具体验和使用指导请见:[DevEco Studio (OpenHarmony) 使用指南](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421)
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。 应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。
对于系统特权应用,提供独立的能效资源申请接口。系统特权应用如果需要使用特定的系统资源,例如在被挂起期间仍然能够收到系统公共事件,可以使用能效资源申请接口。
> **说明:** > **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -201,7 +203,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want ...@@ -201,7 +203,7 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want
| bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 | | bgMode | [BackgroundMode](#backgroundmode8) | 是 | 向系统申请的后台模式。 |
| wantAgent | [WantAgent](js-apis-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。 | | wantAgent | [WantAgent](js-apis-wantAgent.md) | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。 |
**返回值** **返回值**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ---------------- | | -------------- | ---------------- |
| Promise\<void> | 使用Promise形式返回结果。 | | Promise\<void> | 使用Promise形式返回结果。 |
...@@ -279,7 +281,7 @@ stopBackgroundRunning(context: Context): Promise&lt;void&gt; ...@@ -279,7 +281,7 @@ stopBackgroundRunning(context: Context): Promise&lt;void&gt;
| ------- | ------- | ---- | ---------------------------------------- | | ------- | ------- | ---- | ---------------------------------------- |
| context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | | context | Context | 是 | 应用运行的上下文。<br>FA模型的应用Context定义见[Context](js-apis-Context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
**返回值** **返回值**
| 类型 | 说明 | | 类型 | 说明 |
| -------------- | ---------------- | | -------------- | ---------------- |
| Promise\<void> | 使用Promise形式返回结果。 | | Promise\<void> | 使用Promise形式返回结果。 |
...@@ -297,6 +299,64 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() ...@@ -297,6 +299,64 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(()
``` ```
## backgroundTaskManager.applyEfficiencyResources<sup>9+</sup>
applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest9)): boolean
向系统申请能效资源,使用boolean形式返回结果。
进程和它所属的应用可以同时申请某一类资源,例如CPU资源,但是应用释放资源的时候会将进程的资源一起释放。
**系统能力**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**系统API**: 此接口为系统接口。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ---------------------------------------- |
| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest9) | 是 | 请求的必要信息。包括资源类型,超时时间等信息。详见[EfficiencyResourcesRequest](#efficiencyresourcesrequest9)。 |
**返回值**
| 类型 | 说明 |
| -------------- | ---------------- |
| boolean | true代表申请成功,false代表申请失败。 |
**示例**
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: false,
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("result of applyEfficiencyResources is: " + res)
```
## backgroundTaskManager.resetAllEfficiencyResources<sup>9+</sup>
resetAllEfficiencyResources(): void
释放所有已经申请的资源。
**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**系统API**: 此接口为系统接口。
**示例**
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources();
```
## DelaySuspendInfo ## DelaySuspendInfo
延迟挂起信息。 延迟挂起信息。
...@@ -315,12 +375,47 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() ...@@ -315,12 +375,47 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(()
| 参数名 | 参数值 | 描述 | | 参数名 | 参数值 | 描述 |
| ----------------------- | ---- | --------------------- | | ----------------------- | ---- | --------------------- |
| DATA_TRANSFER | 1 | 数据传输 | | DATA_TRANSFER | 1 | 数据传输 |
| AUDIO_PLAYBACK | 2 | 音频播放 | | AUDIO_PLAYBACK | 2 | 音频播放 |
| AUDIO_RECORDING | 3 | 录音 | | AUDIO_RECORDING | 3 | 录音 |
| LOCATION | 4 | 定位导航 | | LOCATION | 4 | 定位导航 |
| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | | BLUETOOTH_INTERACTION | 5 | 蓝牙相关 |
| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | | MULTI_DEVICE_CONNECTION | 6 | 多设备互联 |
| WIFI_INTERACTION | 7 | WLAN相关<br />此接口为系统接口。 | | WIFI_INTERACTION | 7 | WLAN相关<br />此接口为系统接口。 |
| VOIP | 8 | 音视频通话<br />此接口为系统接口。 | | VOIP | 8 | 音视频通话<br />此接口为系统接口。 |
| TASK_KEEPING | 9 | 计算任务(仅在特定设备生效) | | TASK_KEEPING | 9 | 计算任务(仅在特定设备生效)。 |
\ No newline at end of file
## EfficiencyResourcesRequest<sup>9+</sup>
能效资源申请参数。
**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**系统API**: 此接口为系统接口。
| 参数名 | 类型 | 必填 | 说明 |
| --------------- | ------ | ---- | ---------------------------------------- |
| resourceTypes | number | 是 | 申请的资源类型。 |
| isApply | boolean | 是 | 申请资源或者是释放资源。 |
| timeOut | number | 是 | 资源的使用时间,以毫秒为单位。 |
| isPersist | boolean | 否 | 是否永久持有资源,如果是true,那么timeOut就无效。 |
| isProcess | boolean | 否 | 应用申请或者是进程申请。 |
| reason | string | 是 | 申请资源的原因。 |
## ResourceType<sup>9+</sup>
能效资源类型。
**系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
**系统API**: 此接口为系统接口。
| 参数名 | 参数值 | 描述 |
| ----------------------- | ---- | --------------------- |
| CPU | 1 | CPU资源,申请后不被挂起。 |
| COMMON_EVENT | 2 | 公共事件,申请后挂起状态下不被代理掉。 |
| TIMER | 4 | 计时器,申请后挂起状态下不被代理掉。 |
| WORK_SCHEDULER | 8 | 延迟任务,申请后有更长的执行时间。 |
| BLUETOOTH | 16 | 蓝牙相关,申请后挂起状态下不被代理掉。 |
| GPS | 32 | GPS相关,申请后挂起状态下不被代理掉。 |
| AUDIO | 64 | 音频资源,申请后挂起状态下不被代理掉。 |
\ No newline at end of file
...@@ -7,19 +7,19 @@ ...@@ -7,19 +7,19 @@
LauncherAbilityInfo信息 LauncherAbilityInfo信息,通过接口[innerBundleManager.getLauncherAbilityInfos](js-apis-Bundle-InnerBundleManager.md)获取。
## LauncherAbilityInfo ## LauncherAbilityInfo
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework。
**系统API:**此接口为系统接口,三方应用不支持调用 **系统API:** 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | | --------------- | ---------------------------------------------------- | ---- | ---- | -------------------------------------- |
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | launcher ability的应用程序的配置信息 | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | 是 | 否 | launcher ability的应用程序的配置信息。 |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 否 | launcher ability的ElementName信息 | | elementName | [ElementName](js-apis-bundle-ElementName.md) | 是 | 否 | launcher ability的ElementName信息。 |
| labelId | number | 是 | 否 | launcher ability的标签ID | | labelId | number | 是 | 否 | launcher ability的标签ID。 |
| iconId | number | 是 | 否 | launcher ability的图标ID | | iconId | number | 是 | 否 | launcher ability的图标ID。 |
| userId | number | 是 | 否 | launcher ability的用户ID | | userId | number | 是 | 否 | launcher ability的用户ID。 |
| installTime | number | 是 | 否 | launcher ability的安装时间 | | installTime | number | 是 | 否 | launcher ability的安装时间。 |
\ No newline at end of file \ No newline at end of file
...@@ -969,6 +969,8 @@ FA的使用信息的属性集合。 ...@@ -969,6 +969,8 @@ FA的使用信息的属性集合。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------------------- | ---------------------------------------- | ---- | ----------------------------- | | -------------------- | ---------------------------------------- | ---- | ----------------------------- |
| deviceId | string | 否 | FA所属deviceId。 | | deviceId | string | 否 | FA所属deviceId。 |
...@@ -990,6 +992,8 @@ FA卡片的使用信息的属性集合。 ...@@ -990,6 +992,8 @@ FA卡片的使用信息的属性集合。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | ------ | ---- | ----------- | | ---------------- | ------ | ---- | ----------- |
| formName | string | 是 | 卡片名称。 | | formName | string | 是 | 卡片名称。 |
...@@ -1004,6 +1008,8 @@ FA卡片的使用信息的属性集合。 ...@@ -1004,6 +1008,8 @@ FA卡片的使用信息的属性集合。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**系统API**:此接口为系统接口,三方应用不支持调用。
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ---------------- | ------ | ---- | ---------------- | | ---------------- | ------ | ---- | ---------------- |
| appUsageOldGroup | number | 是 | 变化前的应用分组 | | appUsageOldGroup | number | 是 | 变化前的应用分组 |
...@@ -1092,6 +1098,8 @@ FA卡片的使用信息的属性集合。 ...@@ -1092,6 +1098,8 @@ FA卡片的使用信息的属性集合。
**系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.AppGroup **系统能力**:以下各项对应的系统能力均为SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**系统API**:此接口为系统接口,三方应用不支持调用。
| 名称 | 默认值 | 说明 | | 名称 | 默认值 | 说明 |
| ------------------ | ---- | ----------------- | | ------------------ | ---- | ----------------- |
| ACTIVE_GROUP_ALIVE | 10 | 活跃分组。 | | ACTIVE_GROUP_ALIVE | 10 | 活跃分组。 |
......
...@@ -433,7 +433,7 @@ ws.off('open', callback1); ...@@ -433,7 +433,7 @@ ws.off('open', callback1);
on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void on\(type: 'message', callback: AsyncCallback<string | ArrayBuffer\>\): void
订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。 订阅WebSocket的接收到服务器消息事件,使用callback方式作为异步方法。每个消息最大长度为4K,超过4K自动分片。
>![](public_sys-resources/icon-note.gif) **说明:** >![](public_sys-resources/icon-note.gif) **说明:**
>AsyncCallback中的数据可以是字符串\(API 6\)或ArrayBuffer\(API 8\)。 >AsyncCallback中的数据可以是字符串\(API 6\)或ArrayBuffer\(API 8\)。
......
...@@ -14,7 +14,7 @@ import worker from '@ohos.worker'; ...@@ -14,7 +14,7 @@ import worker from '@ohos.worker';
## 属性 ## 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| ---------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------ | | ---------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------ |
...@@ -25,7 +25,7 @@ import worker from '@ohos.worker'; ...@@ -25,7 +25,7 @@ import worker from '@ohos.worker';
Worker构造函数的选项信息,用于为Worker添加其他信息。 Worker构造函数的选项信息,用于为Worker添加其他信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| ------ | --------- | ---- | ---- | ---------------------- | | ------ | --------- | ---- | ---- | ---------------------- |
...@@ -568,7 +568,7 @@ parentPort.onmessageerror= function(e) { ...@@ -568,7 +568,7 @@ parentPort.onmessageerror= function(e) {
明确数据传递过程中需要转移所有权对象的类,传递所有权的对象必须是ArrayBuffer。 明确数据传递过程中需要转移所有权对象的类,传递所有权的对象必须是ArrayBuffer。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | ---- | ---- | --------------------------------- | | -------- | -------- | ---- | ---- | --------------------------------- |
...@@ -579,7 +579,7 @@ parentPort.onmessageerror= function(e) { ...@@ -579,7 +579,7 @@ parentPort.onmessageerror= function(e) {
事件类。 事件类。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| --------- | -------- | ---- | ---- | ---------------------------------- | | --------- | -------- | ---- | ---- | ---------------------------------- |
...@@ -591,8 +591,7 @@ parentPort.onmessageerror= function(e) { ...@@ -591,8 +591,7 @@ parentPort.onmessageerror= function(e) {
事件监听类。 事件监听类。
(evt: Event): void | Promise&lt;void&gt;
### (evt: Event): void | Promise&lt;void&gt;
执行的回调函数。 执行的回调函数。
...@@ -624,7 +623,7 @@ workerInstance.addEventListener("alert", (e)=>{ ...@@ -624,7 +623,7 @@ workerInstance.addEventListener("alert", (e)=>{
错误事件类,用于表示Worker执行过程中出现异常的详细信息,ErrorEvent类继承[Event](#event) 错误事件类,用于表示Worker执行过程中出现异常的详细信息,ErrorEvent类继承[Event](#event)
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | ---- | ---- | -------------------- | | -------- | -------- | ---- | ---- | -------------------- |
...@@ -639,7 +638,7 @@ workerInstance.addEventListener("alert", (e)=>{ ...@@ -639,7 +638,7 @@ workerInstance.addEventListener("alert", (e)=>{
消息类,持有Worker线程间传递的数据。 消息类,持有Worker线程间传递的数据。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| ---- | -------- | ---- | ---- | ------------------ | | ---- | -------- | ---- | ---- | ------------------ |
...@@ -652,7 +651,7 @@ Worker线程自身的运行环境,WorkerGlobalScope类继承[EventTarget](#eve ...@@ -652,7 +651,7 @@ Worker线程自身的运行环境,WorkerGlobalScope类继承[EventTarget](#eve
### 属性 ### 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Utils.Lang。 **系统能力:** SystemCapability.Utils.Lang
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
| ---- | ------------------------------------------------------------ | ---- | ---- | --------------------------------------- | | ---- | ------------------------------------------------------------ | ---- | ---- | --------------------------------------- |
...@@ -694,6 +693,7 @@ parentPort.onerror = function(e){ ...@@ -694,6 +693,7 @@ parentPort.onerror = function(e){
### 内存模型 ### 内存模型
Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程可以创建多个Worker子线程,各个Worker线程间相互隔离,并通过序列化传递对象,等到Worker线程完成计算任务,再把结果返回给主线程。 Worker基于Actor并发模型实现。在Worker的交互流程中,JS主线程可以创建多个Worker子线程,各个Worker线程间相互隔离,并通过序列化传递对象,等到Worker线程完成计算任务,再把结果返回给主线程。
Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。 Actor并发模型的交互原理:各个Actor并发地处理主线程任务,每个Actor内部都有一个消息队列及单线程执行模块,消息队列负责接收主线程及其他Actor的请求,单线程执行模块则负责串行地处理请求、向其他Actor发送请求以及创建新的Actor。由于Actor采用的是异步方式,各个Actor之间相互隔离没有数据竞争,因此Actor可以高并发运行。
### 注意事项 ### 注意事项
......
...@@ -61,7 +61,7 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt ...@@ -61,7 +61,7 @@ GridRow(option?: {columns?: number | GridRowColumnOption, gutter?: Length | Gutt
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ----- | ------ | ---- | ---------------------------------------- | | ----- | ------ | ---- | ---------------------------------------- |
| value | Array&lt;string&gt; | 否 | 设置断点位置的单调递增数组。<br>默认值:["320vp", "520vp", "840vp"] | | value | Array&lt;string&gt; | 否 | 设置断点位置的单调递增数组。<br>默认值:["320vp", "520vp", "840vp"] |
| reference | BreakpointsReference | 否 | 竖直gutter option。 | | reference | BreakpointsReference | 否 | 断点切换参照物。 |
```ts ```ts
// 启用xs、sm、md共3个断点 // 启用xs、sm、md共3个断点
breakpoints: {value: ["100vp", "200vp"]} breakpoints: {value: ["100vp", "200vp"]}
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
## 接口 ## 接口
CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean}) CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, autoCancel?: boolean, alignment?: DialogAlignment, offset?: Offset, customStyle?: boolean,gridCount?: number})
- 参数 - 参数
......
...@@ -2,7 +2,9 @@ ...@@ -2,7 +2,9 @@
## 场景介绍 ## 场景介绍
应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。 应用或业务模块处于后台(无可见界面)时,如果有需要继续执行或者后续执行的业务,可基于业务类型,申请短时任务延迟挂起(Suspend)或者长时任务避免进入挂起状态。如果应用需要更加灵活的配置,可以申请能效资源。常见的使用能效资源的场景有:1.应用保证自己在一个时间段内不被挂起,直到任务完成;2.应用处于挂起状态时仍然需要系统的资源,例如闹钟需要计时器资源;3.延时任务需要不受到执行频率的限制,并且拥有更长的执行时间。
在挂起时如果需要单独的某种资源不被代理或者需要更长的延时任务执行时间,可以申请所需的能效资源。
## 短时任务 ## 短时任务
...@@ -486,6 +488,93 @@ export default class BgTaskAbility extends Ability { ...@@ -486,6 +488,93 @@ export default class BgTaskAbility extends Ability {
}; };
``` ```
## 能效资源申请
### 接口说明
**表1** 能效资源申请主要接口
| 接口名 | 描述 |
| ---------------------------------------- | ---------------------------------------- |
| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-backgroundTaskManager.md#efficiencyresourcesrequest9)): boolean | 申请能效资源。 |
| resetAllEfficiencyResources():void | 释放申请的能效资源。 |
### 开发步骤
1. 申请能效资源
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: true,
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
```
2. 释放申请的部分资源
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: false,
timeOut: 0,
reason: "reset",
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
```
3. 释放申请的所有资源
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources();
```
### 开发实例
```js
import backgroundTaskManager from '@ohos.backgroundTaskManager';
// 申请能效资源
let request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT |
backgroundTaskManager.ResourceType.TIMER,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: true,
};
let res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
// 释放部分资源
request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT,
isApply: false,
timeOut: 0,
reason: "reset",
};
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
// 释放全部资源
backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources();
```
## 相关实例 ## 相关实例
基于后台任务管理,有以下相关实例可供参考: 基于后台任务管理,有以下相关实例可供参考:
......
# 后台任务概述 # 后台任务概述
后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。 后台应用频繁活动,会造成用户设备耗电快、卡顿等现象。因此,为了支撑性能、功耗诉求,系统仅允许应用在后台执行规范内的活动,规范外的活动默认会被挂起,当资源不足时会被回收。同时,应用可以申请能效资源,保证自己在一段时间内不会被挂起,或者在挂起状态能够正常使用一些资源,例如公共事件、计时器等。
## 后台任务类型 ## 后台任务类型
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
**3. 长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。 **3. 长时任务** :如果是用户发起的可感知业务需要长时间后台运行,如后台播放音乐、导航、设备连接、VoIP等,则使用长时任务避免进入挂起(Suspend)状态。
**4. 能效资源** :能效资源包括CPU资源、WORK_SCHEDULER资源、软件资源(COMMON_EVENT, TIMER)、硬件资源(GPS, BLUETOOTH)。如果应用或者进程申请了能效资源,那么根据能效资源的类型会拥有相应的特权,例如申请了CPU资源的可以不被挂起,申请了WORK_SCHEDULER后延时任务可以拥有更长的执行时间。
## 短时任务 ## 短时任务
...@@ -60,3 +62,25 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业 ...@@ -60,3 +62,25 @@ OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业
- 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。 - 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。
- 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 - 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。
- 一个Ability同一时刻只能申请运行一个长时任务。 - 一个Ability同一时刻只能申请运行一个长时任务。
## 能效资源申请
能效资源可以分为四种,CPU资源,WORK_SCHEDULER资源,软件资源(COMMON_EVENT,TIMER),硬件资源(GPS,BLOOTOOTH,AUDIO)。
应用或进程申请能效资源后能够获得相应特权,例如:申请CPU资源后可以不被挂起;申请WORK_SCHEDULER资源后不受延迟任务执行频率约束,且任务执行时间增加;申请软件、硬件资源后,相关资源在挂起状态下不被代理。
**表1** 能效资源种类
| 参数名 | 参数值 | 描述 |
| ----------------------- | ---- | --------------------- |
| CPU | 1 | CPU资源,申请后不被挂起 |
| COMMON_EVENT | 2 | 公共事件,申请后挂起状态下不被代理掉 |
| TIMER | 4 | 计时器,申请后挂起状态下不被代理掉 |
| WORK_SCHEDULER | 8 | 延迟任务,申请后有更长的执行时间 |
| BLUETOOTH | 16 | 蓝牙相关,申请后挂起状态下不被代理掉 |
| GPS | 32 | GPS相关,申请后挂起状态下不被代理掉 |
| AUDIO | 64 | 音频资源,申请后挂起状态下不被代理掉 |
### 能效资源使用约束
- 能效资源申请或者释放可以由进程或者应用发起,由应用发起的资源释放会释放属于它的同类型的所有资源,包括进程申请的资源。例如应用申请了CPU资源,进程申请了CPU和WORK_SCHEDULER资源,当应用释放CPU资源的时候,会将进程的CPU资源一同释放,同时不同类型的WORK_SCHEDULER资源不受影响。由进程发起的资源释放对应用申请的资源没有影响,例如当应用和进程同时申请了CPU,进程发起了CPU资源释放,应用的CPU资源不会被释放。
- 同时申请同一类持久资源和非持久资源,持久资源会覆盖非持久资源,在超时时不会释放资源。例如应用首先申请了10s的CPU资源,然后在第5s的时候申请了持久的CPU资源,那么资源会变成持久的,非持久的CPU资源记录会被持久化的CPU资源记录覆盖,到了第10s的时候资源不会被释放,如果在第8s的时候提前释放了资源,那么会将CPU资源释放,无法单独释放其中非持久的或者持久的CPU资源。
- WORK_SCHEDULER资源只能由应用申请和释放,不能由进程申请和释放。
...@@ -10,8 +10,8 @@ ...@@ -10,8 +10,8 @@
延迟调度任务的使用需要遵从如下约束和规则: 延迟调度任务的使用需要遵从如下约束和规则:
- **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。 - **超时**:系统会设置超时机制,延迟任务回调只允许运行一段时间,超时之后,系统会主动停止。默认的超时限制为2分钟,对于系统应用,可以通过[能效资源申请接口](background-task-overview.md#能效资源申请)获取更长的执行时间(充电状态20分钟,非充电状态10分钟)。
- **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。 - **执行频率**:系统会根据应用的活跃度对延迟任务做分级管控,限制延迟任务调度的执行频率。对于通过能效资源接口申请了WORK_SCHEDULER资源的应用,在资源的有效期内,它的延迟任务执行频率不受限制。
应用分组 | 延迟任务执行频率约束 应用分组 | 延迟任务执行频率约束
--------------------|------------------------- --------------------|-------------------------
...@@ -21,6 +21,7 @@ ...@@ -21,6 +21,7 @@
不经常使用 | 最小间隔48小时 不经常使用 | 最小间隔48小时
受限分组 | 禁止 受限分组 | 禁止
未使用分组 | 禁止 未使用分组 | 禁止
[能效资源豁免分组](../reference/apis/js-apis-backgroundTaskManager.md#resourcetype9) | 执行频率不受限制
- **WorkInfo设置参数约束** - **WorkInfo设置参数约束**
......
...@@ -7,9 +7,9 @@ ...@@ -7,9 +7,9 @@
手势识别模块作为端侧设备不可或缺的一部分,为用户提供手势识别控制能力。当前支持的手势识别类型有拿起、翻转、摇一摇、旋转屏等。 手势识别模块作为端侧设备不可或缺的一部分,为用户提供手势识别控制能力。当前支持的手势识别类型有拿起、翻转、摇一摇、旋转屏等。
基于HDF(Hardware Driver Foundation)驱动框架开发的Motion驱动,能够屏蔽硬件器件差异,为上层MSDP(Multimodal Sensor 基于HDF(Hardware Driver Foundation)驱动框架开发的Motion驱动,能够屏蔽硬件器件差异,为上层MSDP(Multimodal Sensor
Data Platform)服务层提供稳定的手势识别控制能力接口,包括手势识别使能/去使能、手势识别订阅/订阅等。 Data Platform)服务层提供稳定的手势识别控制能力接口,包括手势识别使能/去使能、手势识别订阅/取消订阅等。
Motion驱动框架如图1所示,上层为Framework层,提供MSDP服务,通过UHDF(User Hardware Driver Foundation)层的Motion Proxy与Motion Stub进行交互;而Motion Stub可调用Motion HDI实现类接口,从而实现上层服务的手势识别使能/去使能、手势识别订阅/订阅等能力。 Motion驱动框架如图1所示,上层为Framework层,提供MSDP服务,通过UHDF(User Hardware Driver Foundation)层的Motion Proxy与Motion Stub进行交互;而Motion Stub可调用Motion HDI实现类接口,从而实现上层服务的手势识别使能/去使能、手势识别订阅/取消订阅等能力。
**图1** Motion驱动框架 **图1** Motion驱动框架
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册