diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md index 0e4e7c257cbde0853a36bd8a3729ee707a4b2391..b2992e7c9958f0a1ffd87db9e4549bf0187bad78 100644 --- a/en/application-dev/dfx/apprecovery-guidelines.md +++ b/en/application-dev/dfx/apprecovery-guidelines.md @@ -17,7 +17,7 @@ The application recovery APIs are provided by the **appRecovery** module, which | API | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. | +| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. | | saveAppState(): boolean; | Saves the ability status of an application. | | restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.| diff --git a/en/application-dev/faqs/faqs-dfx.md b/en/application-dev/faqs/faqs-dfx.md index ec1c8dbfedd5fa3c087c96d54c9c2aab73d75e8a..9fc12a1b1c26e109240702cca50e50b77495bdf5 100644 --- a/en/application-dev/faqs/faqs-dfx.md +++ b/en/application-dev/faqs/faqs-dfx.md @@ -6,7 +6,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5 1. Locate the crash-related code based on the service log. -2. View the error information in the crash file. The crash file is located at **/data/log/faultlog/faultlogger/**. +2. View the error information in the crash file, which is located at **/data/log/faultlog/faultlogger/**. ## Why cannot access controls in the UiTest test framework? diff --git a/en/application-dev/faqs/faqs-language.md b/en/application-dev/faqs/faqs-language.md index 4c0a6cba384f4e94832a6a4a933aebeee4b2f364..db7e95d5ede5c3bead52e16bceb16e90c6188b79 100644 --- a/en/application-dev/faqs/faqs-language.md +++ b/en/application-dev/faqs/faqs-language.md @@ -51,9 +51,9 @@ build() { Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -1. Obtain data in Uint8Array format by calling the **RawFile** API of **resourceManager**. +1. Obtain Uint8Array data by calling the **RawFile** API of **resourceManager**. -2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API. +2. Convert the Uint8Array data to strings by calling the **String.fromCharCode** API. Reference: [Resource Manager](../reference/apis/js-apis-resource-manager.md) diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md index 048716dfdcd76d0e35f4ed3ad70a5eeb266ac8cc..fb4e648b56839ef76cb0e5277443605734d7ab6f 100644 --- a/en/application-dev/media/image.md +++ b/en/application-dev/media/image.md @@ -19,112 +19,121 @@ const color = new ArrayBuffer(96); // Create a buffer to store image pixel data. let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data. // Create a PixelMap object. -const color = new ArrayBuffer(96); -let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } image.createPixelMap(color, opts, (err, pixelmap) => { console.log('Succeeded in creating pixelmap.'); -}) - -// Read pixels. -const area = { - pixels: new ArrayBuffer(8), - offset: 0, - stride: 8, - region: { size: { height: 1, width: 2 }, x: 0, y: 0 } -} -pixelmap.readPixels(area,() => { - var bufferArr = new Uint8Array(area.pixels); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - console.info(' buffer ' + bufferArr[i]); - if(res) { - if(bufferArr[i] == 0) { - res = false; - console.log('readPixels end.'); - break; - } - } + // Failed to create the PixelMap object. + if (err) { + console.info('create pixelmap failed, err' + err); + return } -}) - -// Store pixels. -const readBuffer = new ArrayBuffer(96); -pixelmap.readPixelsToBuffer(readBuffer,() => { - var bufferArr = new Uint8Array(readBuffer); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== 0) { - res = false; - console.log('readPixelsToBuffer end.'); - break; - } - } + + // Read pixels. + const area = { + pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } } -}) - -// Write pixels. -pixelmap.writePixels(area,() => { - const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} - pixelmap.readPixels(readArea,() => { - var readArr = new Uint8Array(readArea.pixels); - var res = true; - for (var i = 0; i < readArr.length; i++) { + pixelmap.readPixels(area,() => { + let bufferArr = new Uint8Array(area.pixels); + let res = true; + for (let i = 0; i < bufferArr.length; i++) { + console.info(' buffer ' + bufferArr[i]); if(res) { - if (readArr[i] !== 0) { + if(bufferArr[i] == 0) { res = false; - console.log('readPixels end.please check buffer'); + console.log('readPixels end.'); break; } } } }) -}) - -// Write pixels to the buffer. -pixelmap.writeBufferToPixels(writeColor).then(() => { + + // Store pixels. const readBuffer = new ArrayBuffer(96); - pixelmap.readPixelsToBuffer(readBuffer).then (() => { - var bufferArr = new Uint8Array(readBuffer); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { + pixelmap.readPixelsToBuffer(readBuffer,() => { + let bufferArr = new Uint8Array(readBuffer); + let res = true; + for (let i = 0; i < bufferArr.length; i++) { if(res) { - if (bufferArr[i] !== i) { + if (bufferArr[i] !== 0) { res = false; - console.log('readPixels end.please check buffer'); + console.log('readPixelsToBuffer end.'); break; } } } }) -}) + + // Write pixels. + pixelmap.writePixels(area,() => { + const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} + pixelmap.readPixels(readArea,() => { + let readArr = new Uint8Array(readArea.pixels); + let res = true; + for (let i = 0; i < readArr.length; i++) { + if(res) { + if (readArr[i] !== 0) { + res = false; + console.log('readPixels end.please check buffer'); + break; + } + } + } + }) + }) -// Obtain image information. -pixelmap.getImageInfo((error, imageInfo) => { - if (imageInfo !== null) { - console.log('Succeeded in getting imageInfo'); - } -}) + const writeColor = new ArrayBuffer(96); // Pixel data of the image. + // Write pixels to the buffer. + pixelmap.writeBufferToPixels(writeColor).then(() => { + const readBuffer = new ArrayBuffer(96); + pixelmap.readPixelsToBuffer(readBuffer).then (() => { + let bufferArr = new Uint8Array(readBuffer); + let res = true; + for (let i = 0; i < bufferArr.length; i++) { + if(res) { + if (bufferArr[i] !== i) { + res = false; + console.log('readPixels end.please check buffer'); + break; + } + } + } + }) + }) -// Release the PixelMap object. -pixelmap.release(()=>{ - console.log('Succeeded in releasing pixelmap'); + // Obtain image information. + pixelmap.getImageInfo((err, imageInfo) => { + // Failed to obtain the image information. + if (err || imageInfo == null) { + console.info('getImageInfo failed, err' + err); + return + } + if (imageInfo !== null) { + console.log('Succeeded in getting imageInfo'); + } + }) + + // Release the PixelMap object. + pixelmap.release(()=>{ + console.log('Succeeded in releasing pixelmap'); + }) }) // Create an image source (uri). let path = '/data/local/tmp/test.jpg'; -const imageSourceApi = image.createImageSource(path); +const imageSourceApi1 = image.createImageSource(path); // Create an image source (fd). let fd = 29; -const imageSourceApi = image.createImageSource(fd); +const imageSourceApi2 = image.createImageSource(fd); // Create an image source (data). const data = new ArrayBuffer(96); -const imageSourceApi = image.createImageSource(data); +const imageSourceApi3 = image.createImageSource(data); // Release the image source. -imageSourceApi.release(() => { +imageSourceApi3.release(() => { console.log('Succeeded in releasing imagesource'); }) @@ -133,6 +142,10 @@ const imagePackerApi = image.createImagePacker(); const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, (err, data) => { + if (err) { + console.info('packing from imagePackerApi failed, err' + err); + return + } console.log('Succeeded in packing'); }) @@ -161,36 +174,33 @@ let decodingOptions = { // Create a pixel map in callback mode. imageSourceApi.createPixelMap(decodingOptions, (err, pixelmap) => { + // Failed to create the PixelMap object. + if (err) { + console.info('create pixelmap failed, err' + err); + return + } console.log('Succeeded in creating pixelmap.'); }) // Create a pixel map in promise mode. imageSourceApi.createPixelMap().then(pixelmap => { console.log('Succeeded in creating pixelmap.'); -}) - -// Capture error information when an exception occurs during function invoking. -catch(error => { - console.log('Failed in creating pixelmap.' + error); -}) -// Obtain the number of bytes in each line of pixels. -var num = pixelmap.getBytesNumberPerRow(); + // Obtain the number of bytes in each line of pixels. + let num = pixelmap.getBytesNumberPerRow(); -// Obtain the total number of pixel bytes. -var pixelSize = pixelmap.getPixelBytesNumber(); + // Obtain the total number of pixel bytes. + let pixelSize = pixelmap.getPixelBytesNumber(); -// Obtain the pixel map information. -pixelmap.getImageInfo().then( imageInfo => {}); + // Obtain the pixel map information. + pixelmap.getImageInfo().then( imageInfo => {}); -// Release the PixelMap object. -pixelmap.release(()=>{ - console.log('Succeeded in releasing pixelmap'); -}) - -// Capture release failure information. -catch(error => { - console.log('Failed in releasing pixelmap.' + error); + // Release the PixelMap object. + pixelmap.release(()=>{ + console.log('Succeeded in releasing pixelmap'); + }) +}).catch(error => { + console.log('Failed in creating pixelmap.' + error); }) ``` @@ -216,7 +226,7 @@ if (imagePackerApi == null) { } // Set encoding parameters if the image packer is successfully created. -let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. +let packOpts = { format:"image/jpeg", // The supported encoding format is jpg. quality:98 } // Image quality, which ranges from 0 to 100. // Encode the image. @@ -233,8 +243,9 @@ imageSourceApi.getImageInfo((err, imageInfo) => { console.log('Succeeded in getting imageInfo'); }) +const array = new ArrayBuffer(100); // Incremental data. // Update incremental data. -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error, data)=> {}) +imageSourceApi.updateData(array, false, 0, 10,(error, data)=> {}) ``` @@ -246,10 +257,15 @@ Example scenario: The camera functions as the client to transmit image data to t public async init(surfaceId: any) { // (Server code) Create an ImageReceiver object. - var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1); + let receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1); // Obtain the surface ID. receiver.getReceivingSurfaceId((err, surfaceId) => { + // Failed to obtain the surface ID. + if (err) { + console.info('getReceivingSurfaceId failed, err' + err); + return + } console.info("receiver getReceivingSurfaceId success"); }); // Register a surface listener, which is triggered after the buffer of the surface is ready. diff --git a/en/application-dev/quick-start/resource-categories-and-access.md b/en/application-dev/quick-start/resource-categories-and-access.md index d1d342fe74eaed80516a7ca554cbe84f84ad927c..b79359a99ee1f7ecf434a7858a7ee1999b9af5d5 100644 --- a/en/application-dev/quick-start/resource-categories-and-access.md +++ b/en/application-dev/quick-start/resource-categories-and-access.md @@ -230,27 +230,27 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile( > > The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md) API. -In the **.ets** file, you can use the resources defined in the **resources** directory. +In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories): ```ts Text($r('app.string.string_hello')) - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) Text($r('app.string.string_world')) - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) -} - -Text($r('app.string.message_arrive', "five of the clock")) // Reference string resources. The second parameter of $r is used to replace %s. - .fontColor($r('app.color.color_hello')) - .fontSize($r('app.float.font_hello')) -} - -Text($r('app.plural.eat_apple', 5, 5)) // Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d. - .fontColor($r('app.color.color_world')) - .fontSize($r('app.float.font_world')) + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) + +// Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five'o clock". +Text($r('app.string.message_arrive', "five'o clock")) + .fontColor($r('app.color.color_hello')) + .fontSize($r('app.float.font_hello')) + +// Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d. +// The value is "5 apple" in singular form and "5 apples" in plural form. +Text($r('app.plural.eat_apple', 5, 5)) + .fontColor($r('app.color.color_world')) + .fontSize($r('app.float.font_world')) } Image($r('app.media.my_background_image')) // Reference media resources. @@ -274,14 +274,20 @@ To reference a system resource, use the **"$r('sys.type.resource_id')"** format. ```ts Text('Hello') - .fontColor($r('sys.color.ohos_id_color_emphasize')) - .fontSize($r('sys.float.ohos_id_text_size_headline1')) - .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) - .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) + .fontColor($r('sys.color.ohos_id_color_emphasize')) + .fontSize($r('sys.float.ohos_id_text_size_headline1')) + .fontFamily($r('sys.string.ohos_id_text_font_family_medium')) + .backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) + Image($r('sys.media.ohos_app_icon')) - .border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2}) - .margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) - .height(200) - .width(300) + .border({ + color: $r('sys.color.ohos_id_color_palette_aux1'), + radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2 + }) + .margin({ + top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), + bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l') + }) + .height(200) + .width(300) ``` - diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 56596e1ffdb8e011627fa026240375ce1094d9ea..82741c1432d9d4fd9c5babef17548bb643cf2dd9 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -55,7 +55,7 @@ Initiates a call based on the specified options. This API uses an asynchronous c | Name | Type | Mandatory | Description | | ----------- | ---------------------------- | ---- | --------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. | +| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure | **Example** @@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the specified p | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number options. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | **Example** @@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | No | Number formatting options, for example, country code. | | callback | AsyncCallback<string> | Yes | Callback used to return the result. | **Example** @@ -566,33 +566,6 @@ promise.then(data => { }); ``` -## call.answer7+ - -answer\(callback: AsyncCallback\): void - -Answers a call. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permission**: ohos.permission.ANSWER_CALL - -**System capability**: SystemCapability.Telephony.CallManager - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -call.answer((err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); -``` - - ## call.answer7+ answer\(callId: number, callback: AsyncCallback\): void @@ -658,7 +631,7 @@ promise.then(data => { ## call.hangup7+ -hangup\(callback: AsyncCallback\): void +hangup\(callId: number, callback: AsyncCallback\): void Ends a call. This API uses an asynchronous callback to return the result. @@ -672,22 +645,23 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -call.hangup((err, data) => { +call.hangup(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.hangup7+ +## call.answer9+ -hangup\(callId: number, callback: AsyncCallback\): void +answer\(callback: AsyncCallback\): void -Ends a call based on the specified call ID. This API uses an asynchronous callback to return the result. +Answers a call.This API uses an asynchronous callback to return the result. This is a system API. @@ -699,13 +673,12 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------------------------- | -| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -call.hangup(1, (err, data) => { +call.answer((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -746,11 +719,11 @@ promise.then(data => { }); ``` -## call.reject7+ +## call.hangup9+ -reject\(callback: AsyncCallback\): void +hangup\(callback: AsyncCallback\): void -Rejects a call. This API uses an asynchronous callback to return the result. +Ends a call. This API uses an asynchronous callback to return the result. This is a system API. @@ -767,38 +740,7 @@ This is a system API. **Example** ```js -call.reject((err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); -``` - - -## call.reject7+ - -reject\(options: RejectMessageOptions, callback: AsyncCallback\): void - -Rejects a call based on the specified options. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permission**: ohos.permission.ANSWER_CALL - -**System capability**: SystemCapability.Telephony.CallManager - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | -------------- | -| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - -```js -let rejectMessageOptions={ - messageContent: "Unknown number blocked" -} -call.reject(rejectMessageOptions, (err, data) => { +call.hangup((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -903,6 +845,65 @@ promise.then(data => { }); ``` + +## call.reject9+ + +reject\(callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example:** + +```js +call.reject((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject9+ + +reject\(options: RejectMessageOptions, callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | -------------- | +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example:** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + ## call.holdCall7+ holdCall\(callId: number, callback: AsyncCallback\): void @@ -1344,8 +1345,8 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.

- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| **Example** @@ -2399,7 +2400,7 @@ promise.then(data => { }); ``` -## call.setAudioDevice8+ +## call.setAudioDevice9+ setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void @@ -2425,7 +2426,7 @@ call.setAudioDevice(1, (err, data) => { ``` -## call.setAudioDevice8+ +## call.setAudioDevice9+ setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\): void diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index e990ecf8126054b0de5ad52308c4f83843782d97..08bf0cfe66b40f46262765048463081b9c1a66a6 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,13 +1,10 @@ # Internationalization – I18N - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. +The I18N module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. > **NOTE** -> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). - +> 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 @@ -247,9 +244,9 @@ This is a system API. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ----- | ----- | +| language | string | Yes | Language ID.| **Error codes** @@ -313,9 +310,9 @@ This is a system API. **Parameters** -| Name | Type | Description | -| ------ | ------ | ----- | -| region | string | Region ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ----- | ----- | +| region | string | Yes | Region ID.| **Error codes** @@ -379,9 +376,9 @@ This is a system API. **Parameters** -| Name | Type | Description | -| ------ | ------ | --------------- | -| locale | string | System locale ID, for example, **zh-CN**.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ----- | ----- | +| locale | string | Yes | System locale ID, for example, **zh-CN**.| **Error codes** @@ -713,9 +710,9 @@ Checks whether the localized script for the specified language is displayed from **Parameters** -| Name | Type | Description | -| ------ | ------ | ------- | -| locale | string | Locale ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ----- | ----- | +| locale | string | Yes | Locale ID.| **Return value** @@ -905,7 +902,7 @@ Sets the start day of a week for this **Calendar** object. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | --------------------- | -| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +| value | number | Yes | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| **Example** ```js @@ -947,7 +944,7 @@ Sets the minimum number of days in the first week of a year. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------ | -| value | number | No | Minimum number of days in the first week of a year.| +| value | number | Yes | Minimum number of days in the first week of a year.| **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 79cdf3ac5627984eba2f03e7eb37b9cc7137de4a..e3cb7bbfd684ae315d6d54363183401442f5167a 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,6 +1,6 @@ # Internationalization – Intl -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. +The Intl module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 6680ea14f2ea3daa0d9144013469cf094c4904d2..a1261ce5d59d661af602b3ff3657a22ba3538764 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -2,7 +2,8 @@ The Keycode module provides keycodes for a key device. -> **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. ## Modules to Import @@ -337,7 +338,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode'; | KEYCODE_WWAN_WIMAX | number | Yes| No| WWAN WiMAX key| | KEYCODE_RFKILL | number | Yes| No| RF Kill key| | KEYCODE_CHANNEL | number | Yes| No| Channel key| -| KEYCODE_BTN_0 | number | Yes| No| Key 0| +| KEYCODE_BTN_0 | number | Yes| No| Button 0| | KEYCODE_BTN_1 | number | Yes| No| Button 1| | KEYCODE_BTN_2 | number | Yes| No| Button 2| | KEYCODE_BTN_3 | number | Yes| No| Button 3| diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index 31414ab325572d7ed25a31b1b3a78a725dce39e6..2fbe0e1c1d90b155fc52702d1dc69982e511c140 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -332,7 +332,6 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetConnected reportNetConnected(netHandle: NetHandle): Promise<void> @@ -490,7 +489,6 @@ connection.getAddressesByName(host).then(function (addresses) { }) ``` - ## connection.enableAirplaneMode enableAirplaneMode(callback: AsyncCallback\): void @@ -539,7 +537,6 @@ connection.enableAirplaneMode().then(function (error) { }) ``` - ## connection.disableAirplaneMode disableAirplaneMode(callback: AsyncCallback\): void @@ -588,7 +585,6 @@ connection.disableAirplaneMode().then(function (error) { }) ``` - ## connection.createNetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -825,7 +821,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | Name| Type | Description | | ------ | ------ | ------------------------- | -| netId | number | Network ID. The value must be greater than or equal to 100.| +| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| ### bindSocket @@ -847,33 +843,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses **Example** ```js -connection.getDefaultNet().then(function (netHandle) { +import socket from "@ohos.net.socket"; +connection.getDefaultNet().then((netHandle)=>{ var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); - let socketType = "xxxx"; + let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { - netHandle.bindSocket(tcp, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + if (err) { + console.log('bind fail'); + } + netHandle.bindSocket(tcp, (error, data)=>{ + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); + } + }) }) } else { + let callback = value => { + console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + } udp.on('message', callback); udp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { + if (err) { + console.log('bind fail'); + } udp.on('message', (data) => { - console.log(JSON.stringify(data)) - }); - netHandle.bindSocket(udp, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + console.log(JSON.stringify(data)) }); + netHandle.bindSocket(udp,(error, data)=>{ + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); + } + }) }) - } -} + } +}) ``` ### bindSocket @@ -901,31 +914,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses **Example** ```js -connection.getDefaultNet().then(function (netHandle) { +import socket from "@ohos.net.socket"; +connection.getDefaultNet().then((netHandle)=>{ var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); - let socketType = "xxxx"; - if(socketType == "TCPSocket") { + let socketType = "TCPSocket"; + if (socketType == "TCPSocket") { tcp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { - netHandle.bindSocket(tcp).then(err, data) { - console.log(JSON.stringify(data)) + if (err) { + console.log('bind fail'); + } + netHandle.bindSocket(tcp).then((err, data) => { + if (err) { + console.log(JSON.stringify(err)); + } else { + console.log(JSON.stringify(data)); + } + }) }) } else { + let callback = value => { + console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + } udp.on('message', callback); udp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { + if (err) { + console.log('bind fail'); + } udp.on('message', (data) => { - console.log(JSON.stringify(data)) - }); - netHandle.bindSocket(tcp).then(err, data) { - console.log(JSON.stringify(data)) - }); + console.log(JSON.stringify(data)); + }) + netHandle.bindSocket(udp).then((err, data) => { + if (err) { + console.log(JSON.stringify(err)); + } else { + console.log(JSON.stringify(data)); + } + }) }) - } -} + } +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 23284aeb1715a3f8aed9ec7b2d79ad55d1408319..c63c09c5a84bbec34b5b2274d3089fad4fbb603b 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,6 +1,6 @@ # Network Sharing Management -The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. +The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, and Bluetooth sharing. It also allows you to query the network sharing state and shared mobile data volume. > **NOTE** > @@ -405,7 +405,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses **Example** ```js -import SharingIfaceState from '@ohos.net.sharing' +import SharingIfaceType from '@ohos.net.sharing' sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); @@ -498,7 +498,7 @@ Obtains the network sharing state of the specified type. This API uses a promise ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => { +sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -525,8 +525,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch **Example** ```js -import SharingIfaceState from '@ohos.net.sharing' -sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -565,7 +565,7 @@ sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { }); ``` -## on('sharingStateChange') +## sharing.on('sharingStateChange') on(type: 'sharingStateChange', callback: Callback\): void @@ -591,7 +591,7 @@ sharing.on('sharingStateChange', (error, data) => { }); ``` -## off('sharingStateChange') +## sharing.off('sharingStateChange') off(type: 'sharingStateChange', callback?: Callback\): void @@ -617,7 +617,7 @@ sharing.off('sharingStateChange', (error, data) => { }); ``` -## on('interfaceSharingStateChange') +## sharing.on('interfaceSharingStateChange') on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void @@ -643,7 +643,7 @@ sharing.on('interfaceSharingStateChange', (error, data) => { }); ``` -## off('interfaceSharingStateChange') +## sharing.off('interfaceSharingStateChange') off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void @@ -669,7 +669,7 @@ sharing.off('interfaceSharingStateChange', (error, data) => { }); ``` -## on('sharingUpstreamChange') +## sharing.on('sharingUpstreamChange') on(type: 'sharingUpstreamChange', callback: Callback\): void @@ -695,7 +695,7 @@ sharing.on('sharingUpstreamChange', (error, data) => { }); ``` -## off('sharingUpstreamChange') +## sharing.off('sharingUpstreamChange') off(type: 'sharingUpstreamChange', callback?: Callback\): void @@ -735,12 +735,12 @@ Enumerates the network sharing states of an NIC. ## SharingIfaceType -Enumerates the network sharing types of an NIC. +Enumerates the network sharing types of an NIC. **System capability**: SystemCapability.Communication.NetManager.Core | Name | Value | Description | | ------------------------ | ---- | ---------------------- | | SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| -| SHARING_USB | 1 | USB sharing.| +| SHARING_USB | 1 | USB sharing (not supported currently).| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index a6fcacc4333ab0aa48dae7cd8b629e1e77bb399f..ad7d19b4ab7a3cfa6593c81f2c70b52f403aa4d1 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -531,8 +531,8 @@ Enumerates SIM card types and states. **System capability**: SystemCapability.Telephony.StateRegistry -| Name | Type | Description | -| ----------------- | --------------------- | ------------------------------------------------------------ | -| type | [CardType](js-apis-sim.md#cardtype) | SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| -| state | [SimState](js-apis-sim.md#simstate) | SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| -| reason8+ | [LockReason](#lockreason8) | SIM card lock type.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| type | [CardType](js-apis-sim.md#cardtype) | Yes| SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| +| state | [SimState](js-apis-sim.md#simstate) | Yes| SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| +| reason8+ | [LockReason](#lockreason8) | Yes| SIM card lock type.| diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index 06bb32eecce0d9b40133160a8689c6b80c27ad61..ed71da2336509844e7baa5eea49f8a026e969eba 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -142,7 +142,7 @@ Sets the mouse movement speed. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------------------------------- | | speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**. | -| callback | AysncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -349,7 +349,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t | ------------ | ------------------------------ | ---- | ----------------------------------- | | windowId | number | Yes | Window ID. | | pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. | -| callback | AysncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 01d439fd2e3e9d1202aa6969cb15fda67fa9059d..91c6be9cd7d076dbb72a502e64363d729668972f 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1734,8 +1734,8 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci **Example** ```js -radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1763,8 +1763,8 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec **Example** ```js -radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1797,10 +1797,10 @@ Defines the signal strength. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------- | --------------------------- | ------------------ | -| signalType | [NetworkType](#networktype) | Signal strength type.| -| signalLevel | number | Signal strength level.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| signalType | [NetworkType](#networktype) | Yes| Signal strength type.| +| signalLevel | number | Yes| Signal strength level.| ## NetworkType @@ -1825,17 +1825,17 @@ Defines the network status. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------------- | --------------------- | ------------------------------------------------------------ | -| longOperatorName | string | Long carrier name of the registered network.| -| shortOperatorName | string | Short carrier name of the registered network.| -| plmnNumeric | string | PLMN code of the registered network.| -| isRoaming | boolean | Whether the user is roaming.| -| regState | [RegState](#regstate) | Network registration status of the device.| -| cfgTech8+ | [RadioTechnology](#radiotechnology) | RAT of the device.| -| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.| -| isCaActive | boolean | CA status.| -| isEmergency | boolean | Whether only emergency calls are allowed.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| longOperatorName | string | Yes | Long carrier name of the registered network.| +| shortOperatorName | string | Yes | Short carrier name of the registered network.| +| plmnNumeric | string | Yes | PLMN code of the registered network.| +| isRoaming | boolean | Yes | Whether the user is roaming.| +| regState | [RegState](#regstate) | Yes | Network registration status of the device.| +| cfgTech8+ | [RadioTechnology](#radiotechnology) | Yes | RAT of the device.| +| nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device.| +| isCaActive | boolean | Yes | CA status.| +| isEmergency | boolean | Yes | Whether only emergency calls are allowed.| ## RegState @@ -1933,13 +1933,13 @@ Defines the cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| networkType | [NetworkType](#networktype) | Network type of the cell. | -| isCamped | boolean | Status of the cell. | -| timeStamp | number | Timestamp when cell information is obtained. | -| signalInformation | [SignalInformation](#signalinformation) | Signal information. | -| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| networkType | [NetworkType](#networktype) | Yes | Network type of the cell. | +| isCamped | boolean | Yes | Status of the cell. | +| timeStamp | number | Yes | Timestamp when cell information is obtained. | +| signalInformation | [SignalInformation](#signalinformation) | Yes | Signal information. | +| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | Yes | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information| ## CdmaCellInformation8+ @@ -1949,13 +1949,13 @@ Defines the CDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------- | ------ | ------------ | -| baseId | number | Base station ID. | -| latitude | number | Longitude. | -| longitude | number | Latitude. | -| nid | number | Network ID.| -| sid | number | System ID.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| baseId | number | Yes | Base station ID. | +| latitude | number | Yes | Longitude. | +| longitude | number | Yes | Latitude. | +| nid | number | Yes | Network ID.| +| sid | number | Yes | System ID.| ## GsmCellInformation8+ @@ -1965,14 +1965,14 @@ Defines the GSM cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | -------------------- | -| lac | number | Location area code. | -| cellId | number | Cell ID. | -| arfcn | number | Absolute radio frequency channel number.| -| bsic | number | Base station ID. | -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code. | +| cellId | number | Yes | Cell ID. | +| arfcn | number | Yes | Absolute radio frequency channel number.| +| bsic | number | Yes | Base station ID. | +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | ## LteCellInformation8+ @@ -1982,16 +1982,16 @@ Defines the LTE cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------- | ------- | ----------------------- | -| cgi | number | Cell global identification. | -| pci | number | Physical cell ID. | -| tac | number | Tracking area code. | -| earfcn | number | Absolute radio frequency channel number. | -| bandwidth | number | Bandwidth. | -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | -| isSupportEndc | boolean | Support New Radio_Dual Connectivity| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| cgi | number | Yes | Cell global identification. | +| pci | number | Yes | Physical cell ID. | +| tac | number | Yes | Tracking area code. | +| earfcn | number | Yes | Absolute radio frequency channel number. | +| bandwidth | number | Yes | Bandwidth. | +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | +| isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity. | ## NrCellInformation8+ @@ -2001,14 +2001,14 @@ Defines the NR cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------- | ------ | ---------------- | -| nrArfcn | number | 5G frequency number. | -| pci | number | Physical cell ID. | -| tac | number | Tracking area code. | -| nci | number | 5G network cell ID.| -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| nrArfcn | number | Yes | 5G frequency number. | +| pci | number | Yes | Physical cell ID. | +| tac | number | Yes | Tracking area code. | +| nci | number | Yes | 5G network cell ID.| +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | ## TdscdmaCellInformation8+ @@ -2018,14 +2018,14 @@ Defines the TD-SCDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | ------------ | -| lac | number | Location area code.| -| cellId | number | Cell ID. | -| cpid | number | Cell parameter ID.| -| uarfcn | number | Absolute radio frequency number.| -| mcc | string | Mobile country code.| -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code.| +| cellId | number | Yes | Cell ID. | +| cpid | number | Yes | Cell parameter ID.| +| uarfcn | number | Yes | Absolute radio frequency number.| +| mcc | string | Yes | Mobile country code.| +| mnc | string | Yes | Mobile network code. | ## WcdmaCellInformation8+ @@ -2035,14 +2035,14 @@ Defines the WCDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | ------------ | -| lac | number | Location area code.| -| cellId | number | Cell ID. | -| psc | number | Primary scrambling code. | -| uarfcn | number | Absolute radio frequency number.| -| mcc | string | Mobile country code.| -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code.| +| cellId | number | Yes | Cell ID. | +| psc | number | Yes | Primary scrambling code. | +| uarfcn | number | Yes | Absolute radio frequency number.| +| mcc | string | Yes | Mobile country code.| +| mnc | string | Yes | Mobile network code. | ## NrOptionMode8+ @@ -2067,10 +2067,10 @@ Defines the network search result. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------------------- | ------------------------------------------------- | -------------- | -| isNetworkSearchSuccess | boolean | Successful network search.| -| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| isNetworkSearchSuccess | boolean | Yes | Successful network search.| +| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.| ## NetworkInformation @@ -2080,12 +2080,12 @@ Defines the network information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ----------------------------------------- | -------------- | -| operatorName | string | Carrier name.| -| operatorNumeric | string | Carrier number. | -| state | [NetworkInformation](#networkinformationstate) | Network information status.| -| radioTech | string | Radio technology. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| operatorName | string | Yes | Carrier name.| +| operatorNumeric | string | Yes | Carrier number. | +| state | [NetworkInformation](#networkinformationstate) | Yes | Network information status.| +| radioTech | string | Yes | Radio technology. | ## NetworkInformationState @@ -2110,12 +2110,12 @@ Defines the network selection mode. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------------ | --------------------------------------------- | -------------------------------------- | -| slotId | number | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. | -| networkInformation | [NetworkInformation](#networkinformation) | Network information. | -| resumeSelection | boolean | Whether to resume selection. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. | +| networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. | +| resumeSelection | boolean | Yes | Whether to resume selection. | ## ImsRegState9+ @@ -2153,10 +2153,10 @@ Defines the IMS registration information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------- | ---------------------------- | ------------- | -| imsRegState | [ImsRegState](#imsregstate9) | IMS registration state.| -| imsRegTech | [ImsRegTech](#imsregtech9) | IMS registration technology.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.| +| imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.| ## ImsServiceType9+ diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index 8117cdd44862dc934a4022b6b701b9551cd6d25e..865f1104386664ce5b4cafede20ec54ffab711a6 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -15,8 +15,10 @@ import resourceManager from '@ohos.resourceManager'; ## Instruction -Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. -For details about how to reference **context** in the stage model, see [Context in the Stage Model]. +Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object. + +For details about how to reference **context** in the stage model, see Context in the Stage Model. + ```ts import Ability from '@ohos.application.Ability'; @@ -97,6 +99,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ----------------- | | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| @@ -134,6 +137,7 @@ Obtains the **ResourceManager** object of an application based on the specified | bundleName | string | Yes | Bundle name of the application.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------ | | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| @@ -305,7 +309,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example (stage)** ```ts try { - this.context.getStringValue($r('app.string.test').id, (error, value) => { + this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -333,6 +337,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | ----------- | | Promise<string> | Promise used to return the result.| @@ -423,6 +428,7 @@ Obtains the string corresponding to the specified resource object. This API uses | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | --------------------- | ---------------- | | Promise<string> | Promise used to return the result.| @@ -512,6 +518,7 @@ Obtains the string array corresponding to the specified resource ID. This API us | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ---------------------------------- | ------------- | | Promise<Array<string>> | Promise used to return the result.| @@ -599,6 +606,7 @@ Obtains the string array corresponding to the specified resource object. This AP | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ---------------------------------- | ------------------ | | Promise<Array<string>> | Promise used to return the result.| @@ -687,6 +695,7 @@ Obtains the content of the media file corresponding to the specified resource ID | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------------------------- | -------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -772,6 +781,7 @@ Obtains the content of the media file corresponding to the specified resource ob | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------------------------- | ------------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -859,6 +869,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | -------------------- | | Promise<string> | Promise used to return the result.| @@ -944,6 +955,7 @@ Obtains the Base64 code of the image corresponding to the specified resource obj | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -1014,6 +1026,7 @@ Obtains the device configuration. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ---------------- | | Promise<[Configuration](#configuration)> | Promise used to return the result.| @@ -1069,6 +1082,7 @@ Obtains the device capability. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| @@ -1144,6 +1158,7 @@ Obtains the singular-plural string corresponding to the specified resource ID ba | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -1234,6 +1249,7 @@ Obtains the singular-plural string corresponding to the specified resource objec | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------------ | | Promise<string> | Promise used to return the result.| @@ -1321,6 +1337,7 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------------- | ----------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -1402,6 +1419,7 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| @@ -1470,6 +1488,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------- | ---- | | Promise<void> | Promise that returns no value.| @@ -1538,6 +1557,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------- | ---- | | Promise<void> | Promise that returns no value.| @@ -1634,6 +1654,7 @@ Obtains the string corresponding to the specified resource name. This API uses a | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | --------------------- | ---------- | | Promise<string> | String corresponding to the resource name.| @@ -1716,6 +1737,7 @@ Obtains the string array corresponding to the specified resource name. This API | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ---------------------------------- | ------------ | | Promise<Array<string>> | Promise used to return the result.| @@ -1798,6 +1820,7 @@ Obtains the content of the media file corresponding to the specified resource na | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------------------------- | ------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -1880,6 +1903,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | --------------------- | ------------------- | | Promise<string> | Promise used to return the result.| @@ -1965,6 +1989,7 @@ Obtains the plural string corresponding to the specified resource name based on | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ---------------------- | | Promise<string> | Promise used to return the result.| @@ -2007,6 +2032,7 @@ Obtains the string corresponding to the specified resource ID. This API returns | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------ | ----------- | | string | Promise used to return the result.| @@ -2045,6 +2071,7 @@ Obtains the string corresponding to the specified resource object. This API retu | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------ | ---------------- | | string | Promise used to return the result.| @@ -2088,6 +2115,7 @@ Obtains the string corresponding to the specified resource name. This API return | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------ | ---------- | | string | String corresponding to the specified resource name.| @@ -2126,6 +2154,7 @@ Obtains the Boolean result corresponding to the specified resource ID. This API | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------- | ------------ | | boolean | Boolean result corresponding to the specified resource ID.| @@ -2163,6 +2192,7 @@ Obtains the Boolean result corresponding to the specified resource object. This | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------- | ----------------- | | boolean | Boolean result corresponding to the specified resource object.| @@ -2206,6 +2236,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------- | ----------- | | boolean | Boolean result corresponding to the specified resource name.| @@ -2244,6 +2275,7 @@ Obtains the integer or float value corresponding to the specified resource ID. T | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------ | ---------- | | number | Integer or float value corresponding to the specified resource ID.| @@ -2288,6 +2320,7 @@ Obtains the integer or float value corresponding to the specified resource objec | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------ | --------------- | | number | Integer or float value corresponding to the specified resource object.| @@ -2331,6 +2364,7 @@ Obtains the integer or float value corresponding to the specified resource name. | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------ | --------- | | number | Integer or float value corresponding to the specified resource name.| @@ -2409,6 +2443,7 @@ This API is deprecated since API version 9. You are advised to use [getStringVal | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | ----------- | | Promise<string> | Promise used to return the result.| @@ -2473,6 +2508,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ---------------------------------- | ------------- | | Promise<Array<string>> | Promise used to return the result.| @@ -2495,7 +2531,7 @@ getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2526,7 +2562,7 @@ getMedia(resId: number): Promise<Uint8Array> Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent-1) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2537,6 +2573,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------------------------- | -------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -2559,7 +2596,7 @@ getMediaBase64(resId: number, callback: AsyncCallback<string>): void Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2590,7 +2627,7 @@ getMediaBase64(resId: number): Promise<string> Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64-1) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2601,6 +2638,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | -------------------- | | Promise<string> | Promise used to return the result.| @@ -2623,7 +2661,7 @@ getPluralString(resId: number, num: number): Promise<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue) instead. +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2635,6 +2673,7 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -2657,7 +2696,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue-1) instead. +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2731,6 +2770,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------------- | ----------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -2796,6 +2836,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFd](#g | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index b0915951260105661f35dcad54468e2417962e89..7c415cc718aa72b7d1d098483a73399fc431d7af 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2847,10 +2847,10 @@ Defines the lock status response. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ------ | ------------------ | -| result | number | Operation result. | -| remain?: number | number | Remaining attempts (can be null).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| result | number | Yes | Operation result. | +| remain?: number | number | Yes | Remaining attempts (can be null).| ## LockInfo8+ @@ -2860,11 +2860,11 @@ Defines the lock information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | ------------------------ | ------ | -| lockType | [LockType](#locktype8) | Lock type.| -| password | string | Password. | -| state | [LockState](#lockstate8) | Lock state.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lockType | [LockType](#locktype8) | Yes | Lock type.| +| password | string | Yes | Password. | +| state | [LockState](#lockstate8) | Yes | Lock state.| ## PersoLockInfo8+ @@ -2874,10 +2874,10 @@ Defines the personalized lock information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | -------------------------------- | ------------ | -| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.| -| password | string | Password. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.| +| password | string | Yes | Password. | ## IccAccountInfo7+ @@ -2887,15 +2887,15 @@ Defines the ICC account information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------- | ------- | ---------------- | -| simId | number | SIM card ID. | -| slotIndex | number | Card slot ID. | -| isEsim | boolean | Whether the SIM card is an eSim card.| -| isActive | boolean | Whether the card is activated. | -| iccId | string | ICCID number. | -| showName | string | SIM card display name. | -| showNumber | string | SIM card display number. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| simId | number | Yes | SIM card ID. | +| slotIndex | number | Yes | Card slot ID. | +| isEsim | boolean | Yes | Whether the SIM card is an eSim card.| +| isActive | boolean | Yes | Whether the card is activated. | +| iccId | string | Yes | ICCID number. | +| showName | string | Yes | SIM card display name. | +| showNumber | string | Yes | SIM card display number. | ## OperatorConfig8+ @@ -2905,10 +2905,10 @@ Defines the carrier configuration. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description| -| ----- | ------ | ---- | -| field | string | Field| -| value | string | Value | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| field | string | Yes | Field. | +| value | string | Yes | Value. | ## DiallingNumbersInfo8+ @@ -2918,12 +2918,12 @@ Defines the contact number information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------ | ------ | -------- | -| alphaTag | string | Alpha tag. | -| number | string | Contact number. | -| recordNumber | number | Record number.| -| pin2 | string | PIN 2.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| alphaTag | string | Yes | Alpha tag. | +| number | string | Yes | Contact number. | +| recordNumber | number | Yes | Record number.| +| pin2 | string | Yes | PIN 2.| ## ContactType8+ diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 7d372978202503f6ed0a0517fa69f85ae5dfcf44..e9e32416426bf852590ed7d7a7f9c5e086a89480 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1116,19 +1116,19 @@ Defines an SMS message instance. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Description | -| ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| -| isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| -| isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| -| messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. | -| pdu | Array<number> | PDU in the SMS message. | -| protocolId | number | Protocol identifier used for delivering the SMS message. | -| scAddress | string | SMSC address. | -| scTimestamp | number | SMSC timestamp. | -| status | number | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| -| visibleMessageBody | string | SMS message body. | -| visibleRawAddress | string | Sender address. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| hasReplyPath | boolean | Yes |Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| +| isReplaceMessage | boolean | Yes |Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| +| isSmsStatusReportMessage | boolean | Yes |Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| +| messageClass | [ShortMessageClass](#shortmessageclass) | Yes | SMS message type. | +| pdu | Array<number> | Yes | PDU in the SMS message. | +| protocolId | number | Yes | Protocol identifier used for delivering the SMS message. | +| scAddress | string | Yes | SMSC address. | +| scTimestamp | number | Yes | SMSC timestamp. | +| status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| +| visibleMessageBody | string | Yes | SMS message body. | +| visibleRawAddress | string | Yes | Sender address. | ## ShortMessageClass diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 05a6e52c9d6f1e402dc9a7e3d8d4a19c9a117ec3..404a78973a81b9604fd3e7644bca5d61d8773a49 100644 --- a/en/application-dev/reference/apis/js-apis-touchevent.md +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -70,7 +70,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | toolHeight | number | Yes| No| Height of the tool area.| | rawX | number | Yes| No| X coordinate of the input device.| | rawY | number | Yes| No| Y coordinate of the input device.| -| toolType | number | Yes| No| Tool type.| +| toolType | ToolType | Yes| No| Tool type.| ## TouchEvent diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md index ca250939af9aadf2c544dee30431c889331d332e..b3be9875df2554c6df5b8c358c9243d734d87874 100644 --- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -638,16 +638,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ------------- | ------------------------------------------- | ------------- | -| address | number | Endpoint address. | -| attributes | number | Endpoint attributes. | -| interval | number | Endpoint interval. | -| maxPacketSize | number | Maximum size of data packets on the endpoint. | -| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. | -| number | number | Endpoint number. | -| type | number | Endpoint type. | -| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | number | Yes | Endpoint address. | +| attributes | number | Yes | Endpoint attributes. | +| interval | number | Yes | Endpoint interval. | +| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | +| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | +| number | number | Yes | Endpoint number. | +| type | number | Yes | Endpoint type. | +| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| ## USBInterface @@ -655,15 +655,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------------- | ---------------------------------------- | --------------------- | -| id | number | Unique ID of the USB interface. | -| protocol | number | Interface protocol. | -| clazz | number | Device type. | -| subClass | number | Device subclass. | -| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| -| name | string | Interface name. | -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique ID of the USB interface. | +| protocol | number | Yes | Interface protocol. | +| clazz | number | Yes | Device type. | +| subClass | number | Yes | Device subclass. | +| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| +| name | string | Yes | Interface name. | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes | Endpoints that belong to the USB interface. | ## USBConfig @@ -671,15 +671,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| -------------- | ------------------------------------------------ | --------------- | -| id | number | Unique ID of the USB configuration. | -| attributes | number | Configuration attributes. | -| maxPower | number | Maximum power consumption, in mA. | -| name | string | Configuration name, which can be left empty. | -| isRemoteWakeup | boolean | Support for remote wakeup.| -| isSelfPowered | boolean | Support for independent power supplies.| -| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique ID of the USB configuration. | +| attributes | number | Yes | Configuration attributes. | +| maxPower | number | Yes | Maximum power consumption, in mA. | +| name | string | Yes | Configuration name, which can be left empty. | +| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| +| isSelfPowered | boolean | Yes | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Yes | Supported interface attributes. | ## USBDevice @@ -687,21 +687,21 @@ Represents the USB device information. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------------- | ------------------------------------ | ---------- | -| busNum | number | Bus address. | -| devAddress | number | Device address. | -| serial | string | Sequence number. | -| name | string | Device name. | -| manufacturerName | string | Device manufacturer. | -| productName | string | Product name. | -| version | string | Version number. | -| vendorId | number | Vendor ID. | -| productId | number | Product ID. | -| clazz | number | Device class. | -| subClass | number | Device subclass. | -| protocol | number | Device protocol code. | -| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| busNum | number | Yes | Bus address. | +| devAddress | number | Yes | Device address. | +| serial | string | Yes | Sequence number. | +| name | string | Yes | Device name. | +| manufacturerName | string | Yes | Device manufacturer. | +| productName | string | Yes | Product name. | +| version | string | Yes | Version number. | +| vendorId | number | Yes | Vendor ID. | +| productId | number | Yes | Product ID. | +| clazz | number | Yes | Device class. | +| subClass | number | Yes | Device subclass. | +| protocol | number | Yes | Device protocol code. | +| configs | Array<[USBConfig](#usbconfig)> | Yes | Device configuration descriptor information.| ## USBDevicePipe @@ -709,10 +709,10 @@ Represents a USB device pipe, which is used to determine a USB device. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------- | ------ | ----- | -| busNum | number | Bus address.| -| devAddress | number | Device address.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| busNum | number | Yes | Bus address.| +| devAddress | number | Yes | Device address.| ## USBControlParams @@ -720,14 +720,14 @@ Represents control transfer parameters. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ------- | ----------------------------------------------- | ---------------- | -| request | number | Request type. | -| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. | -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. | -| value | number | Request parameter value. | -| index | number | Index of the request parameter value.| -| data | Uint8Array | Buffer for writing or reading data. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| request | number | Yes | Request type. | +| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | +| value | number | Yes | Request parameter value. | +| index | number | Yes | Index of the request parameter value.| +| data | Uint8Array | Yes | Buffer for writing or reading data. | ## USBPort9+ @@ -737,11 +737,11 @@ Represents a USB port. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| -------------- | -------------------------------- | ----------------------------------- | -| id | number | Unique identifier of a USB port. | -| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.| -| status | [USBPortStatus](#usbportstatus9) | USB port role. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique identifier of a USB port. | +| supportedModes | [PortModeType](#portmodetype9) | Yes | Numeric mask combination for the supported mode list.| +| status | [USBPortStatus](#usbportstatus9) | Yes | USB port role. | ## USBPortStatus9+ @@ -751,11 +751,11 @@ Enumerates USB port roles. **System capability**: SystemCapability.USB.USBManager -| Name | Type| Description | -| ---------------- | -------- | ---------------------- | -| currentMode | number | Current USB mode. | -| currentPowerRole | number | Current power role. | -| currentDataRole | number | Current data role.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| currentMode | number | Yes | Current USB mode. | +| currentPowerRole | number | Yes | Current power role. | +| currentDataRole | number | Yes | Current data role. | ## USBRequestTargetType diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 18c0ae75e03604340f2d9f61953c869605d01245..3e1c5b919c881ef5c0d0619a5b35e791c48c46cb 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -720,14 +720,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain | Name | Type | Mandatory |Description | | ------------- | ------------------------------------------- | ------------- |------------- | -| address | number | Yes|Endpoint address. | -| attributes | number | Yes|Endpoint attributes. | -| interval | number | Yes|Endpoint interval. | -| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. | -| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. | -| number | number | Yes|Endpoint number. | -| type | number | Yes|Endpoint type. | -| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.| +| address | number | Yes | Endpoint address. | +| attributes | number | Yes | Endpoint attributes. | +| interval | number | Yes | Endpoint interval. | +| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | +| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | +| number | number | Yes | Endpoint number. | +| type | number | Yes | Endpoint type. | +| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| ## USBInterface @@ -737,13 +737,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U | Name | Type | Mandatory |Description | | ---------------- | ---------------------------------------- | ------------- |--------------------- | -| id | number | Yes|Unique ID of the USB interface. | -| protocol | number | Yes|Interface protocol. | -| clazz | number | Yes|Device type. | -| subClass | number | Yes|Device subclass. | -| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.| -| name | string | Yes|Interface name. | -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes|Endpoints that belong to the USB interface. | +| id | number | Yes | Unique ID of the USB interface. | +| protocol | number | Yes | Interface protocol. | +| clazz | number | Yes | Device type. | +| subClass | number | Yes | Device subclass. | +| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| +| name | string | Yes | Interface name. | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes | Endpoints that belong to the USB interface. | ## USBConfig @@ -753,13 +753,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip | Name | Type | Mandatory |Description | | -------------- | ------------------------------------------------ | --------------- |--------------- | -| id | number | Yes|Unique ID of the USB configuration. | -| attributes | number | Yes|Configuration attributes. | -| maxPower | number | Yes|Maximum power consumption, in mA. | -| name | string | Yes|Configuration name, which can be left empty. | -| isRemoteWakeup | boolean | Yes|Support for remote wakeup.| -| isSelfPowered | boolean | Yes| Support for independent power supplies.| -| interfaces | Array <[USBInterface](#usbinterface)> | Yes|Supported interface attributes. | +| id | number | Yes | Unique ID of the USB configuration. | +| attributes | number | Yes | Configuration attributes. | +| maxPower | number | Yes | Maximum power consumption, in mA. | +| name | string | Yes | Configuration name, which can be left empty. | +| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| +| isSelfPowered | boolean | Yes | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Yes | Supported interface attributes. | ## USBDevice @@ -769,19 +769,19 @@ Represents the USB device information. | Name | Type | Mandatory |Description | | ---------------- | ------------------------------------ | ---------- |---------- | -| busNum | number | Yes|Bus address. | -| devAddress | number | Yes|Device address. | -| serial | string | Yes|Sequence number. | -| name | string | Yes|Device name. | -| manufacturerName | string | Yes| Device manufacturer. | -| productName | string | Yes|Product name. | -| version | string | Yes|Version number. | -| vendorId | number | Yes|Vendor ID. | -| productId | number | Yes|Product ID. | -| clazz | number | Yes|Device class. | -| subClass | number | Yes|Device subclass. | -| protocol | number | Yes|Device protocol code. | -| configs | Array<[USBConfig](#usbconfig)> | Yes|Device configuration descriptor information.| +| busNum | number | Yes | Bus address. | +| devAddress | number | Yes | Device address. | +| serial | string | Yes | Sequence number. | +| name | string | Yes | Device name. | +| manufacturerName | string | Yes | Device manufacturer. | +| productName | string | Yes | Product name. | +| version | string | Yes | Version number. | +| vendorId | number | Yes | Vendor ID. | +| productId | number | Yes | Product ID. | +| clazz | number | Yes | Device class. | +| subClass | number | Yes | Device subclass. | +| protocol | number | Yes | Device protocol code. | +| configs | Array<[USBConfig](#usbconfig)> | Yes | Device configuration descriptor information.| ## USBDevicePipe @@ -802,12 +802,12 @@ Represents control transfer parameters. | Name | Type | Mandatory |Description | | ------- | ----------------------------------------------- | ---------------- |---------------- | -| request | number | Yes |Request type. | -| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. | -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. | -| value | number | Yes |Request parameter value. | -| index | number | Yes |Index of the request parameter value.| -| data | Uint8Array | Yes |Buffer for writing or reading data. | +| request | number | Yes | Request type. | +| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | +| value | number | Yes | Request parameter value. | +| index | number | Yes | Index of the request parameter value.| +| data | Uint8Array | Yes | Buffer for writing or reading data. | ## USBPort @@ -819,9 +819,9 @@ Represents a USB port. | Name | Type | Mandatory |Description | | -------------- | ------------------------------- | ------------------- |------------------------ | -| id | number | Yes |Unique identifier of a USB port. | -| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.| -| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. | +| id | number | Yes | Unique identifier of a USB port. | +| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.| +| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. | ## USBPortStatus @@ -833,9 +833,9 @@ Enumerates USB port roles. | Name | Type| Mandatory |Description | | ---------------- | -------- | ---------------- |---------------------- | -| currentMode | number | Yes|Current USB mode. | -| currentPowerRole | number | Yes |Current power role. | -| currentDataRole | number | Yes |Current data role.| +| currentMode | number | Yes | Current USB mode. | +| currentPowerRole | number | Yes | Current power role. | +| currentDataRole | number | Yes | Current data role.| ## USBRequestTargetType @@ -843,12 +843,12 @@ Enumerates request target types. **System capability**: SystemCapability.USB.USBManager -| Name | Value | Description | -| ---------------------------- | ---- | ------ | -| USB_REQUEST_TARGET_DEVICE | 0 | Device| -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface| -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| -| USB_REQUEST_TARGET_OTHER | 3 | Other| +| Name | Value | Description | +| ---------------------------- | ----- | ----------- | +| USB_REQUEST_TARGET_DEVICE | 0 | Device | +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface | +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint | +| USB_REQUEST_TARGET_OTHER | 3 | Other | ## USBControlRequestType diff --git a/en/device-dev/driver/driver-peripherals-lcd-des.md b/en/device-dev/driver/driver-peripherals-lcd-des.md index d5ba25a559c9c255a829ac083e869c0b28db9b00..ce3cfd04cf2a23ef6ef8bd250ffa287691c7faab 100644 --- a/en/device-dev/driver/driver-peripherals-lcd-des.md +++ b/en/device-dev/driver/driver-peripherals-lcd-des.md @@ -1,19 +1,25 @@ # LCD - ## Overview +### Function + The Liquid Crystal Display (LCD) driver performs operations such as powering on the LCD and initializing the internal registers of the driver integrated circuits (ICs). -The display driver model developed based on the Hardware Driver Foundation [(HDF)](../driver/driver-hdf-overview.md) provides a basic framework for LCD driver development, improves driver development efficiency, and facilitates porting of the driver across OSs and chip platforms. The figure below shows the HDF-based display driver model. +The display driver model based on the [Hardware Driver Foundation (HDF)](../driver/driver-hdf-overview.md) provides the following functions: + +- Provides a basic framework for LCD driver development to improve development efficiency. + +- Facilitates driver porting across OSs and chip platforms. + +The following figure shows the HDF-based display driver model. **Figure 1** HDF-based display driver model ![image](figures/architecture-of-the-display-driver-model.png "Display Driver Model") - -The display driver model consists of the display common driver layer, SoC adapter layer, and LCD panel driver layer. The HDF-based display driver model shields the differences between kernel forms through platform and OSAL APIs so the LCD driver can be easily ported between different OSs and chip platforms. The display driver model connects to the display common Hardware Abstraction Layer (HAL), supports the implementation of the Hardware Device Interface (HDI), and provides various driver capability interfaces for graphics services through the Display-HDI. +The display driver model consists of the display common driver layer, SoC adapter layer, and LCD panel driver layer. The HDF-based display driver model shields the differences between kernel forms through platform and OSAL APIs so that the LCD driver can be easily ported across OSs and chip platforms. The display driver model connects to the display common Hardware Abstraction Layer (HAL), supports the implementation of the Hardware Device Interface (HDI), and provides various driver capability interfaces for graphics services through the Display-HDI. - Display common driver layer: connects to the display common HAL through the IOService data channel provided by the HDF to receive and process various upper-layer calls in a centralized manner. @@ -23,8 +29,7 @@ The display driver model consists of the display common driver layer, SoC adapte The display driver model leverages the capabilities and APIs provided by the platform to simplify the display driver development and improve the efficiency. - -## Available APIs +### Basic Concepts The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Display Serial Interface (DSI), Transistor-Transistor Logic (TTL) interface, and Low Voltage Differential Signaling (LVDS) interface. The MIPI DSI and TTL interfaces are commonly used. Here is a brief introduction to them. @@ -34,7 +39,7 @@ The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Displa ![](figures/mipi-dsi.png "MIPI DSI") - The DSI is defined by the MIPI Alliance for the displays used in mobile devices. The MIPI DSI is used to transmit image data, in compliance with the MIPI protocol. Generally, control information is sent to the peer IC in the form of MIPI packets over the MIPI DSI, without the need of additional peripheral interfaces. + The DSI is defined by the MIPI Alliance for the displays used in mobile devices. The MIPI DSI is used to transmit image data, in compliance with the MIPI protocol. Generally, control information is sent to the peer IC in the form of MIPI packets over the MIPI DSI, without the need of additional peripheral interfaces. - TTL interface @@ -42,14 +47,31 @@ The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Displa ![](figures/ttl-interface.png "ttl-interface") - TTL level signals are generated by TTL devices, which are a major type of digital integrated circuits. TTL devices are manufactured using the bipolar process and feature high speed, low power consumption, and diversified types. + ​ TTL level signals are generated by TTL devices, which are a major type of digital integrated circuits. TTL devices are manufactured using the bipolar process and feature high speed, low power consumption, and diversified types. + + The TTL interface is used to transmit data in parallel mode under control signals. It transmits data signals, clock signals, and control signals (such as line synchronization signals, frame synchronization signals, and data validity signals). For the LCD with the TTL, additional peripheral interfaces, such as the Serial Peripheral Interface (SPI) and Inter-Integrated Circuit (I2C), are required for the read and write of the internal registers. - The TTL interface is used to transmit data in parallel mode under control signals. It transmits data signals, clock signals, and control signals (such as line synchronization signals, frame synchronization signals, and data validity signals). For the LCD with the TTL, additional peripheral interfaces, such as the Serial Peripheral Interface (SPI) and Inter-Integrated Circuit (I2C), are required for the read and write of the internal registers. +### Constraints +In addition to the IC model, you must consider the LCD peripheral circuit design, LCD interface unit of the baseband chip, backlight IC control, and upper-layer software programs. All these factors affect the development of the LCD driver. -## How to Develop +## Development Guidelines -The HDF-based display driver model provides a unified driver model for LCDs regardless of the OS (LiteOS or Linux OS) and chip platform (Hi35xx, Hi38xx, or V3S). The development procedure is as follows: +### When to Use + +Before applying your device with OpenHarmony system, you need to perform LCD driver adaption. The HDF-based display driver model provides a unified driver model for LCD adaptation regardless of the OS (LiteOS or Linux OS) and chip platform (Hi35xx, Hi38xx, or V3S). + +### Available APIs + +Table 1 APIs required for LCD driver adaptation + +| API | Description | +| :------------------------------------------------------ | ------------------- | +| display :: host | Sets device information. | +| static int32_t LcdResetOn(void) | Sets the status of the reset pin.| +| int32_t SampleEntryInit(struct HdfDeviceObject *object) | Initializes the entry function of the device driver. | + +### How to Develop 1. Add the device configuration related to the LCD driver. @@ -58,305 +80,228 @@ The HDF-based display driver model provides a unified driver model for LCDs rega 3. Add the LCD panel driver and register the panel driver functions in the driver entry function **Init**. The functions provide capabilities for: - Powering on/off the LCD device + Based on the LCD hardware connection, use the GPIO APIs provided by the platform to perform operations on the LCD pins, such as the reset pin and IOVCC pin. For details about the power-on sequence, see the SPEC provided by the LCD supplier. + - Sending the initialization sequence + Based on the LCD hardware interfaces, use the I2C, SPI, and MIPI interfaces provided by the platform to download the LCD initialization sequence. For details, see the SPEC provided by the LCD supplier. -4. Implement other HDF APIs as required, for example, **Release()**. - -5. Use the HDF to create other device nodes for implementing service logic or debugging as required. - - -## Development Example - -Add the device configuration. - - -``` -/* Configuration of the devices related to the display driver */ -display :: host { - hostName = "display_host"; - /* Configuration of the HDF display driver */ - device_hdf_disp :: device { - device0 :: deviceNode { - policy = 2; - priority = 200; - permission = 0660; - moduleName = "HDF_DISP"; - serviceName = "hdf_disp"; - } - } - /* Configuration of the driver device at the SoC adapter layer */ - device_hi35xx_disp :: device { - device0 :: deviceNode { - policy = 0; - priority = 199; - moduleName = "HI351XX_DISP"; - } - } - /* Configuration of the LCD driver */ - device_lcd :: device { - device0 :: deviceNode { - policy = 0; - priority = 100; - preload = 0; - moduleName = "LCD_Sample"; - } - device1 :: deviceNode { - policy = 0; - priority = 100; - preload = 2; - moduleName = "LCD_SampleXX"; - } - } -} -``` - -Adapt the driver to the chip at the SoC adapter layer. The following example shows how to adapt the MIPI device to the Hi35xx series chips at the SoC adapter layer: - - -``` -static int32_t MipiDsiInit(struct PanelInfo *info) -{ - int32_t ret; - struct DevHandle *mipiHandle = NULL; - struct MipiCfg cfg; - - mipiHandle = MipiDsiOpen(0); - if (mipiHandle == NULL) { - HDF_LOGE("%s: MipiDsiOpen failure", __func__); - return HDF_FAILURE; - } - cfg.lane = info->mipi.lane; - cfg.mode = info->mipi.mode; - cfg.format = info->mipi.format; - cfg.burstMode = info->mipi.burstMode; - cfg.timing.xPixels = info->width; - cfg.timing.hsaPixels = info->hsw; - cfg.timing.hbpPixels = info->hbp; - cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; - cfg.timing.vsaLines = info->vsw; - cfg.timing.vbpLines = info->vbp; - cfg.timing.vfpLines = info->vfp; - cfg.timing.ylines = info->height; - /* 0 : no care */ - cfg.timing.edpiCmdSize = 0; - cfg.pixelClk = CalcPixelClk(info); - cfg.phyDataRate = CalcDataRate(info); - /* Configure the MIPI device. */ - ret = MipiDsiSetCfg(mipiHandle, &cfg); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s:MipiDsiSetCfg failure", __func__); - } - MipiDsiClose(mipiHandle); - HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__, - cfg.pixelClk, cfg.phyDataRate); - return ret; -} -``` - -Develop an LCD driver. The sample code is as follows: - - -``` -#define RESET_GPIO 5 -#define MIPI_DSI0 0 -#define BLK_PWM1 1 -#define PWM_MAX_PERIOD 100000 -/* Set the backlight. */ -#define MIN_LEVEL 0 -#define MAX_LEVEL 255 -#define DEFAULT_LEVEL 100 - -#define WIDTH 480 -#define HEIGHT 960 -#define HORIZONTAL_BACK_PORCH 20 -#define HORIZONTAL_FRONT_PORCH 20 -#define HORIZONTAL_SYNC_WIDTH 10 -#define VERTICAL_BACK_PORCH 14 -#define VERTICAL_FRONT_PORCH 16 -#define VERTICAL_SYNC_WIDTH 2 -#define FRAME_RATE 60 - -/* PanelInfo structure */ -struct PanelInfo { - uint32_t width; - uint32_t height; - uint32_t hbp; - uint32_t hfp; - uint32_t hsw; - uint32_t vbp; - uint32_t vfp; - uint32_t vsw; - uint32_t frameRate; - enum LcdIntfType intfType; - enum IntfSync intfSync; - struct MipiDsiDesc mipi; - struct BlkDesc blk; - struct PwmCfg pwm; -}; - -/* Initialization sequence of the LCD panel */ -static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A }; -static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 }; -static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B }; -static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A }; -static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C }; -static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C }; -static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; -static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; -static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; -static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; -static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; -static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; -static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; -static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; -static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; -static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; -static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; -static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; -static uint8_t g_payLoad18[] = { - 0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, - 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, - 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 -}; -static uint8_t g_payLoad19[] = { 0x11 }; -static uint8_t g_payLoad20[] = { 0x29 }; - -struct DsiCmdDesc g_OnCmd[] = { - { 0x29, 0, sizeof(g_payLoad0), g_payLoad0 }, - { 0x29, 0, sizeof(g_payLoad1), g_payLoad1 }, - { 0x29, 0, sizeof(g_payLoad2), g_payLoad2 }, - { 0x29, 0, sizeof(g_payLoad3), g_payLoad3 }, - { 0x29, 0, sizeof(g_payLoad4), g_payLoad4 }, - { 0x29, 0, sizeof(g_payLoad5), g_payLoad5 }, - { 0x29, 0, sizeof(g_payLoad6), g_payLoad6 }, - { 0x29, 0, sizeof(g_payLoad7), g_payLoad7 }, - { 0x29, 0, sizeof(g_payLoad8), g_payLoad8 }, - { 0x29, 0, sizeof(g_payLoad9), g_payLoad9 }, - { 0x23, 0, sizeof(g_payLoad10), g_payLoad10 }, - { 0x29, 0, sizeof(g_payLoad11), g_payLoad11 }, - { 0x29, 0, sizeof(g_payLoad12), g_payLoad12 }, - { 0x29, 0, sizeof(g_payLoad13), g_payLoad13 }, - { 0x29, 0, sizeof(g_payLoad14), g_payLoad14 }, - { 0x29, 0, sizeof(g_payLoad15), g_payLoad15 }, - { 0x29, 0, sizeof(g_payLoad16), g_payLoad16 }, - { 0x23, 0, sizeof(g_payLoad17), g_payLoad17 }, - { 0x29, 1, sizeof(g_payLoad18), g_payLoad18 }, - { 0x05, 120, sizeof(g_payLoad19), g_payLoad19 }, - { 0x05, 120, sizeof(g_payLoad20), g_payLoad20 }, -}; -static DevHandle g_mipiHandle = NULL; -static DevHandle g_pwmHandle = NULL; - -/* Set the status of the reset pin. */ -static int32_t LcdResetOn(void) -{ - int32_t ret; - ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); - if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioSetDir failure, ret:%d", ret); - return HDF_FAILURE; - } - ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); - if (ret != HDF_SUCCESS) { - HDF_LOGE("GpioWrite failure, ret:%d", ret); - return HDF_FAILURE; - } - /* Set the delay to 20 ms. */ - OsalMSleep(20); - return HDF_SUCCESS; -} - -static int32_t SampleInit(void) -{ - /* Open the MIPI DSI device handle. */ - g_mipiHandle = MipiDsiOpen(MIPI_DSI0); - if (g_mipiHandle == NULL) { - HDF_LOGE("%s: MipiDsiOpen failure", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -static int32_t SampleOn(void) -{ - int32_t ret; - /* Power on the LCD. */ - ret = LcdResetOn(); - if (ret != HDF_SUCCESS) { - HDF_LOGE("%s: LcdResetOn failure", __func__); - return HDF_FAILURE; - } - if (g_mipiHandle == NULL) { - HDF_LOGE("%s: g_mipiHandle is null", __func__); - return HDF_FAILURE; - } - /* Send the initialization sequence via MIPI. */ - int32_t count = sizeof(g_OnCmd) / sizeof(g_OnCmd[0]); - int32_t i; - for (i = 0; i < count; i++) { - ret = MipiDsiTx(g_mipiHandle, &(g_OnCmd[i])); - if (ret != HDF_SUCCESS) { - HDF_LOGE("MipiDsiTx failure"); - return HDF_FAILURE; - } - } - /* Set MIPI to the high speed (HS) mode. */ - MipiDsiSetHsMode(g_mipiHandle); - return HDF_SUCCESS; -} - -/* PanelInfo structure variables */ -static struct PanelInfo g_panelInfo = { - .width = WIDTH, /* width */ - .height = HEIGHT, /* height */ - .hbp = HORIZONTAL_BACK_PORCH, /* horizontal back porch */ - .hfp = HORIZONTAL_FRONT_PORCH, /* horizontal front porch */ - .hsw = HORIZONTAL_SYNC_WIDTH, /* horizontal sync width */ - .vbp = VERTICAL_BACK_PORCH, /* vertical back porch */ - .vfp = VERTICAL_FRONT_PORCH, /* vertical front porch */ - .vsw = VERTICAL_SYNC_WIDTH, /* vertical sync width */ - .frameRate = FRAME_RATE, /* frame rate */ - .intfType = MIPI_DSI, /* panel interface type */ - .intfSync = OUTPUT_USER, /* output timing type */ - /* MIPI configuration */ - .mipi = { DSI_2_LANES, DSI_VIDEO_MODE, VIDEO_BURST_MODE, FORMAT_RGB_24_BIT }, - /* backlight config info */ - .blk = { BLK_PWM, MIN_LEVEL, MAX_LEVEL, DEFAULT_LEVEL }, - .pwm = { BLK_PWM1, PWM_MAX_PERIOD }, -}; - -/* Basic APIs that need to be adapted for the chip driver */ -static struct PanelData g_panelData = { - .info = &g_panelInfo, - .init = SampleInit, - .on = SampleOn, - .off = SampleOff, - .setBacklight = SampleSetBacklight, -}; - -/* Entry function of the chip driver */ -int32_t SampleEntryInit(struct HdfDeviceObject *object) -{ - HDF_LOGI("%s: enter", __func__); - if (object == NULL) { - HDF_LOGE("%s: param is null!", __func__); - return HDF_FAILURE; - } - /* Register the device driver APIs with the platform driver. */ - if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { - HDF_LOGE("%s: PanelDataRegister error!", __func__); - return HDF_FAILURE; - } - return HDF_SUCCESS; -} - -struct HdfDriverEntry g_sampleDevEntry = { - .moduleVersion = 1, - .moduleName = "LCD_SAMPLE", - .Init = SampleEntryInit, -}; - -HDF_INIT(g_sampleDevEntry); -``` +4. (Optional) Implement other HDF APIs, such as **Release()**, as required. + +5. (Optional) Create other device nodes for implementing service logic or debugging based on the HDF as required. + +### Example + +The following uses the Hi35xx series chips as an example to describe how to perform LCD driver adaptation. + +1. Add device information in the **vendor/bearpi/bearpi_hm_micro/hdf_config/device_info/device_info.hcs** file. + + ```c++ + /* Configuration of the devices related to the display driver */ + display :: host { + hostName = "display_host"; + /* Configuration of the HDF display driver */ + device_hdf_disp :: device { + device0 :: deviceNode { + policy = 2; + priority = 200; + permission = 0660; + moduleName = "HDF_DISP"; + serviceName = "hdf_disp"; + } + } + /* Configuration of the driver device at the SoC adapter layer */ + device_hi35xx_disp :: device { + device0 :: deviceNode { + policy = 0; + priority = 199; + moduleName = "HI351XX_DISP"; + } + } + /* Configuration of the LCD driver */ + device_lcd :: device { + device0 :: deviceNode { + policy = 0; + priority = 100; + preload = 0; + moduleName = "LCD_Sample"; + } + device1 :: deviceNode { + policy = 0; + priority = 100; + preload = 2; + moduleName = "LCD_SampleXX"; + } + } + } + ``` + +2. Configure the chip platform driver information in the **drivers/hdf_core/framework/model/display/driver/adapter_soc/hi35xx_disp.c file**. + + ```c++ + /* Configuration of the display driver to adapt to the MIPI and chip platform */ + static int32_t MipiDsiInit(struct PanelInfo *info) + { + int32_t ret; + struct DevHandle *mipiHandle = NULL; + struct MipiCfg cfg; + + mipiHandle = MipiDsiOpen(0); + if (mipiHandle == NULL) { + HDF_LOGE("%s: MipiDsiOpen failure", __func__); + return HDF_FAILURE; + } + cfg.lane = info->mipi.lane; + cfg.mode = info->mipi.mode; + cfg.format = info->mipi.format; + cfg.burstMode = info->mipi.burstMode; + cfg.timing.xPixels = info->width; + cfg.timing.hsaPixels = info->hsw; + cfg.timing.hbpPixels = info->hbp; + cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; + cfg.timing.vsaLines = info->vsw; + cfg.timing.vbpLines = info->vbp; + cfg.timing.vfpLines = info->vfp; + cfg.timing.ylines = info->height; + /* 0 : no care */ + cfg.timing.edpiCmdSize = 0; + cfg.pixelClk = CalcPixelClk(info); + cfg.phyDataRate = CalcDataRate(info); + /* Configure the MIPI device. */ + ret = MipiDsiSetCfg(mipiHandle, &cfg); + if (ret != HDF_SUCCESS) { + HDF_LOGE("%s:MipiDsiSetCfg failure", __func__); + } + MipiDsiClose(mipiHandle); + HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__, + cfg.pixelClk, cfg.phyDataRate); + return ret; + } + ``` + +3. Add a device in **drivers/hdf_core/framework/model/display/driver/panel/mipi_icn9700.c**. + + - Define driver-related interface information. + + ```c++ + #define RESET_GPIO 5 + #define MIPI_DSI0 0 + #define BLK_PWM1 1 + #define PWM_MAX_PERIOD 100000 + /* Set the backlight. */ + #define MIN_LEVEL 0 + #define MAX_LEVEL 255 + #define DEFAULT_LEVEL 100 + #define WIDTH 480 + #define HEIGHT 960 + #define HORIZONTAL_BACK_PORCH 20 + #define HORIZONTAL_FRONT_PORCH 20 + #define HORIZONTAL_SYNC_WIDTH 10 + #define VERTICAL_BACK_PORCH 14 + #define VERTICAL_FRONT_PORCH 16 + #define VERTICAL_SYNC_WIDTH 2 + #define FRAME_RATE 60 + ``` + + - Define the **PanelInfo** structure. + + ```c++ + struct PanelInfo { + uint32_t width; + uint32_t height; + uint32_t hbp; + uint32_t hfp; + uint32_t hsw; + uint32_t vbp; + uint32_t vfp; + uint32_t vsw; + uint32_t frameRate; + enum LcdIntfType intfType; + enum IntfSync intfSync; + struct MipiDsiDesc mipi; + struct BlkDesc blk; + struct PwmCfg pwm; + }; + ``` + + - Initialize the LCD. + + ```c++ + static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A }; + static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 }; + static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B }; + static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A }; + static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C }; + static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C }; + static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; + static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; + static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; + static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; + static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; + static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; + static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; + static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; + static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; + static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; + static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; + static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; + static uint8_t g_payLoad18[] = { + 0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, + 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, + 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 + }; + static uint8_t g_payLoad19[] = { 0x11 }; + static uint8_t g_payLoad20[] = { 0x29 }; + static DevHandle g_mipiHandle = NULL; + static DevHandle g_pwmHandle = NULL; + ``` + + - Set the status of the reset pin. + + ```c++ + static int32_t LcdResetOn(void) + { + int32_t ret; + ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioSetDir failure, ret:%d", ret); + return HDF_FAILURE; + } + ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); + if (ret != HDF_SUCCESS) { + HDF_LOGE("GpioWrite failure, ret:%d", ret); + return HDF_FAILURE; + } + /* Set the delay to 20 ms. */ + OsalMSleep(20); + return HDF_SUCCESS; + } + ``` + + - Initialize the entry function of the device driver. + + ```c++ + int32_t SampleEntryInit(struct HdfDeviceObject *object) + { + HDF_LOGI("%s: enter", __func__); + if (object == NULL) { + HDF_LOGE("%s: param is null!", __func__); + return HDF_FAILURE; + } + /* Register the device driver APIs with the platform driver. */ + if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) { + HDF_LOGE("%s: PanelDataRegister error!", __func__); + return HDF_FAILURE; + } + return HDF_SUCCESS; + } + + struct HdfDriverEntry g_sampleDevEntry = { + .moduleVersion = 1, + .moduleName = "LCD_SAMPLE", + .Init = SampleEntryInit, + }; + + HDF_INIT(g_sampleDevEntry); + ``` diff --git a/en/device-dev/driver/driver-peripherals-motion-des.md b/en/device-dev/driver/driver-peripherals-motion-des.md index e3c3de926067feead05a095109ed2e8cb1e5ed95..eb147972aff5358f8e503e7375a094ea56323840 100644 --- a/en/device-dev/driver/driver-peripherals-motion-des.md +++ b/en/device-dev/driver/driver-peripherals-motion-des.md @@ -4,11 +4,11 @@ ### Function -The motion 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. OpenHarmony supports recognition of pick-up, flip, shake, and rotation. 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 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 following figure 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 driver architecture @@ -23,8 +23,8 @@ The figure below illustrates how a motion driver works. ![](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. -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 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. +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: The 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 @@ -53,15 +53,15 @@ The development procedure is as follows: The motion recognition directory structure is as follows: ```undefined -/drivers/peripheral/motion # Developed by the vendor. -├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer. -├── test # Test code for the motion recognition module. -│ └── unittest\hdi # HDI unit test code for the motion recognition module. +/drivers/peripheral/motion # Developed by the vendor. +├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer. +├── test # 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 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. +You need to implement the **Bind()**, **Init()**, **Release()**, and **Dispatch()** functions. The **Bind()** function binds the service capability with the driver; **Init()** implements the initialization required before the driver is loaded; **Release()** reclaims resources when **Init()** fails; **Dispatch()** implements the service, which is bound in **Bind()**. ```c++ // Custom HdfMotionInterfaceHost object @@ -153,7 +153,6 @@ struct HdfDriverEntry g_motioninterfaceDriverEntry = { HDF_INIT(g_userAuthInterfaceDriverEntry); ``` - ### Verification The procedure is as follows: diff --git a/en/device-dev/driver/driver-peripherals-sensor-des.md b/en/device-dev/driver/driver-peripherals-sensor-des.md index 0d1d3b5707af5d4523c44c1ed20b6b3d5fe503e7..2f04c658f03f217fe292dc885cbf06c3a6b50597 100644 --- a/en/device-dev/driver/driver-peripherals-sensor-des.md +++ b/en/device-dev/driver/driver-peripherals-sensor-des.md @@ -1,41 +1,41 @@ # Sensor - + ## Overview -### Introduction +### Function -The sensor driver model masks the sensor hardware differences and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor options. The model is developed on the Hardware Driver Foundation (HDF), Operating System Abstraction Layer (OSAL), and platform driver interfaces (such as the I2C, SPI, and UART buses). It provides functionalities such as cross-OS migration and differentiated device configurations. The figure below shows the architecture of the sensor driver model. +The sensor driver model shields the hardware difference and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor attributes. Developed based on the Hardware Driver Foundation (HDF), the sensor driver model leverages the capabilities of the OS adaptation layer (OSAL) and platform driver interfaces (such as I2C, SPI, and UART buses) to shield the difference between OSs and platform bus resources, achieving "one-time development and multi-system deployment" of the sensor driver. The figure below shows the architecture of the sensor driver model. **Figure 1** Sensor driver model - + ![Sensor driver model](figures/sensor_driver_model.png) ### Basic Concepts -Currently, sensors are classified into medical sensors and traditional sensors by sensor ID. +Sensors are classified into the following types by sensor ID: -- The IDs of medical sensors range from 128 to 160. +- Medical sensors: The sensor IDs range from 128 to 160. -- The IDs of traditional sensors are out of the range of 128 to 160. +- Traditional sensors: The sensor IDs are out of the range of 128 to 160. ### Working Principles -Based on the loading and running process (shown below) of the sensor driver model, the relationships between key modules in the model and associated modules are clearly defined. +The following figure shows how a sensor driver works. -**Figure 2** How sensor driver works +**Figure 2** How a sensor driver works ![How sensor driver works](figures/sensor_working.png) The following uses the acceleration sensor driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process. -1. The sensor host reads the sensor management configuration from the Sensor Host node of the device_info HCS (sensor device information HCS). -2. The sensor host parses the sensor management configuration from the HCB database and associates the corresponding sensor driver. +1. The sensor host reads the sensor device management configuration from **Sensor Host** in the **device_info.hcs** file. +2. The sensor host parses the sensor management configuration from the HCB database and associates the configuration with the sensor driver. 3. The sensor host loads and initializes the sensor manager driver. -4. The sensor manager driver publishes the sensor hardware device interfaces (HDIs). -5. The sensor host reads the acceleration sensor driver configuration from the Sensor Host node of the device_info HCS. +4. The sensor manager driver publishes the sensor APIs for the hardware driver interface (HDI). +5. The sensor host reads the acceleration sensor driver configuration information from **Sensor Host** in the **device_info.hcs** configuration file. 6. The sensor host loads the acceleration sensor abstract driver and calls the initialization interface to allocate the sensor driver resources and create the data processing queue. -7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the accel_xxx_config HCS (sensor private configuration HCS). +7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the **accel_xxx_config.hcs** file. 8. The acceleration sensor chipset driver calls the common configuration parsing interface to parse the sensor attributes and registers. 9. The chipset driver detects sensors, allocates configuration resources to the acceleration sensor, and registers the acceleration sensor chipset interfaces. 10. Upon successful sensor detection, the chipset driver instructs the abstract driver to register the acceleration sensor to the sensor manager driver. @@ -54,34 +54,38 @@ The following uses the acceleration sensor driver on the Hi3516D V300 developmen The sensor driver model offers the following APIs: -- Sensor HDIs, for easier sensor service development -- Sensor driver model capability interfaces - - Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors - - Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors -- Interfaces to be implemented by developers: Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, developers need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development. +- Sensor HDI APIs, for easier sensor service development + +- APIs for implementing sensor driver model capabilities + - APIs for loading, registering, and deregitering sensor drivers, and detecting sensors based on the HDF + - Unified driver API, register configuration parsing API, bus access abstract API, and platform abstract API for the same type of sensors + +- APIs to be implemented by developers + + Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, you need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development. The sensor driver model provides APIs for the hardware service to make sensor service development easier. See the table below. **Table 1** APIs of the sensor driver model -| API| Description| +| API| Description| | ----- | -------- | | int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | Obtains information about all registered sensors in the system. The sensor information includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum range, accuracy, and power consumption.| -| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.| -| int32_t Disable(int32_t sensorId) | Disables a sensor.| -| int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.| -| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.| -| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.| -| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.| -| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.| +| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.| +| int32_t Disable(int32_t sensorId) | Disables a sensor.| +| int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.| +| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.| +| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.| +| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.| +| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.| The sensor driver model provides driver development APIs that do not require further implementation. See the table below. - **Table 2** Sensor driver development APIs that do not need to be implemented by driver developers + **Table 2** Sensor driver development APIs -| API| Description| +| API| Description| | ----- | -------- | | int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | Adds a sensor of the current type to the sensor management module.| | int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | Deletes a sensor from the sensor management module.| @@ -97,12 +101,11 @@ The sensor driver model provides driver development APIs that do not require fur - The sensor driver model also provides certain driver development APIs that need to be implemented by driver developers. See the table below. -**Table 3** APIs that need to be implemented by driver developers +**Table 3** APIs to be implemented by driver developers -| API| Description| +| API| Description| | ----- | -------- | | int32_t init(void) | Initializes the sensor device configuration after a sensor is detected.| | int32_t Enable(void) | Enables the current sensor by delivering the register configuration in the enabling operation group based on the device information HCS configuration.| @@ -121,14 +124,14 @@ The sensor driver model also provides certain driver development APIs that need ```c /* Register the entry structure object of the acceleration sensor. */ struct HdfDriverEntry g_sensorAccelDevEntry = { - .moduleVersion = 1, // Version of the acceleration sensor module. - .moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file. - .Bind = BindAccelDriver, // Function for binding an acceleration sensor. - .Init = InitAccelDriver, // Function for initializing an acceleration sensor. - .Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources. + .moduleVersion = 1, // Version of the acceleration sensor module. + .moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file. + .Bind = BindAccelDriver, // Function for binding an acceleration sensor. + .Init = InitAccelDriver, // Function for initializing an acceleration sensor. + .Release = ReleaseAccelDriver // Function for releasing acceleration sensor resources. }; - /* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind function first and then the Init function. If the Init function fails to be called, the HDF will call Release to release the driver resource and exit the sensor driver model. */ + /* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls Bind() and then Init() to load the driver. If Init() fails to be called, the HDF calls Release() to release resources and exit. */ HDF_INIT(g_sensorAccelDevEntry); ``` @@ -228,7 +231,7 @@ The sensor driver model also provides certain driver development APIs that need return drvData->accelCfg; ... } - /* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a sensor data reporting timer, register the sensor normalization APIs, and register the sensor device. */ + /* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a timer for sensor data reporting, register the sensor normalization APIs, and register the sensor device. */ int32_t AccelInitDriver(struct HdfDeviceObject *device) { ... @@ -271,16 +274,16 @@ The sensor driver model also provides certain driver development APIs that need The acceleration sensor model uses the HCS as the configuration source code. For details about the HCS configuration fields, see [Driver Configuration Management](driver-hdf-manage.md). - ``` + ```hcs /* Device information HCS configuration of the acceleration sensor. */ device_sensor_accel :: device { device0 :: deviceNode { - policy = 1; // Policy for publishing the driver service. - priority = 110; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random. - preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. - permission = 0664; // Permission for the driver to create a device node. - moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure. - serviceName = "sensor_accel"; // Name of the service provided by the driver. The name must be unique. + policy = 1; // Policy for the driver to publish services. + priority = 100; // Priority (0–200) for starting the driver. A larger value indicates a lower priority. The recommended value is 100. If the priorities are the same, the device loading sequence is not ensured. + preload = 0; // The value 0 means to load the driver by default during the startup of the system. The value 2 means the opposite. + permission = 0664; // Permission for the device node created. + moduleName = "HDF_SENSOR_ACCEL"; // Driver name. It must be the same as moduleName in the driver entry structure. + serviceName = "sensor_accel"; // Name of the service published by the driver. The name must be unique. deviceMatchAttr = "hdf_sensor_accel_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. } } @@ -466,7 +469,7 @@ The sensor driver model also provides certain driver development APIs that need /* Release the resources allocated during driver initialization. */ void Bmi160ReleaseDriver(struct HdfDeviceObject *device) { - ...... + ... if (drvData->sensorCfg != NULL) { AccelReleaseCfgData(drvData->sensorCfg); drvData->sensorCfg = NULL; @@ -511,18 +514,12 @@ The sensor driver model also provides certain driver development APIs that need } ``` ->![](../public_sys-resources/icon-note.gif) **NOTE** -> ->- The sensor driver model provides certain APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, common configuration, and configuration parsing capabilities. For details about them, see Table 2. ->- You need to implement the following functions: certain sensor operation interfaces (listed in Table 3) and sensor chipset HCS configuration. ->- You also need to verify basic driver functions. +### Verification -### How to Verify +After the driver is developed, develop test cases in the sensor unit test to verify the basic functions of the driver. Use your test platform to set up the test environment. -After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. Use the developer self-test platform as the test environment. - -``` -static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data. +```c++ +static int32_t g_sensorDataFlag = 0; // Whether to report sensor data. static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address. /* Register the data reporting function. */ @@ -558,9 +555,9 @@ void HdfSensorTest::TearDownTestCase() /* Verify the sensor driver. */ HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) { - int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds. - int32_t pollTime = 5; // Data sampling duration, in seconds. - int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1. + int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds. + int32_t pollTime = 5; // Data sampling time, in seconds. + int32_t accelSensorId = 1; // Acceleration sensor ID, which specifies the sensor type. int32_t count = 0; int ret; struct SensorInformation *sensorInfo = nullptr; diff --git a/zh-cn/application-dev/application-models/ability-startup-with-explicit-want.md b/zh-cn/application-dev/application-models/ability-startup-with-explicit-want.md index 67dc2e9a44c57cabb5e4cff1ecd69779016890ba..4f470899d8db2a73d34c0b08fb9314bee57deeaf 100644 --- a/zh-cn/application-dev/application-models/ability-startup-with-explicit-want.md +++ b/zh-cn/application-dev/application-models/ability-startup-with-explicit-want.md @@ -1,72 +1,4 @@ # 使用显式Want启动Ability -在应用使用场景中,当用户点击某个按钮时,应用经常需要拉起指定UIAbility组件来完成某些特定任务。下面介绍如何通过显式Want拉起应用内一个指定UIAbility组件。 - - -## 开发步骤 - -1. Stage模型工程内,创建一个Ability(此示例内命名为callerAbility)与相应Page(此示例中名为Index.ets),并在callerAbility.ts文件内的onWindowStageCreate函数内通过windowStage.loadContent()方法将两者绑定。 - - ```ts - // ... - // callerAbility.ts - onWindowStageCreate(windowStage) { - // Main window is created, set main page for this ability - console.info('[Demo] EntryAbility onWindowStageCreate') - // Bind callerAbility with a paged named Index - windowStage.loadContent('pages/Index') - } - // ... - ``` - -2. 同上方法再创建一个Ability,此示例内命名为“calleeAbility”。 - -3. 在callerAbility的“Index.ets”页面内新增一个按钮。 - - ```ts - // ... - build() { - Row() { - Column() { - Text('hello') - .fontSize(50) - .fontWeight(FontWeight.Bold) - // A new button with will call explicitStartAbility() when clicked. - Button("CLICKME") - .onClick(this.explicitStartAbility) // explicitStartAbility见下面示例代码 - // ... - } - .width('100%') - } - .height('100%') - } - // ... - ``` - -4. 补充相对应的onClick方法,并使用**显式Want**在方法内启动calleeAbility。bundleName字段可在工程AppScope>app.json5文件内获取;abilityName可在对应模块内的“yourModuleName > src > main > module.json5”文件查看。 - - ```ts - import common from '@ohos.app.ability.common'; - - // ... - async explicitStartAbility() { - try { - // Explicit want with abilityName specified. - let want = { - deviceId: "", - bundleName: "com.example.myapplication", - abilityName: "calleeAbility" - }; - let context = getContext(this) as common.UIAbilityContext; - await context.startAbility(want); - console.info(`explicit start ability succeed`); - } catch (error) { - console.info(`explicit start ability failed with ${error.code}`); - } - } - // ... - ``` - -5. 至此,当您点击CLICKME按钮时,应看到页面的跳转。 - startAbilityWtExplicitWant +在应用使用场景中,当用户在应用内点击某个按钮时,经常需要拉起指定UIAbility组件来完成某些特定任务。在启动UIAbility时,指定了abilityName和bundleName参数,可以使用显示Want方式启动UIAbility。显示Want的使用请参见[启动应用内的UIAbility](uiability-intra-device-interaction.md#启动应用内的uiability)。 diff --git a/zh-cn/application-dev/application-models/ability-startup-with-implicit-want.md b/zh-cn/application-dev/application-models/ability-startup-with-implicit-want.md index 8b120b81e72168a6c01576ea5a9b8e638e9febba..dbf65fc512576ea5b57cee09bacd77f283d1055f 100644 --- a/zh-cn/application-dev/application-models/ability-startup-with-implicit-want.md +++ b/zh-cn/application-dev/application-models/ability-startup-with-implicit-want.md @@ -41,7 +41,7 @@ ## 开发步骤 1. 在自定义函数implicitStartAbility内使用**隐式Want**启动Ability。 - + ```ts async implicitStartAbility() { try { @@ -71,12 +71,12 @@ 匹配过程如下: 1. want内action不为空,且被skills内action包括,匹配成功。 - + 2. want内entities不为空,且被skills内entities包括,匹配成功。 - - 3. skills内uris拼接为https://www.test.com:8080/query\* (\*为通配符)包含want内uri,匹配成功。 - + + 3. skills内uris拼接为`https://www.test.com:8080/query*` (\*为通配符)包含want内uri,匹配成功。 + 4. want内type不为空,且被skills内type包含,匹配成功。 -2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。 - stage-want1 +2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。 +stage-want1 diff --git a/zh-cn/application-dev/application-models/actions-entities.md b/zh-cn/application-dev/application-models/actions-entities.md index 68cc20700d501e21681748ae9ac02203c13d3656..a03921827b795c847d66cd8d4637b2639cb3b9a0 100644 --- a/zh-cn/application-dev/application-models/actions-entities.md +++ b/zh-cn/application-dev/application-models/actions-entities.md @@ -1,6 +1,5 @@ # 常见action与entities - **[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)**:表示调用方要执行的通用操作(如查看、分享、应用详情)。在隐式Want中,您可定义该字段,配合uri或parameters来表示对数据要执行的操作。如打开,查看该uri数据。例如,当uri为一段网址,action为ohos.want.action.viewData则表示匹配可查看该网址的Ability。在Want内声明action字段表示希望被调用方应用支持声明的操作。在被调用方应用配置文件skills字段内声明actions表示该应用支持声明操作。 @@ -15,7 +14,6 @@ - ACTION_VIEW_MULTIPLE_DATA:发送多个数据记录的操作。 - **[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。 diff --git a/zh-cn/application-dev/application-models/data-share-via-want.md b/zh-cn/application-dev/application-models/data-share-via-want.md index 7ae2b4b8c3aa94cda0fadc6c6f8b2d31339e3133..1c78aafe082370f758d6434ac6c7ee2af796e40f 100644 --- a/zh-cn/application-dev/application-models/data-share-via-want.md +++ b/zh-cn/application-dev/application-models/data-share-via-want.md @@ -64,7 +64,7 @@ - "ability.picker.fileSizes":应用选择器根据该字段展示文件大小。以字节为单位。 - "ability.picker.fileNames"与"ability.picker.fileSizes"为数组,其有一一对应关系。 - 例如:当"ability.picker.type"为“application/pdf”,"ability.picker.fileNames"为“["接口文档.pdf"]”,"ability.picker.fileSizes"为“[350 \* 1024]”时,应用选择器将以下形式展示。 + 例如:当"ability.picker.type"为“application/pdf”,"ability.picker.fileNames"为“["接口文档.pdf"]”,"ability.picker.fileSizes"为“[350 \* 1024]”时,应用选择器将以下形式展示。 stage-want2 示例代码中“ability.want.params.INTENT”字段是一个嵌套Want,内部所含action、type等字段将由应用选择器进行隐式匹配,具体隐式匹配规则可参考[隐式Want匹配原理详解](explicit-implicit-want-mappings.md#隐式want匹配原理详解)。当用户选择具体应用后,“ability.want.params.INTENT”字段的嵌套Want将传递至所选应用。 diff --git a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md index 2fcecb63c094190c71db81d3b703c888539a0e66..5cba63d0d4d07151c226feca88fabff0ebc8eb73 100644 --- a/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md +++ b/zh-cn/application-dev/application-models/explicit-implicit-want-mappings.md @@ -49,7 +49,7 @@ ### want参数的action匹配规则 -将调用方传入的want参数的action与待匹配Ability的skills配置中的actions进行匹配。 +将调用方传入的want参数的[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)与待匹配Ability的skills配置中的actions进行匹配。 - 调用方传入的want参数的action不为空,待匹配Ability的skills配置中的actions为空,则action匹配失败。 @@ -64,7 +64,7 @@ ### want参数的entities匹配规则 -将调用方传入的want参数的entities与待匹配Ability的skills配置中的entities进行匹配。 +将调用方传入的want参数的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)与待匹配Ability的skills配置中的entities进行匹配。 - 调用方传入的want参数的entities为空,待匹配Ability的skills配置中的entities不为空,则entities匹配成功。 @@ -84,7 +84,7 @@ 调用方传入的want参数中设置uri和type参数发起组件启动请求,系统会遍历当前系统已安装的组件列表,并逐个匹配待匹配Ability的skills配置中的uris数组,如果待匹配Ability的skills配置中的uris数组中只要有一个可以匹配调用方传入的want参数中设置的uri和type即为匹配成功。 - **图3** want参数中uri和type皆不为空时的匹配规则 +**图3** want参数中uri和type皆不为空时的匹配规则 want-uri-type1 实际应用中,uri和type共存在四种情况,下面将讲解四种情况的具体匹配规则: @@ -110,7 +110,7 @@ 下图为了简化描述,称want中传入的uri为w_uri,称want中传入的type为w_type, 待匹配Ability的skills配置中uris为s_uris,其中每个元素为s_uri;按自上而下顺序匹配。 - **图4** want参数中uri和type的具体匹配规则 +**图4** want参数中uri和type的具体匹配规则 want-uri-type2 @@ -133,24 +133,24 @@ > **说明:** > 待匹配Ability的skills配置的uris中scheme、host、port、path、pathStartWith和pathRegex属性拼接,如果依次声明了path、pathStartWith和pathRegex属性时,uris将分别拼接为如下三种表达式: > -> - **全路径表达式**:scheme://host:port/path +> - **全路径表达式**:`scheme://host:port/path` > -> - **前缀表达式**:scheme://host:port/pathStartWith +> - **前缀表达式**:`scheme://host:port/pathStartWith` > -> - **正则表达式**:scheme://host:port/pathRegex +> - **正则表达式**:`scheme://host:port/pathRegex` ### type匹配规则 > **说明:** -> 此小节所述的type匹配规则的适用性需建立在want参数内type不为空的基础上。当want参数内type为空时请参考[want参数的uri和type匹配规则](#want参数的uri和type匹配规则)。 +> 此小节所述的type匹配规则的适用性需建立在want参数内type不为空的基础上。当want参数内type为空时请参见[want参数的uri和type匹配规则](#want参数的uri和type匹配规则)。 这里为了简化描述,称want中传入的uri为w_type,待匹配Ability的skills数组中uris的type数据为s_type,具体的匹配规则如下: - 如果s_type为空,则匹配失败。 -- 如果s_type或者w_type为通配符"\*/\*",则匹配成功。 +- 如果s_type或者w_type为通配符`*/*`,则匹配成功。 -- 如果s_type最后一个字符为通配符'\*',如"prefixType/\*",则当w_type包含"prefixType/"时匹配成功,否则匹配失败。 +- 如果s_type最后一个字符为通配符`*`,如`prefixType/*`,则当w_type包含`prefixType/`时匹配成功,否则匹配失败。 -- 如果w_type最后一个字符为通配符'\*',如"prefixType/\*",则当s_type包含"prefixType/"时匹配成功,否则匹配失败。 +- 如果w_type最后一个字符为通配符`*`,如`prefixType/*`,则当s_type包含`prefixType/`时匹配成功,否则匹配失败。 diff --git a/zh-cn/application-dev/application-models/uiability-launch-type.md b/zh-cn/application-dev/application-models/uiability-launch-type.md index 7dca65f44256b10a2dfd463ce3514796d0a82b4e..e07b1567ed1fb763c83b0ae283fdfda1bcae36d1 100644 --- a/zh-cn/application-dev/application-models/uiability-launch-type.md +++ b/zh-cn/application-dev/application-models/uiability-launch-type.md @@ -15,15 +15,14 @@ UIAbility的启动模式是指UIAbility实例在启动时的不同呈现状态 singleton启动模式为单实例模式,也是默认情况下的启动模式。 -每次调用startAbility()方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。 +每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。 **图1** 单实例模式演示效果 -uiability-launch-type1 +uiability-launch-type1 -> **说明:** -> 应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用startAbility()方法启动该UIAbility实例,此时只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其onCreate()和onWindowStageCreate()生命周期回调。 +> **说明**:应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其[onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。 -如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的"launchType"字段配置为"singleton"即可。 +如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`singleton`即可。 ```json @@ -43,12 +42,12 @@ singleton启动模式为单实例模式,也是默认情况下的启动模式 ## standard启动模式 -standard启动模式为标准实例模式,每次调用startAbility()方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。 +standard启动模式为标准实例模式,每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。 - **图2** 标准实例模式演示效果 -standard-mode +**图2** 标准实例模式演示效果 +standard-mode -standard启动模式的开发使用,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的"launchType"字段配置为"standard"即可。 +standard启动模式的开发使用,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`standard`即可。 ```json @@ -70,19 +69,12 @@ standard启动模式的开发使用,在[module.json5配置文件](../quick-sta specified启动模式为指定实例模式,针对一些特殊场景使用(例如文档应用中每次新建文档希望都能新建一个文档实例,重复打开一个已保存的文档希望打开的都是同一个文档实例)。 -在UIAbility实例创建之前,允许开发者为该实例创建一个唯一的字符串Key,创建的UIAbility实例绑定Key之后,后续每次调用startAbility()方法时,都会询问应用使用哪个Key对应的UIAbility实例来响应startAbility()请求。运行时由UIAbility内部业务决定是否创建多实例,如果匹配有该UIAbility实例的Key,则直接拉起与之绑定的UIAbility实例,否则创建一个新的UIAbility实例。 - - **图3** 指定实例模式演示效果 +**图3** 指定实例模式演示效果 uiability-launch-type2 -> **说明:** -> -> 1. 应用的UIAbility实例已创建,该UIAbility配置为指定实例模式,再次调用startAbility()方法启动该UIAbility实例,且[AbilityStage](abilitystage.md)的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)回调匹配到一个已创建的UIAbility实例。此时,再次启动该UIAbility时,只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其onCreate()和onWindowStageCreate()生命周期回调。 -> 2. DevEco Studio默认工程中未自动生成AbilityStage,AbilityStage文件的创建请参见[AbilityStage组件容器](abilitystage.md)。 - -例如有两个UIAbility:EntryAbility和FuncAbility,FuncAbility配置为specified启动模式,需要从EntryAbility的页面中启动FuncAbility。 +例如有两个UIAbility:EntryAbility和SpecifiedAbility,SpecifiedAbility配置为specified启动模式,需要从EntryAbility的页面中启动SpecifiedAbility。 -1. 在FuncAbility中,将[module.json5配置文件](../quick-start/module-configuration-file.md)的"launchType"字段配置为"specified"。 +1. 在SpecifiedAbility中,将[module.json5配置文件](../quick-start/module-configuration-file.md)的`launchType`字段配置为`specified`。 ```json { @@ -98,7 +90,8 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( } ``` -2. 在EntryAbility中,调用startAbility()方法时,在want参数中,增加一个自定义参数来区别UIAbility实例,例如增加一个"instanceKey"自定义参数。 +2. 在UIAbility实例创建之前,允许开发者为该实例创建一个唯一的字符串Key,创建的UIAbility实例绑定Key之后,后续每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,都会询问应用使用哪个Key对应的UIAbility实例来响应[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)请求。 + 在EntryAbility中,调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,在want参数中,增加一个自定义参数来区别UIAbility实例,例如增加一个`instanceKey`自定义参数。 ```ts // 在启动指定实例模式的UIAbility时,给每一个UIAbility实例配置一个独立的Key标识 @@ -110,7 +103,7 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( let want = { deviceId: '', // deviceId为空表示本设备 bundleName: 'com.example.myapplication', - abilityName: 'FuncAbility', + abilityName: 'SpecifiedAbility', moduleName: 'module1', // moduleName非必选 parameters: { // 自定义信息 instanceKey: getInstance(), @@ -123,8 +116,9 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( // ... }) ``` - -3. 由于FuncAbility的启动模式配置为了指定实例启动模式,在FuncAbility启动之前,会先进入其对应的AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调中,解析传入的want参数,获取"instanceKey"自定义参数。根据业务需要通过AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调返回一个字符串Key标识。[如果返回的Key对应一个已启动的UIAbility](mission-management-launch-type.md#fig14520125175314),则会将之前的UIAbility拉回前台并获焦,而不创建新的实例,否则创建新的实例并启动。 + +3. 运行时由UIAbility内部业务决定是否创建多实例,如果匹配有该UIAbility实例的Key,则直接拉起与之绑定的UIAbility实例,否则创建一个新的UIAbility实例。 + 由于SpecifiedAbility的启动模式配置为了指定实例启动模式,在SpecifiedAbility启动之前,会先进入其对应的AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调中,解析传入的want参数,获取`instanceKey`自定义参数。根据业务需要通过AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调返回一个字符串Key标识。[如果返回的Key对应一个已启动的UIAbility](mission-management-launch-type.md#fig14520125175314),则会将之前的UIAbility拉回前台并获焦,而不创建新的实例,否则创建新的实例并启动。 ```ts import AbilityStage from '@ohos.app.ability.AbilityStage'; @@ -132,19 +126,24 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( export default class MyAbilityStage extends AbilityStage { onAcceptWant(want): string { // 在被调用方的AbilityStage中,针对启动模式为specified的UIAbility返回一个UIAbility实例对应的一个Key值 - // 当前示例指的是module1 Module的FuncAbility - if (want.abilityName === 'FuncAbility') { + // 当前示例指的是module1 Module的SpecifiedAbility + if (want.abilityName === 'SpecifiedAbility') { // 返回的字符串Key标识为自定义拼接的字符串内容 - return `FuncAbilityInstance_${want.parameters.instanceKey}`; + return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`; } return ''; } } ``` - + + > **说明:** + > + > 1. 应用的UIAbility实例已创建,该UIAbility配置为指定实例模式,再次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例,且[AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md)的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)回调匹配到一个已创建的UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时再次启动该UIAbility时,只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其[onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。 + > 2. DevEco Studio默认工程中未自动生成AbilityStage,AbilityStage文件的创建请参见[AbilityStage组件容器](abilitystage.md)。 + 例如在文档应用中,可以对不同的文档实例内容绑定不同的Key值。当每次新建文档的时候,可以传入不同的新Key值(如可以将文件的路径作为一个Key标识),此时AbilityStage中启动UIAbility时都会创建一个新的UIAbility实例;当新建的文档保存之后,回到桌面,或者新打开一个已保存的文档,回到桌面,此时再次打开该已保存的文档,此时AbilityStage中再次启动该UIAbility时,打开的仍然是之前原来已保存的文档界面。 - + 以如下步骤所示进行举例说明。 1. 打开文件A,对应启动一个新的UIAbility实例,例如启动“UIAbility实例1”。 diff --git a/zh-cn/application-dev/application-models/want-overview.md b/zh-cn/application-dev/application-models/want-overview.md index b02617e6192c92214808fdb0d7d1c6d9c63db37d..2f4e72601056a6bbdf2beb24898f441bee11dd23 100644 --- a/zh-cn/application-dev/application-models/want-overview.md +++ b/zh-cn/application-dev/application-models/want-overview.md @@ -12,7 +12,7 @@ ## Want的类型 - **显式Want**:在启动Ability时指定了abilityName和bundleName的Want称为显式Want。 - 当有明确处理请求的对象时,通过提供目标Ability所在应用的Bundle名称信息(bundleName),并在Want内指定abilityName便可启动目标Ability。显式Want通常用于在当前应用开发中启动某个已知的Ability。参数说明参见[Want参数说明](want-overview.md#Want参数说明)。 + 当有明确处理请求的对象时,通过提供目标Ability所在应用的Bundle名称信息(bundleName),并在Want内指定abilityName便可启动目标Ability。显式Want通常用于在当前应用开发中启动某个已知的Ability。 ```ts let wantInfo = { @@ -22,7 +22,7 @@ } ``` -- **隐式Want**:在启动UIAbility时未指定abilityName的Want称为隐式Want。 +- **隐式Want**:在启动Ability时未指定abilityName的Want称为隐式Want。 当请求处理的对象不明确时,希望在当前应用中使用其他应用提供的某个能力(通过[skills标签](../quick-start/module-configuration-file.md#skills标签)定义),而不关心提供该能力的具体应用,可以使用隐式Want。例如使用隐式Want描述需要打开一个链接的请求,而不关心通过具体哪个应用打开,系统将匹配声明支持该请求的所有应用。 @@ -47,18 +47,3 @@ > - 调用方传入的want参数中不带有abilityName和bundleName,则不允许通过隐式Want启动所有应用的ServiceExtensionAbility。 > > - 调用方传入的want参数中带有bundleName,则允许使用startServiceExtensionAbility()方法隐式Want启动ServiceExtensionAbility,默认返回优先级最高的ServiceExtensionAbility,如果优先级相同,返回第一个。 - -## Want参数说明 - -| 名称 | 读写属性 | 类型 | 必填 | 描述 | -| -------- | -------- | -------- | -------- | -------- | -| deviceId | 只读 | string | 否 | 表示目标Ability所在设备ID。如果未设置该字段,则表明本设备。 | -| bundleName | 只读 | string | 否 | 表示目标Ability所在应用名称。 | -| moduleName | 只读 | string | 否 | 表示目标Ability所属的模块名称。 | -| abilityName | 只读 | string | 否 | 表示目标Ability名称。如果未设置该字段,则该Want为隐式。如果在Want中同时指定了bundleName,moduleName和abilityName,则Want可以直接匹配到指定的Ability。 | -| uri | 只读 | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在Want中指定了uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | -| type | 只读 | string | 否 | 表示携带数据类型,使用[MIME类型](https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com%E3%80%82)规范。例如:"text/plain"、"image/\*"等。 | -| [action](../reference/apis/js-apis-ability-wantConstant.md) | 只读 | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可定义该字段,配合uri或parameters来表示对数据要执行的操作。如打开,查看该uri数据。例如,当uri为一段网址,action为ohos.want.action.viewData则表示匹配可查看该网址的Ability。 | -| [entities](../reference/apis/js-apis-ability-wantConstant.md) | 只读 | Array<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器,视频播放器),在隐式Want中是对action的补充。在隐式Want中,您可定义该字段,来过滤匹配UIAbility类别,如必须是浏览器。例如,在action字段的举例中,可存在多个应用声明了支持查看网址的操作,其中有应用为普通社交应用,有的为浏览器应用,您可通过entity.system.browsable过滤掉非浏览器的其他应用。 | -| [flags](../reference/apis/js-apis-ability-wantConstant.md#wantconstantflags) | 只读 | number | 否 | 表示处理Want的方式。例如通过wantConstant.Flags.FLAG_ABILITY_CONTINUATION表示是否以设备间迁移方式启动Ability。 | -| parameters | 只读 | {[key: string]: any} | 否 | 此参数用于传递自定义数据,通过用户自定义的键值对进行数据填充,具体支持的数据类型如[Want API](../reference/apis/js-apis-app-ability-want.md)所示。 | diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index 46f40d627eb8894fc3ce46167965f2d446a018ee..a4b72ddf0306ce59332ac78754cf1d493fcb9452 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ ## 接口说明 -以下是关系型数据库的常用接口说明,大部分为异步接口。异步接口均有callback和Promise两种返回形式,下表均以Promise形式为例,更多接口及使用方式请见[关系型数据库](../reference/apis/js-apis-data-rdb.md)。 +以下是关系型数据库的常用接口说明,大部分为异步接口。异步接口均有callback和Promise两种返回形式,下表均以Promise形式为例,更多接口及使用方式请见[关系型数据库](../reference/apis/js-apis-data-relationalStore.md)。 ### 数据库的创建和删除 @@ -17,8 +17,8 @@ | 接口名 | 描述 | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> | 获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。
-context:应用程序或功能的上下文。
-config:与此RDB存储相关的数据库配置。
-version:数据库版本。目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | -| deleteRdbStoreV9(context: Context, name: string): Promise<void> | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。
-context:应用程序或功能的上下文。
-name:数据库名称。 | +| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。
-context:应用上下文。
-config:与此RDB存储相关的数据库配置。 | +| deleteRdbStore(context: Context, name: string): Promise<void> | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。
-context:应用上下文。
-name:数据库名称。 | ### 数据库的增删改查 @@ -33,29 +33,29 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise<number> | 向目标表中插入一行数据,使用Promise异步回调。
如果操作成功,返回行ID;否则返回-1。
-table:指定的目标表名。
-values:表示要插入到表中的数据行。 | + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | 向目标表中插入一行数据,使用Promise异步回调。
如果操作成功,返回行ID;否则返回-1。
-table:指定的目标表名。
-values:表示要插入到表中的数据行。 | - **更新** - 调用更新接口,传入要更新的数据,并通过RdbPredicatesV9指定更新条件。该接口的返回值表示更新操作影响的行数。如果更新失败,则返回0。 + 调用更新接口,传入要更新的数据,并通过RdbPredicates指定更新条件。该接口的返回值表示更新操作影响的行数。如果更新失败,则返回0。 **表3** 数据库更新API | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise<number> | 根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。
返回受影响的行数。
-values:以ValuesBucket存储的要更新的数据。
-predicates:表示RdbPredicatesV9的实例对象指定的更新条件。 | + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
返回受影响的行数。
-values:以ValuesBucket存储的要更新的数据。
-predicates:表示RdbPredicates的实例对象指定的更新条件。 | - **删除** - 调用删除接口,通过RdbPredicatesV9指定删除条件。该接口的返回值表示删除的数据行数,可根据此值判断是否删除成功。如果删除失败,则返回0。 + 调用删除接口,通过RdbPredicates指定删除条件。该接口的返回值表示删除的数据行数,可根据此值判断是否删除成功。如果删除失败,则返回0。 **表4** 数据库删除API | 类名 | 接口名 | 描述 | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | - | RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise<number> | 根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。
返回受影响的行数。
-predicates:RdbPredicatesV9的实例对象指定的删除条件。 | + | RdbStore | delete(predicates: RdbPredicates): Promise<number> | 根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。
返回受影响的行数。
-predicates:RdbPredicates的实例对象指定的删除条件。 | - **查询** @@ -66,35 +66,34 @@ **表5** 数据库查询API - -| 类名 | 接口名 | 描述 | -| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array<string>): Promise<ResultSetV9> | 根据指定条件查询数据库中的数据,使用Promise异步回调。
-predicates:表示RdbPredicatesV9的实例对象指定的查询条件。
-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | -| RdbStoreV9 | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSetV9> | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。
-sql:指定要查询的SQL语句。
-bindArgs:SQL语句中参数的值。 | -| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> | 根据指定条件查询指定远程设备数据库中的数据。使用Promise异步回调。
-device:指定远程查询的设备networkId。
-table:指定远程查询的表名。
-predicates:表示RdbPredicatesV9的实例对象,指定查询的条件。
-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | + | 类名 | 接口名 | 描述 | + | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | 根据指定条件查询数据库中的数据,使用Promise异步回调。
-predicates:表示RdbPredicates的实例对象指定的查询条件。
-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSet> | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。
-sql:指定要查询的SQL语句。
-bindArgs:SQL语句中参数的值。 | + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | 根据指定条件查询指定远程设备数据库中的数据。使用Promise异步回调。
-device:指定远程查询的设备networkId。
-table:指定远程查询的表名。
-predicates:表示RdbPredicates的实例对象,指定查询的条件。
-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | ### 数据库谓词的使用 -关系型数据库提供了用于设置数据库操作条件的谓词RdbPredicatesV9,该类确定RDB中条件表达式的值是true还是false。 +关系型数据库提供了用于设置数据库操作条件的谓词RdbPredicates,该类确定RDB中条件表达式的值是true还是false。 -以下列举几个常用谓词,更多谓词的使用请见[关系型数据库谓词](../reference/apis/js-apis-data-rdb.md#rdbpredicates)。 +以下列举几个常用谓词,更多谓词的使用请见[关系型数据库谓词](../reference/apis/js-apis-data-relationalStore.md#rdbpredicates)。 **表6** 数据库谓词API | 类名 | 接口名 | 描述 | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicatesV9:返回与指定字段匹配的谓词。 | -| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicatesV9:返回与指定字段匹配的谓词。 | -| RdbPredicatesV9 | or(): RdbPredicatesV9 | 将或条件添加到谓词中。
-RdbPredicatesV9:返回带有或条件的谓词。 | -| RdbPredicatesV9 | and(): RdbPredicatesV9 | 向谓词添加和条件。
-RdbPredicatesV9:返回带有和条件的谓词。 | -| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | 配置谓词以匹配数据字段为String且value包含指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicatesV9:返回带有包含条件的谓词。 | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | or(): RdbPredicates | 将或条件添加到谓词中。
-RdbPredicates:返回带有或条件的谓词。 | +| RdbPredicates | and(): RdbPredicates | 向谓词添加和条件。
-RdbPredicates:返回带有和条件的谓词。 | +| RdbPredicates | contains(field: string, value: string): RdbPredicates | 配置谓词以匹配数据字段为String且value包含指定值的字段。
-field:数据库表中的列名。
-value:指示要与谓词匹配的值。
-RdbPredicates:返回带有包含条件的谓词。 | ### 查询结果集的使用 -关系型数据库提供了查询返回的结果集ResultSetV9,其指向查询结果中的一行数据,供用户对查询结果进行遍历和访问。 +关系型数据库提供了查询返回的结果集ResultSet,其指向查询结果中的一行数据,供用户对查询结果进行遍历和访问。 -更多结果集的接口使用,请见[结果集](../reference/apis/js-apis-data-resultset.md)。 +更多结果集的接口使用,请见[结果集](../reference/apis/js-apis-data-relationalStore.md#resultset)。 > **须知:** > **结果集使用完后,请一定要调用close方法显式关闭。** @@ -103,12 +102,12 @@ | 类名 | 接口名 | 描述 | | ----------- | ---------------------------------------- | ------------------------------------------ | -| ResultSetV9 | goToFirstRow(): boolean | 将结果集移动到第一行。 | -| ResultSetV9 | getString(columnIndex: number): string | 获取当前行指定列的值,以String类型返回。 | -| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 | -| ResultSetV9 | getDouble(columnIndex: number): number | 获取当前行指定列的值,以double型返回。 | -| ResultSetV9 | getLong(columnIndex: number): number | 获取当前行指定列的值,以Long形式返回。 | -| ResultSetV9 | close(): void | 关闭结果集。 | +| ResultSet | goToFirstRow(): boolean | 将结果集移动到第一行。 | +| ResultSet | getString(columnIndex: number): string | 获取当前行指定列的值,以String类型返回。 | +| ResultSet | getBlob(columnIndex: number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 | +| ResultSet | getDouble(columnIndex: number): number | 获取当前行指定列的值,以double型返回。 | +| ResultSet | getLong(columnIndex: number): number | 获取当前行指定列的值,以Long形式返回。 | +| ResultSet | close(): void | 关闭结果集。 | @@ -116,7 +115,7 @@ > **说明:** > -> - 在使用RdbStoreV9的setDistributedTables、obtainDistributedTableName、sync、on、off接口时,需要请求相应的权限:ohos.permission.DISTRIBUTED_DATASYNC。 +> - 在使用RdbStore的setDistributedTables、obtainDistributedTableName、sync、on、off接口时,需要请求相应的权限:ohos.permission.DISTRIBUTED_DATASYNC。 > - 使用分布式列表前,需要先建立设备间组网,具体接口及使用可见[设备管理](../reference/apis/js-apis-device-manager.md)。 **设置分布式列表** @@ -125,7 +124,7 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | setDistributedTables(tables: Array\): Promise\ | 设置分布式列表,使用Promise异步回调。
-tables:要设置的分布式列表表名。 | +| RdbStore | setDistributedTables(tables: Array\): Promise\ | 设置分布式列表,使用Promise异步回调。
-tables:要设置的分布式列表表名。 | **根据本地表名获取指定远程设备的分布式表名** @@ -135,7 +134,7 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | obtainDistributedTableName(device: string, table: string): Promise\ | 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。
-device:远程设备。
-table:本地表名。 | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。
-device:远程设备。
-table:本地表名。 | **在设备之间同步数据** @@ -143,7 +142,7 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\> | 在设备之间同步数据,使用Promise异步回调。
-mode:指同步模式。SYNC_MODE_PUSH 表示数据从本地设备推送到远程设备;SYNC_MODE_PULL 表示数据从远程设备拉至本地设备。
-predicates:约束同步数据和设备。
-string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | 在设备之间同步数据,使用Promise异步回调。
-mode:指同步模式。SYNC_MODE_PUSH 表示数据从本地设备推送到远程设备;SYNC_MODE_PULL 表示数据从远程设备拉至本地设备。
-predicates:约束同步数据和设备。
-string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | **注册数据库的观察者** @@ -151,7 +150,7 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。
-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。
-observer:指分布式数据库中数据更改事件的观察者。 | +| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。
-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。
-observer:指分布式数据库中数据更改事件的观察者。 | **从数据库中删除指定类型的指定观察者** @@ -159,7 +158,7 @@ | 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | 从数据库中删除指定类型的指定观察者,使用callback异步回调。
-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。
-observer:指已注册的数据更改观察者。 | +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | 从数据库中删除指定类型的指定观察者,使用callback异步回调。
-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。
-observer:指已注册的数据更改观察者。 | ### 数据库的备份和恢复 @@ -169,7 +168,7 @@ | 类名 | 接口名 | 描述 | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | backup(destName: string): Promise<void> | 以指定名称备份数据库,使用Promise异步回调。
-destName:指定数据库的备份文件名。 | +| RdbStore | backup(destName: string): Promise<void> | 以指定名称备份数据库,使用Promise异步回调。
-destName:指定数据库的备份文件名。 | **恢复** @@ -177,17 +176,17 @@ | 类名 | 接口名 | 描述 | | ---------- | --------------------------------------------- | ------------------------------------------------------------ | -| RdbStoreV9 | restore(srcName: string): Promise<void> | 从指定的数据库备份文件恢复数据库,使用Promise异步回调。
-srcName:指定数据库的备份文件名。 | +| RdbStore | restore(srcName: string): Promise<void> | 从指定的数据库备份文件恢复数据库,使用Promise异步回调。
-srcName:指定数据库的备份文件名。 | -**事务** +### 事务 **表15** 事务 | 类名 | 接口名 | 描述 | | -------- | ----------------------- | --------------------------------- | -| RdbStoreV9 | beginTransaction(): void | 在开始执行SQL语句之前,开始事务。 | -| RdbStoreV9 | commit(): void | 提交已执行的SQL语句。 | -| RdbStoreV9 | rollBack(): void | 回滚已经执行的SQL语句。 | +| RdbStore | beginTransaction(): void | 在开始执行SQL语句之前,开始事务。 | +| RdbStore | commit(): void | 提交已执行的SQL语句。 | +| RdbStore | rollBack(): void | 回滚已经执行的SQL语句。 | ## 开发步骤 @@ -202,23 +201,23 @@ FA模型示例: ```js - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // 获取context import featureAbility from '@ohos.ability.featureAbility' let context = featureAbility.getContext() const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "RdbTest.db", + const STORE_CONFIG = { name: "RdbTest.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` Stage模型示例: ```ts - import data_rdb from '@ohos.data.rdb' + import data_rdb from '@ohos.data.relationalStore' // 获取context import Ability from '@ohos.application.Ability' let context = null @@ -230,10 +229,10 @@ const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIGV9 = { name: "rdbstore.db", + const STORE_CONFIG = { name: "rdbstore.db", securityLevel: data_rdb.SecurityLevel.S1} - data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - rdbStoreV9.executeSql(CREATE_TABLE_TEST) + data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { + rdbStore.executeSql(CREATE_TABLE_TEST) console.info('create table done.') }) ``` @@ -247,9 +246,24 @@ 示例代码如下: ```js - var u8 = new Uint8Array([1, 2, 3]) + let u8 = new Uint8Array([1, 2, 3]) const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } - let insertPromise = rdbStoreV9.insert("test", valueBucket) + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + + ```js + //使用事务插入数据 + beginTransaction() + try { + let u8 = new Uint8Array([1, 2, 3]) + const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } + const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 } + let insertPromise1 = rdbStore.insert("test", valueBucket1) + let insertPromise2 = rdbStore.insert("test", valueBucket2) + commit() + } catch (e) { + rollBack() + } ``` 3. 查询数据。 @@ -263,17 +277,17 @@ 示例代码如下: ```js - let predicatesV9 = new data_rdb.RdbPredicatesV9("test"); - predicatesV9.equalTo("name", "Tom") - let promisequery = rdbStoreV9.query(predicatesV9) - promisequery.then((resultSetV9) => { - resultSetV9.goToFirstRow() - const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) - const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) - const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) - const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) - const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) - resultSetV9.close() + let predicates = new data_rdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let promisequery = rdbStore.query(predicates) + promisequery.then((resultSet) => { + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("id")) + const name = resultSet.getString(resultSet.getColumnIndex("name")) + const age = resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) + resultSet.close() }) ``` @@ -301,7 +315,7 @@ context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { console.info(`result.requestCode=${result.requestCode}`) }) - let promise = rdbStoreV9.setDistributedTables(["test"]) + let promise = rdbStore.setDistributedTables(["test"]) promise.then(() => { console.info("setDistributedTables success.") }).catch((err) => { @@ -320,9 +334,9 @@ 示例代码如下: ```js - let predicateV9 = new data_rdb.RdbPredicatesV9('test') - predicateV9.inDevices(['12345678abcde']) - let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9) + let predicate = new data_rdb.RdbPredicates('test') + predicate.inDevices(['12345678abcde']) + let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate) promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { @@ -349,7 +363,7 @@ } try { - rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { console.log('register observer failed') } @@ -364,8 +378,8 @@ 示例代码如下: ```js - let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test"); - let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName) + let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); + let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` 8. 远程查询。 @@ -378,17 +392,17 @@ 示例代码如下: ```js - let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee') - predicatesV9.greaterThan("id", 0) - let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9) - promiseQuery.then((resultSetV9) => { - while (resultSetV9.goToNextRow()) { - let idx = resultSetV9.getLong(0); - let name = resultSetV9.getString(1); - let age = resultSetV9.getLong(2); + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + promiseQuery.then((resultSet) => { + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); console.info(idx + " " + name + " " + age); } - resultSetV9.close(); + resultSet.close(); }).catch((err) => { console.info("failed to remoteQuery, err: " + err) }) @@ -401,7 +415,7 @@ 示例代码如下: ```js - let promiseBackup = rdbStoreV9.backup("dbBackup.db") + let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(() => { console.info('Backup success.') }).catch((err) => { @@ -413,7 +427,7 @@ 示例代码如下: ```js - let promiseRestore = rdbStoreV9.restore("dbBackup.db") + let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { console.info('Restore success.') }).catch((err) => { diff --git a/zh-cn/application-dev/media/avsession-guidelines.md b/zh-cn/application-dev/media/avsession-guidelines.md index e2ca9f139cbfaa6d9cd6d0f6ae1c9e4ec91ccf0f..033df56f572263677db7fb6e71b1736d881c093f 100644 --- a/zh-cn/application-dev/media/avsession-guidelines.md +++ b/zh-cn/application-dev/media/avsession-guidelines.md @@ -191,7 +191,7 @@ currentSession.on('playNext', () => { }); console.log("调用AudioPlayer.play方法"); // 设置播放状态 - let time = (new Data()).getTime(); + let time = (new Date()).getTime(); currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => { console.info('setAVPlaybackState successfully'); }).catch((err) => { @@ -286,7 +286,7 @@ currentSession.off('outputDeviceChange'); // 去激活session并销毁对象 currentSession.deactivate().then(() => { - currentSession.destory(); + currentSession.destroy(); }); ``` diff --git a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md index 73356b179707aeafa783dee6b6a0e051da4c547f..33cfa6df243811280fc3940072d01d34c42e5959 100644 --- a/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md @@ -91,7 +91,9 @@ struct MyComponent { - 支持多个实例:一个组件中可以定义多个标有@Prop的属性; - 创建自定义组件时将值传递给@Prop变量进行初始化:在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。 -> **说明:** @Prop修饰的变量不能在组件内部进行初始化。 +> **说明:** +> +> @Prop修饰的变量不能在组件内部进行初始化。 **示例:** @@ -158,7 +160,9 @@ struct CountDownComponent { - 双向通信:子组件对@Link变量的更改将同步修改父组件中的@State变量; - 创建自定义组件时需要将变量的引用传递给@Link变量,在创建组件的新实例时,必须使用命名参数初始化所有@Link变量。@Link变量可以使用@State变量或@Link变量的引用进行初始化,@State变量可以通过`'$'`操作符创建引用。 -> **说明:** @Link修饰的变量不能在组件内部进行初始化。 +> **说明:** +> +> @Link修饰的变量不能在组件内部进行初始化。 **简单类型示例:** @@ -395,7 +399,9 @@ struct ViewB { @Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。@Consume在感知到@Provide数据的更新后,会触发当前自定义组件的重新渲染。 -> **说明:** 使用@Provide和@Consume时应避免循环引用导致死循环。 +> **说明:** +> +> 使用@Provide和@Consume时应避免循环引用导致死循环。 ### @Provide diff --git a/zh-cn/application-dev/quick-start/stage-structure.md b/zh-cn/application-dev/quick-start/stage-structure.md new file mode 100644 index 0000000000000000000000000000000000000000..6fe06ff209f927a182deb971d1195c3ce373cbba --- /dev/null +++ b/zh-cn/application-dev/quick-start/stage-structure.md @@ -0,0 +1,25 @@ +# 应用配置文件概述(Stage模型) + + +每个应用项目必须在项目的代码目录下加入配置文件,这些配置文件会向编译工具、操作系统和应用市场提供应用的基本信息。 + + +在基于Stage模型开发的应用项目代码下,都存在一个app.json5及一个或多个module.json5这两种配置文件。 + + +[app.json5](app-configuration-file.md)主要包含以下内容: + + +- 应用的全局配置信息,包含应用的Bundle名称、开发厂商、版本号等基本信息。 + +- 特定设备类型的配置信息。 + + +[module.json5](module-configuration-file.md)主要包含以下内容: + + +- Module的基本配置信息,例如Module名称、类型、描述、支持的设备类型等基本信息。 + +- [应用组件](../application-models/stage-model-development-overview.md)信息,包含UIAbility组件和ExtensionAbility组件的描述信息。 + +- 应用运行过程中所需的权限信息。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md index 19c13000427a72db9a781c4f7a9add5136f2fa56..f6a99d431dbf0d43482dee2b200d536a009c1845 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-want.md @@ -1,6 +1,6 @@ # @ohos.app.ability.Want (Want) -Want是对象间信息传递的载体, 可以用于应用组件间的信息传递。 Want的使用场景之一是作为startAbility的参数, 其包含了指定的启动目标, 以及启动时需携带的相关数据, 如bundleName和abilityName字段分别指明目标Ability所在应用的包名以及对应包内的Ability名称。当Ability A需要启动Ability B并传入一些数据时, 可使用Want作为载体将这些数据传递给Ability B。 +Want是对象间信息传递的载体, 可以用于应用组件间的信息传递。 Want的使用场景之一是作为startAbility的参数, 其包含了指定的启动目标, 以及启动时需携带的相关数据, 如bundleName和abilityName字段分别指明目标Ability所在应用的包名以及对应包内的Ability名称。当UIAbilityA需要启动UIAbilityB并传入一些数据时, 可使用Want作为载体将这些数据传递给UIAbilityB。 > **说明:** > @@ -19,25 +19,25 @@ import Want from '@ohos.app.ability.Want'; | 名称 | 类型 | 必填 | 说明 | | ----------- | -------------------- | ---- | ------------------------------------------------------------ | | deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 | -| bundleName | string | 否 | 表示Bundle名称。 | -| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | -| uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | -| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | -| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-app-ability-wantConstant.md#wantConstant.Flags)。 | -| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md)。 | -| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
ohos.aafwk.callerPid 表示拉起方的pid。
ohos.aafwk.param.callerToken 表示拉起方的token。
ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | -| entities | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity)。 | -| moduleName | string | 否 | 表示待启动的Ability所属的模块(module)。 | +| bundleName | string | 否 | 表示待启动Ability所在的应用Bundle名称。 | +| moduleName | string | 否 | 表示待启动的Ability所属的模块名称。 | +| abilityName | string | 否 | 表示待启动Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | +| [action](js-apis-app-ability-wantConstant.md#wantConstant.Action) | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。隐式Want定义及匹配规则请参见[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md)。 | +| [entities](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | Array\ | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 | +| uri | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在Want中指定了uri,则Want将匹配指定的Uri信息,包括`scheme`、`schemeSpecificPart`、`authority`和`path`信息。 | +| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义请参见https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | +| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:
- ohos.aafwk.callerPid:表示拉起方的pid。
- ohos.aafwk.param.callerToken:表示拉起方的token。
- ohos.aafwk.param.callerUid:表示[BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | +| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | 否 | 表示处理Want的方式。默认传数字。
例如通过wantConstant.Flags.FLAG_ABILITY_CONTINUATION表示是否以设备间迁移方式启动Ability。 | **示例:** -- 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象) +- 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。 ```ts let want = { "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", "moduleName": "entry" // moduleName非必选 }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want'; }) ``` -- 通过自定字段传递数据, 以下为当前支持类型。(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象) +- 通过自定字段传递数据, 以下为当前支持类型(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。 * 字符串(String) ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want'; * 数字(Number) ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want'; * 布尔(Boolean) ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want'; * 对象(Object) ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want'; * 数组(Array) ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -109,30 +109,29 @@ import Want from '@ohos.app.ability.Want'; ``` * 文件描述符(FD) ```ts - import fileio from '@ohos.fileio'; - let fd; - try { - fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); - } catch(e) { - console.log("openSync fail:" + JSON.stringify(e)); + import fileio from '@ohos.fileio'; + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // deviceId为空表示本设备 + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", + "moduleName": "entry", // moduleName非必选 + "parameters": { + "keyFd":{"type":"FD", "value":fd} } - let want = { - "deviceId": "", // deviceId为空表示本设备 - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry", // moduleName非必选 - "parameters": { - "keyFd":{"type":"FD", "value":fd} - } - }; - this.context.startAbility(want, (error) => { - // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability - console.log("error.code = " + error.code) - }) + }; + this.context.startAbility(want, (error) => { + // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability + console.log("error.code = " + error.code) + }) ``` - 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want - diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md index c8121dfc31aff943dde774c159ba64649308f1ea..5f345d559ef34c5f33f55f2b7f103db8a45a6136 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -24,10 +24,11 @@ getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | 是 | WantAgent信息。 | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | 是 | WantAgent信息。 | | callback | AsyncCallback\ | 是 | 创建WantAgent的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -52,33 +53,31 @@ getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) - **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -90,15 +89,15 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -126,6 +125,7 @@ getWantAgent(info: WantAgentInfo): Promise\ | Promise\ | 以Promise形式返回WantAgent。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -150,30 +150,29 @@ getWantAgent(info: WantAgentInfo): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -212,6 +211,7 @@ getBundleName(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 获取WantAgent实例的包名的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -241,26 +241,26 @@ getBundleName(agent: WantAgent, callback: AsyncCallback\): void ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -272,7 +272,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -291,9 +291,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -321,6 +321,7 @@ getBundleName(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent实例的包名。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -345,32 +346,31 @@ getBundleName(agent: WantAgent): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -382,7 +382,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -397,9 +397,9 @@ function getWantAgentCallback(err, data) { console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -422,6 +422,7 @@ getUid(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 获取WantAgent实例的用户ID的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -446,33 +447,32 @@ getUid(agent: WantAgent, callback: AsyncCallback\): void | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts import WantAgent from '@ohos.app.ability.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -484,7 +484,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(err)); @@ -503,9 +503,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -533,6 +533,7 @@ getUid(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent实例的用户ID。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -557,32 +558,31 @@ getUid(agent: WantAgent): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -594,7 +594,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -609,9 +609,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -635,7 +635,7 @@ getWant(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | 是 | 获取WantAgent对象want的回调方法。 | **错误码:** -|错误码ID |错误信息 | +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -660,32 +660,31 @@ getWant(agent: WantAgent, callback: AsyncCallback\): void | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -697,7 +696,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -716,9 +715,9 @@ function getWantAgentCallback(err, data) { console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -748,6 +747,7 @@ getWant(agent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取WantAgent对象的want。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -772,32 +772,31 @@ getWant(agent: WantAgent): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -809,7 +808,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -824,9 +823,9 @@ function getWantAgentCallback(err, data) { console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -849,6 +848,7 @@ cancel(agent: WantAgent, callback: AsyncCallback\): void | callback | AsyncCallback\ | 是 | 取消WantAgent实例的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -873,32 +873,31 @@ cancel(agent: WantAgent, callback: AsyncCallback\): void | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -910,7 +909,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -929,9 +928,9 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -959,6 +958,7 @@ cancel(agent: WantAgent): Promise\ | Promise\ | 以Promise形式获取异步返回结果。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -983,32 +983,31 @@ cancel(agent: WantAgent): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1020,7 +1019,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1035,9 +1034,9 @@ function getWantAgentCallback(err, data) { console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1059,6 +1058,7 @@ trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\ | 否 | 主动激发WantAgent实例的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -1083,36 +1083,35 @@ trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void -判断两个WantAgent实例是否相等(callback形式)。 +判断两个WantAgent实例是否相等(Callback形式),以此来判断是否是来自同一应用的相同操作。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -1169,6 +1168,7 @@ equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\ | 是 | 判断两个WantAgent实例是否相等的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -1193,33 +1193,32 @@ equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\ -判断两个WantAgent实例是否相等(Promise形式)。 +判断两个WantAgent实例是否相等(Promise形式),以此来判断是否是来自同一应用的相同操作。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -1282,6 +1281,7 @@ equal(agent: WantAgent, otherAgent: WantAgent): Promise\ | Promise\ | 以Promise形式返回获取判断两个WantAgent实例是否相等的结果。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -1306,33 +1306,32 @@ equal(agent: WantAgent, otherAgent: WantAgent): Promise\ | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1344,7 +1343,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent1 = data; wantAgent2 = data; } else { @@ -1360,9 +1359,9 @@ function getWantAgentCallback(err, data) { console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1383,6 +1382,7 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; | callback | AsyncCallback\ | 是 | 获取一个WantAgent的OperationType信息的回调方法。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -1407,32 +1407,31 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1444,7 +1443,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed' + JSON.stringify(wantAgent)); @@ -1463,9 +1462,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` @@ -1491,6 +1490,7 @@ getOperationType(agent: WantAgent): Promise\; | Promise\ | 以Promise形式返回获取operationType的结果。 | **错误码:** +错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) | 错误码ID | 错误信息 | |-----------|--------------------| | 16000001 | Input error. The specified ability name does not exist. | @@ -1515,32 +1515,31 @@ getOperationType(agent: WantAgent): Promise\; | 16000151 | Invalid wantagent object.| | 16000152 | wantAgent object not found.| | 16000153 | wangAgent object canceled.| -以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) **示例:** ```ts //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1552,7 +1551,7 @@ var wantAgentInfo = { //getWantAgent回调 function getWantAgentCallback(err, data) { - if (err == undefined) { + if (err === undefined) { wantAgent = data; } else { console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); @@ -1567,9 +1566,9 @@ function getWantAgentCallback(err, data) { console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } } -try{ +try { WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); -} catch(err){ +} catch(err) { console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md index 6a9acda6c88e5b6d0199ff1077cfbedc66bed8d8..a10d06e97306a06dd16b4328e931b30fbb1c5563 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -48,20 +48,17 @@ createFormBindingData(obj?: Object | string): FormBindingData **示例:** ```ts -import featureAbility from '@ohos.ability.featureAbility'; -import fileio from '@ohos.fileio'; -let context=featureAbility.getContext(); -context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); +import fs from '@ohos.file.fs'; +import formBindingData from '@ohos.app.form.formBindingData'; + +try { + let fd = fs.openSync('/path/to/form.png') let obj = { "temperature": "21°", - "formImages": {"image": fd} + "formImages": { "image": fd } }; - try { - formBindingData.createFormBindingData(obj); - } catch (error) { - console.log(`catch err->${JSON.stringify(err)}`); - } -}) + formBindingData.createFormBindingData(obj); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md index 4175a69a6016cecd855876af5ebbd0c7111c3fb6..8159563dcaef3257e6155125ef9e42bfc8395853 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -33,7 +33,7 @@ onAddForm(want: Want): formBindingData.FormBindingData | 参数名 | 类型 | 必填 | 说明 | | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-want.md) | 是 | 当前ExtensionAbility相关的Want类型信息,包括卡片ID、卡片名称、卡片样式等。这些卡片信息必须作为持久数据进行管理,以便后续更新和删除卡片。 | +| want | [Want](js-apis-application-want.md) | 是 | 当前卡片相关的Want类型信息,包括卡片ID、卡片名称、卡片样式等。这些卡片信息必须作为持久数据进行管理,以便后续更新和删除卡片。 | **返回值:** @@ -45,17 +45,19 @@ onAddForm(want: Want): formBindingData.FormBindingData ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onAddForm(want) { console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); let dataObj1 = { - temperature:"11c", - "time":"11:00" + temperature: "11c", + "time": "11:00" }; let obj1 = formBindingData.createFormBindingData(dataObj1); return obj1; } -} +}; ``` ## onCastToNormalForm @@ -75,11 +77,13 @@ onCastToNormalForm(formId: string): void **示例:** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onCastToNormalForm(formId) { console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); } -} +}; ``` ## onUpdateForm @@ -99,17 +103,24 @@ onUpdateForm(formId: string): void **示例:** ```ts -import formBindingData from '@ohos.app.form.formBindingData' +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onUpdateForm(formId) { console.log('FormExtensionAbility onUpdateForm, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2).then((data)=>{ + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + formProvider.updateForm(formId, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } -} + console.error('Operation updateForm failed. Cause: ' + error); + }); + } +}; ``` ## onChangeFormVisibility @@ -129,21 +140,28 @@ onChangeFormVisibility(newStatus: { [key: string]: number }): void **示例:** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData' +import formProvider from '@ohos.app.form.formProvider'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onChangeFormVisibility(newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + + for (let key in newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + formProvider.updateForm(key, obj2).then((data) => { console.log('FormExtensionAbility context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error); + }); } } -} +}; ``` ## onFormEvent @@ -164,11 +182,13 @@ onFormEvent(formId: string, message: string): void **示例:** ```ts -export default class MyFormExtension extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onFormEvent(formId, message) { console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); } -} +}; ``` ## onRemoveForm @@ -188,11 +208,13 @@ onRemoveForm(formId: string): void **示例:** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + export default class MyFormExtensionAbility extends FormExtensionAbility { onRemoveForm(formId) { console.log('FormExtensionAbility onRemoveForm, formId:' + formId); } -} +}; ``` ## onConfigurationUpdate @@ -212,11 +234,13 @@ onConfigurationUpdate(newConfig: Configuration): void; **示例:** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onConfigurationUpdate(config) { console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); } -} +}; ``` ## onAcquireFormState @@ -236,13 +260,15 @@ onAcquireFormState?(want: Want): formInfo.FormState; **示例:** ```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formInfo from '@ohos.app.form.formInfo'; -class MyFormExtensionAbility extends FormExtensionAbility { + +export default class MyFormExtensionAbility extends FormExtensionAbility { onAcquireFormState(want) { console.log('FormExtensionAbility onAcquireFormState, want:' + want); return formInfo.FormState.UNKNOWN; } -} +}; ``` ## onShareForm @@ -270,14 +296,16 @@ onShareForm?(formId: string): { [key: string]: any } **示例:** ```ts -class MyFormExtensionAbility extends FormExtensionAbility { +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { onShareForm(formId) { console.log('FormExtensionAbility onShareForm, formId:' + formId); let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", + "temperature": "20", + "time": "2022-8-8 09:59", }; return wantParams; } -} +}; ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md index d903617a76e09a06aac287347d8ba863860a101c..621d6afda55b9df0797e30cb094ddc6a466fdfc0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -1,6 +1,6 @@ -# @ohos.app.form.formHost (FormHost) +# @ohos.app.form.formHost (formHost) -FormHost模块提供了卡片使用方相关接口的能力,包括对使用方同一用户下安装的卡片进行删除、释放、请求更新、获取卡片信息、状态等操作。 +formHost模块提供了卡片使用方相关接口的能力,包括对使用方同一用户下安装的卡片进行删除、释放、请求更新、获取卡片信息、状态等操作。 > **说明:** > @@ -34,25 +34,24 @@ deleteForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; - formHost.deleteForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.deleteForm(formId, (error) => { if (error) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost deleteForm success'); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - ``` ## deleteForm @@ -82,21 +81,21 @@ deleteForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **参数:** ```ts try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.deleteForm(formId).then(() => { console.log('formHost deleteForm success'); }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -121,21 +120,21 @@ releaseForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -161,21 +160,21 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback< | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error, data) => { + let formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error) => { if (error) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -206,21 +205,21 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.releaseForm(formId, true).then(() => { console.log('formHost releaseForm success'); }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -245,21 +244,21 @@ requestForm(formId: string, callback: AsyncCallback<void>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; - formHost.requestForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.requestForm(formId, (error) => { if (error) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -289,21 +288,21 @@ requestForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.requestForm(formId).then(() => { console.log('formHost requestForm success'); }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -323,27 +322,27 @@ castToNormalForm(formId: string, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formId | string | 是 | 卡片标识。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当将指定的临时卡片转换为普通卡片成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当将指定的临时卡片转换为普通卡片成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; - formHost.castToNormalForm(formId, (error, data) => { + let formId = "12400633174999288"; + formHost.castToNormalForm(formId, (error) => { if (error) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -373,21 +372,21 @@ castToNormalForm(formId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = "12400633174999288"; + let formId = "12400633174999288"; formHost.castToNormalForm(formId).then(() => { console.log('formHost castTempForm success'); }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -406,27 +405,27 @@ notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可见成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可见成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -456,21 +455,21 @@ notifyVisibleForms(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyVisibleForms(formId).then(() => { console.log('formHost notifyVisibleForms success'); }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -489,27 +488,27 @@ notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<vo | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。| -| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可见成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可见成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId, (error) => { if (error) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -539,21 +538,21 @@ notifyInvisibleForms(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.notifyInvisibleForms(formId).then(() => { console.log('formHost notifyInvisibleForms success'); }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -572,27 +571,27 @@ enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void& | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可以更新成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可以更新成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -622,21 +621,21 @@ enableFormsUpdate(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.enableFormsUpdate(formId).then(() => { console.log('formHost enableFormsUpdate success'); }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -655,27 +654,27 @@ disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可以更新成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可以更新成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error, data) => { + let formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId, (error) => { if (error) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -705,21 +704,21 @@ disableFormsUpdate(formIds: Array<string>): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts try { - var formId = ["12400633174999288"]; + let formId = ["12400633174999288"]; formHost.disableFormsUpdate(formId).then(() => { console.log('formHost disableFormsUpdate success'); }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -735,20 +734,19 @@ isSystemReady(callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | 是 | 回调函数。当检查系统是否准备好成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当检查系统是否准备好成功,error为undefined,否则为错误对象。 | **示例:** ```ts try { - var formId = "12400633174999288"; formHost.isSystemReady((error, data) => { if (error) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -770,14 +768,13 @@ isSystemReady(): Promise<void> ```ts try { - var formId = "12400633174999288"; formHost.isSystemReady().then(() => { console.log('formHost isSystemReady success'); }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -795,7 +792,7 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上所有应用提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上所有应用提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 | **示例:** @@ -803,13 +800,13 @@ getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): try { formHost.getAllFormsInfo((error, data) => { if (error) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -825,9 +822,9 @@ getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> **返回值:** -| 类型 | 说明 | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | +| 类型 | 说明 | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | **示例:** @@ -836,10 +833,10 @@ try { formHost.getAllFormsInfo().then((data) => { console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -858,14 +855,14 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | bundleName | string | 是 | 要查询的应用Bundle名称。 | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -873,13 +870,13 @@ getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.Fo try { formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -899,14 +896,14 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< | ------ | ------ | ---- | ------- | | bundleName | string | 是 | 要查询的应用Bundle名称。 | | moduleName | string | 是 | 要查询的模块名称。 | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -914,13 +911,13 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback< try { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { if (error) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -943,16 +940,16 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formI **返回值:** -| 类型 | 说明 | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | +| 类型 | 说明 | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象,返回查询到的卡片信息。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -961,10 +958,10 @@ try { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -983,22 +980,22 @@ deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<numb | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 有效卡片标识列表。 | -| callback | AsyncCallback<number> | 是 | 回调函数。当根据列表删除应用程序的无效卡片成功,err为undefined,data为删除的卡片个数;否则为错误对象。 | +| callback | AsyncCallback<number> | 是 | 回调函数。当根据列表删除应用程序的无效卡片成功,error为undefined,data为删除的卡片个数;否则为错误对象。 | **示例:** ```ts try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds, (error, data) => { if (error) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1028,14 +1025,14 @@ deleteInvalidForms(formIds: Array<string>): Promise<number> ```ts try { - var formIds = new Array("12400633174999288", "12400633174999289"); + let formIds = new Array("12400633174999288", "12400633174999289"); formHost.deleteInvalidForms(formIds).then((data) => { console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1053,15 +1050,15 @@ acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo&g | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。 | -| callback | AsyncCallback<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | 是 | 回调函数。当获取卡片状态成功,err为undefined,data为获取到的卡片状态;否则为错误对象。 | +| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。需要包含bundle名、ability名、module名、卡片名、卡片规格等。 | +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | 是 | 回调函数。当获取卡片状态成功,error为undefined,data为获取到的卡片状态;否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1079,13 +1076,13 @@ var want = { try { formHost.acquireFormState(want, (error, data) => { if (error) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } else { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1103,20 +1100,20 @@ acquireFormState(want: Want): Promise<formInfo.FormStateInfo> | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。 | +| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。需要包含bundle名、ability名、module名、卡片名、卡片规格等。 | **返回值:** | 类型 | 说明 | | :------------ | :---------------------------------- | -| Promise<[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise对象,返回卡片状态。 | +| Promise<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise对象,返回卡片状态。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** @@ -1135,10 +1132,10 @@ try { formHost.acquireFormState(want).then((data) => { console.log('formHost acquireFormState, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1206,27 +1203,27 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: A | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。 | | isVisible | boolean | 是 | 是否可见。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当通知卡片是否可见成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当通知卡片是否可见成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsVisible(formIds, true, (error, data) => { + formHost.notifyFormsVisible(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1257,21 +1254,21 @@ notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise< | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsVisible(formIds, true).then(() => { console.log('formHost notifyFormsVisible success'); }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1291,27 +1288,27 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, c | ------ | ------ | ---- | ------- | | formIds | Array<string> | 是 | 卡片标识列表。 | | isEnableUpdate | boolean | 是 | 是否使能更新。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当通知卡片是否启用更新状态成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当通知卡片是否启用更新状态成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array("12400633174999288", "12400633174999289"); try { - formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + formHost.notifyFormsEnableUpdate(formIds, true, (error) => { if (error) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1342,21 +1339,21 @@ notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsEnableUpdate(formIds, true).then(() => { console.log('formHost notifyFormsEnableUpdate success'); }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` ## shareForm @@ -1375,29 +1372,28 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>) | ------ | ------ | ---- | ------- | | formId | string | 是 | 卡片标识。 | | deviceId | string | 是 | 远程设备标识。 | -| callback | AsyncCallback<void> | 是 | 回调函数。当指定formId和远程设备Id进行卡片分享成功,err为undefined,否则为错误对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当指定formId和远程设备Id进行卡片分享成功,error为undefined,否则为错误对象。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 - +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formId = "12400633174999288"; +let formId = "12400633174999288"; var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { - formHost.shareForm(formId, deviceId, (error, data) => { + formHost.shareForm(formId, deviceId, (error) => { if (error) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); } }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1428,22 +1424,22 @@ shareForm(formId: string, deviceId: string): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| -**参数:** +**示例:** ```ts -var formId = "12400633174999288"; +let formId = "12400633174999288"; var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; try { formHost.shareForm(formId, deviceId).then(() => { console.log('formHost shareForm success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -1451,6 +1447,8 @@ try { notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void +通知指定卡片隐私保护状态改变。使用callback异步回调。 + **需要权限**:ohos.permission.REQUIRE_FORM **系统能力**:SystemCapability.Ability.Form @@ -1459,18 +1457,72 @@ notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callb | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| formId | string | 是 | 卡片标识。 | -| deviceId | string | 是 | 远程设备标识。 | +| formIds | Array\ | 是 | 需要修改隐私保护的卡片标识列表。 | +| isProtected | boolean | 是 | 是否进行隐私保护。 | +| callback | AsyncCallback\ | 是 | 回调函数。当指定卡片设置隐私保护属性成功,error为undefined,否则为错误对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------------------------------------------------------------ | ------------------ | +| 401 | 调用接口入参错误。 | +| 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | | + +**示例:** ```ts -var formIds = new Array("12400633174999288", "12400633174999289"); +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message})`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean): Promise\; + +通知指定卡片隐私保护状态改变。使用Promise异步回调。 + +**需要权限**:ohos.permission.REQUIRE_FORM + +**系统能力**:SystemCapability.Ability.Form + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | --------------- | ---- | -------------------------------- | +| formIds | Array\ | 是 | 需要修改隐私保护的卡片标识列表。 | +| isProtected | boolean | 是 | 是否进行隐私保护。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +| 错误码ID | 错误信息 | +| ------------------------------------------------------------ | ------------------ | +| 401 | 调用接口入参错误。 | +| 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | | + +```ts +let formIds = new Array("12400633174999288", "12400633174999289"); try { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { - console.log('formHost shareForm success'); + console.log('formHost notifyFormsPrivacyProtected success'); }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); + console.log(`error, code: ${error.code}, message: ${error.message})`); }); } catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` + diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md index 5cc2bab3d9de476e4e07cf84f351a61283f946d8..6683a8a7c43cca0f34efc979a943ff87b335897d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -1,6 +1,6 @@ -# @ohos.app.form.formInfo (FormInfo) +# @ohos.app.form.formInfo (formInfo) -FormInfo模块提供对卡片的相关卡片信息和状态进行设置和查询的能力。 +formInfo模块提供了卡片信息和状态等相关类型和枚举。 > **说明:** > @@ -30,11 +30,11 @@ import formInfo from '@ohos.app.form.formInfo'; | colorMode | [ColorMode](#colormode) | 是 | 否 | 卡片颜色模式。 | | isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 | | updateEnabled | boolean | 是 | 否 | 卡片是否使能更新。 | -| formVisibleNotify | string | 是 | 否 | 卡片是否使能可见通知。 | +| formVisibleNotify | boolean | 是 | 否 | 卡片是否使能可见通知。 | | relatedBundleName | string | 是 | 否 | 卡片所属的相关联Bundle名称。 | | scheduledUpdateTime | string | 是 | 否 | 卡片更新时间。 | | formConfigAbility | string | 是 | 否 | 卡片配置ability。指定长按卡片弹出的选择框内,编辑选项所对应的ability。 | -| updateDuration | string | 是 | 否 | 卡片更新周期。 | +| updateDuration | number | 是 | 否 | 卡片更新周期。 | | defaultDimension | number | 是 | 否 | 表示卡片规格 | | supportDimensions | Array<number> | 是 | 否 | 卡片支持的规格。具体可选规格参考[FormDimension](#formdimension) | | customizeData | {[key: string]: [value: string]} | 是 | 否 | 卡片用户数据。 | @@ -100,8 +100,8 @@ import formInfo from '@ohos.app.form.formInfo'; | WIDTH_KEY | "ohos.extra.param.key.form_width" | 卡片宽度。 | | HEIGHT_KEY | "ohos.extra.param.key.form_height" | 卡片高度。 | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | 临时卡片。 | -| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称 | -| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。
**系统接口**: 此接口为系统接口。 | +| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称。 | +| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。 | | BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | 指示指定要获取的捆绑Bundle名称的键。 | ## FormDimension @@ -127,7 +127,7 @@ import formInfo from '@ohos.app.form.formInfo'; | 名称 | 说明 | | ----------- | ------------ | -| moduleName | 仅保留moduleName与提供值相符的卡片信息。 | +| moduleName | 选填。仅保留moduleName与提供值相符的卡片信息。未填写时则不通过moduleName进行过滤。 | ## VisibilityType diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md index 04ccf2a32fbba0447f651c3129d3835857f60a8c..5d227bbcaa4439be09bf9895c330f0cd5975d4ca 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md +++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -1,6 +1,6 @@ -# @ohos.app.form.formProvider (FormProvider) +# @ohos.app.form.formProvider (formProvider) -FormProvider模块提供了卡片提供方相关接口的能力,开发者在开发卡片时,可通过该模块提供接口实现更新卡片,设置卡片更新时间,获取卡片信息,请求发布卡片等。 +FormProvider模块提供了卡片提供方相关接口的能力,开发者在开发卡片时,可通过该模块提供接口实现更新卡片、设置卡片更新时间、获取卡片信息、请求发布卡片等。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -31,23 +31,25 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { if (error) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider setFormNextRefreshTime success`); } }); } catch (error) { - console.log("error" + JSON.stringify(error)) + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -76,21 +78,23 @@ setFormNextRefreshTime(formId: string, minute: number): Promise<void> | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log(`formProvider setFormNextRefreshTime success`); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -114,25 +118,27 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; try { let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj, (error, data) => { if (error) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log(`formProvider updateForm success`); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -161,23 +167,25 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts import formBindingData from '@ohos.application.formBindingData'; -var formId = "12400633174999288"; -let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); try { formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log(`formProvider updateForm success`); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -193,29 +201,31 @@ getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): voi | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到的卡片信息。 | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到的卡片信息。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.getFormsInfo((error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` ## getFormsInfo @@ -231,33 +241,35 @@ getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array&l | 参数名 | 类型 | 必填 | 说明 | | ------ | ------ | ---- | ------- | | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | 是 | 卡片信息过滤器。 | -| callback | AsyncCallback<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到符合条件的卡片信息。 | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | 是 | 回调函数。返回查询到符合条件的卡片信息。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter, (error, data) => { if (error) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); } }); -} catch(error) { - console.log(`catch err->${JSON.stringify(error)}`); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -279,31 +291,33 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.For | 类型 | 说明 | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象。返回查询到符合条件的卡片信息。 | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise对象。返回查询到符合条件的卡片信息。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -import formInfo from '@ohos.application.formInfo'; -const filter : formInfo.FormInfoFilter = { - // get info of forms belong to module entry. - moduleName : "entry" +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" }; try { formProvider.getFormsInfo(filter).then((data) => { console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -322,21 +336,23 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, | 参数名 | 类型 | 必填 | 说明 | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。
abilityName: 目标卡片ability
parameters:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | 是 | 创建卡片的数据。 | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | 是 | 创建卡片的数据。 | | callback | AsyncCallback<string> | 是 | 回调函数。返回卡片标识。 | **错误码:** | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts import formBindingData from '@ohos.application.formBindingData'; -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -345,16 +361,16 @@ var want = { } }; try { - let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); formProvider.requestPublishForm(want, obj, (error, data) => { if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -379,13 +395,15 @@ requestPublishForm(want: Want, callback: AsyncCallback<string>): void | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -396,15 +414,14 @@ var want = { try { formProvider.requestPublishForm(want, (error, data) => { if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`callback error, code: ${error.code}, message: ${error.message})`); } else { console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); } }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - ``` ## requestPublishForm @@ -422,7 +439,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData | 参数名 | 类型 | 必填 | 说明 | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。
abilityName: 目标卡片ability
parameters:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | 否 | 创建卡片的数据。 | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | 否 | 创建卡片的数据。 | **返回值:** @@ -434,13 +451,15 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData | 错误码ID | 错误信息 | | -------- | -------- | -| 401 | If the input parameter is not valid parameter. | -以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 +| 401 | 调用接口入参错误。 | +|以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。|| **示例:** ```ts -var want = { +import formProvider from '@ohos.app.form.formProvider'; + +let want = { abilityName: "FormAbility", parameters: { "ohos.extra.param.key.form_dimension": 2, @@ -452,10 +471,10 @@ try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -478,37 +497,38 @@ isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void **示例:** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported((error, isSupported) => { - if (error) { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); - } else { - if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } - }; - try { - formProvider.requestPublishForm(want, (error, data) => { - if (error) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" } - }); - } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + }; + try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); + } catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); + } } - } - } -}); + }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` @@ -531,32 +551,33 @@ isRequestPublishFormSupported(): Promise<boolean> **示例:** ```ts +import formProvider from '@ohos.app.form.formProvider'; + try { formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; try { formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } - } }).catch((error) => { - console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); + console.log(`promise error, code: ${error.code}, message: ${error.message})`); }); } catch (error) { - console.log(`catch err->${JSON.stringify(error)}`); + console.log(`catch error, code: ${error.code}, message: ${error.message})`); } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-buffer.md b/zh-cn/application-dev/reference/apis/js-apis-buffer.md index 33f6d16e90e4a44034281d7d598a96fa9e1a458b..3395c225e3a01019355c7a1680387e189886ba9d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-buffer.md +++ b/zh-cn/application-dev/reference/apis/js-apis-buffer.md @@ -1,11 +1,12 @@ # @ohos.buffer (Buffer) -> **说明:** -> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +Buffer对象用于表示固定长度的字节序列,是专门存放二进制数据的缓存区。 -Buffer对象用于表示固定长度的字节序列,是专门存放二进制数据的缓存区。 +**推荐使用场景:** 可用于处理大量二进制数据,图片处理、文件接收上传等。 -**推荐使用场景:** 可用于处理大量二进制数据,处理图片、文件接收上传等等 +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -21,29 +22,27 @@ import buffer from '@ohos.buffer'; | 编码格式 | 说明 | | ------- | -------------------- | -| ascii | 表示ascii格式。 | -| utf8 | 表示utf8格式。 | -| utf-8 | 表示utf8格式。 | -| utf16le | 表示utf16小端序格式。 | -| ucs2 | 表示utf16小端序格式。 | -| ucs-2 | 表示utf16小端序格式。 | -| base64 | 表示base64格式。 | -| base64url | 表示base64格式。 | -| latin1 | 表示ascii格式。 | -| binary | 表示二进制格式。 | -| hex | 表示十六进制格式。 | - -## Buffer +| 'ascii' | 表示ascii格式,不区分大小写。 | +| 'utf8' | 表示utf8格式,不区分大小写。 | +| 'utf-8' | 表示utf8格式,不区分大小写。 | +| 'utf16le' | 表示utf16小端序格式,不区分大小写。 | +| 'ucs2' | 表示utf16小端序格式,不区分大小写。 | +| 'ucs-2' | 表示utf16小端序格式,不区分大小写。 | +| 'base64' | 表示base64格式,不区分大小写。 | +| 'base64url' | 表示base64格式,不区分大小写。 | +| 'latin1' | 表示ascii格式,不区分大小写。 | +| 'binary' | 表示二进制格式,不区分大小写。 | +| 'hex' | 表示十六进制格式,不区分大小写。 | -### 属性 +## 属性 **系统能力:** SystemCapability.Utils.Lang | 名称 | 类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | -| length | number | 是 | 否 | buffer的字节长度。 | +| length | number | 是 | 否 | Buffer对象的字节长度。 | | buffer | ArrayBuffer | 是 | 否 | ArrayBuffer对象。 | -| byteOffset | number | 是 | 否 | 当前buffer所在内存池的偏移量。 | +| byteOffset | number | 是 | 否 | 当前Buffer所在内存池的偏移量。 | **错误码:** @@ -65,11 +64,11 @@ console.log(JSON.stringify(new Uint8Array(arrayBuffer))); console.log(JSON.stringify(buf.byteOffset)); ``` -### alloc +## buffer.alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer -创建`size`个字节长度的Buffer实例,并初始化。 +创建一定字节长度的Buffer对象,并初始化。 **系统能力:** SystemCapability.Utils.Lang @@ -77,15 +76,15 @@ alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| size | number | 是 | 指定的Buffer实例长度,单位:字节。 | -| fill | string \| Buffer \| number | 否 | 预填充的值,默认值: 0 | -| encoding | [BufferEncoding](#bufferencoding) | 否 | 编码方式(当`fill`为string时,才有意义)。 默认值: 'utf-8' | +| size | number | 是 | 指定的Buffer对象长度,单位:字节。 | +| fill | string \| Buffer \| number | 否 | 填充至新缓存区的值,默认值: 0。 | +| encoding | [BufferEncoding](#bufferencoding) | 否 | 编码格式(当`fill`为string时,才有意义)。 默认值: 'utf-8'。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 带初始化的Buffer实例。 | +| Buffer | 返回一个Buffer对象。 | **示例:** @@ -97,12 +96,12 @@ let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ``` -### allocUninitializedFromPool +## buffer.allocUninitializedFromPool allocUninitializedFromPool(size: number): Buffer -创建指定大小的未被初始化Buffer实例。内存从缓冲池分配。 -创建的Buffer的内容未知,需要使用fill()函数来初始化Buffer实例。 +创建指定大小未被初始化的Buffer对象。内存从缓冲池分配。 +创建的Buffer的内容未知,需要使用[buffer.fill](#bufferfill)函数来初始化Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -110,7 +109,7 @@ allocUninitializedFromPool(size: number): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| size | number | 是 | 指定的Buffer实例长度,单位:字节。 | +| size | number | 是 | 指定的Buffer对象长度,单位:字节。 | **返回值:** @@ -127,11 +126,12 @@ let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); ``` -### allocUninitialized +## buffer.allocUninitialized allocUninitialized(size: number): Buffer -创建指定大小的未被初始化Buffer实例。内存不从缓冲池分配。 +创建指定大小未被初始化的Buffer实例。内存不从缓冲池分配。 +创建的Buffer的内容未知,需要使用[buffer.fill](#bufferfill)函数来初始化Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -139,7 +139,7 @@ allocUninitialized(size: number): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| size | number | 是 |指定的Buffer实例长度,单位:字节。 | +| size | number | 是 |指定的Buffer对象长度,单位:字节。 | **返回值:** @@ -156,11 +156,11 @@ let buf = buffer.allocUninitialized(10); buf.fill(0); ``` -### byteLength +## buffer.byteLength byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number -根据不同的编码方法,返回字符串的字节数。 +根据不同的编码方法,返回指定字符串的字节数。 **系统能力:** SystemCapability.Utils.Lang @@ -169,13 +169,13 @@ byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | Share | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | 是 | 指定字符串。 | -| encoding | [BufferEncoding](#bufferencoding) | 否 | 编码方式。 默认值: 'utf-8' | +| encoding | [BufferEncoding](#bufferencoding) | 否 | 编码格式。 默认值: 'utf-8'。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| number | 返回字符串的字节数 | +| number | 返回指定字符串的字节数。 | **示例:** @@ -187,11 +187,11 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8') // 打印: ½ + ¼ = ¾: 9 characters, 12 bytes ``` -### compare +## buffer.compare compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 -返回比较buf1和buf2的结果, 通常用于对Buffer实例的数组进行排序。 +返回两个数组的比较结果,通常用于对Buffer对象数组进行排序。 **系统能力:** SystemCapability.Utils.Lang @@ -207,7 +207,7 @@ compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 | 类型 | 说明 | | -------- | -------- | -| -1 \| 0 \| 1 | 如果buf1与buf2相同,则返回0
如果排序时buf1位于buf2之后,则返回1
如果排序时buf1位于buf2之前,则返回-1。 | +| -1 \| 0 \| 1 | 如果buf1与buf2相同,则返回0。
如果排序时buf1位于buf2之后,则返回1。
如果排序时buf1位于buf2之前,则返回-1。 | **示例:** @@ -221,11 +221,11 @@ let res = buf1.compare(buf2); console.log(Number(res).toString()); // 打印 1 ``` -### concat +## buffer.concat concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer -将`list`中的实例内容复制`totalLength`字节长度到新的Buffer实例中并返回。 +将数组中的内容复制指定字节长度到新的Buffer对象中并返回。 **系统能力:** SystemCapability.Utils.Lang @@ -234,13 +234,13 @@ concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | 是 | 实例数组。 | -| totalLength | number | 否 | 需要融合的总字节长度。 | +| totalLength | number | 否 | 需要复制的总字节长度。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 返回新Buffer的实例。 | +| Buffer | 返回新的Buffer对象。 | **错误码:** @@ -261,11 +261,11 @@ let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 ``` -### from +## buffer.from from(array: number[]): Buffer; -根据指定数组创建新的Buffer实例。 +根据指定数组创建新的Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -279,7 +279,7 @@ from(array: number[]): Buffer; | 类型 | 说明 | | -------- | -------- | -| Buffer | 新的Buffer实例。 | +| Buffer | 新的Buffer对象。 | **示例:** @@ -290,11 +290,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 ``` -### from +## buffer.from from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer -创建指定长度的与`arrayBuffer`共享内存的Buffer实例 +创建指定长度的与`arrayBuffer`共享内存的Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -304,13 +304,13 @@ from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: | -------- | -------- | -------- | -------- | | arrayBuffer | ArrayBuffer \| SharedArrayBuffer | 是 | 实例对象。 | | byteOffset | number | 否 | 字节偏移量,默认值: 0。 | -| length | number | 否 | 字节长度, 默认值: arrayBuffer.byteLength - byteOffset。 | +| length | number | 否 | 字节长度, 默认值: (arrayBuffer.byteLength - byteOffset)。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 返回一个共享内存的Buffer实例。 | +| Buffer | 返回一个共享内存的Buffer对象。 | **错误码:** @@ -329,11 +329,11 @@ let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); ``` -### from +## buffer.from from(buffer: Buffer | Uint8Array): Buffer -创建并复制`buffer`数据到新的Buffer实例并返回。 +创建并复制`buffer`数据到新的Buffer对象并返回。 **系统能力:** SystemCapability.Utils.Lang @@ -341,13 +341,13 @@ from(buffer: Buffer | Uint8Array): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| buffer | Buffer \| Uint8Array | 是 | 实例数据。 | +| buffer | Buffer \| Uint8Array | 是 | 对象数据。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 新的Buffer实例。 | +| Buffer | 新的Buffer对象。 | **示例:** @@ -358,11 +358,11 @@ let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); ``` -### from +## buffer.from from(object: Object, offsetOrEncoding: number | string, length: number): Buffer -根据指定的`object`类型数据,创建新的Buffer实例。 +根据指定的`object`类型数据,创建新的Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -370,29 +370,29 @@ from(object: Object, offsetOrEncoding: number | string, length: number): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| object | Object | 是 | 支持Symbol.toPrimitive或valueOf()的对象 | -| offsetOrEncoding | number \| string | 是 | 字节偏移量或编码。 | +| object | Object | 是 | 支持Symbol.toPrimitive或valueOf()的对象。 | +| offsetOrEncoding | number \| string | 是 | 字节偏移量或编码格式。 | | length | number | 是 | 字节长度。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 新的Buffer实例。 | +| Buffer | 返回新的Buffer对象。 | **示例:** ```ts import buffer from '@ohos.buffer'; -let buf = buffer.from(new String('this is a test')); +let buf = buffer.from(new String('this is a test'), 'utf8', 14); ``` -### from +## buffer.from from(string: String, encoding?: BufferEncoding): Buffer -根据指定编码格式的字符串,创建新的Buffer实例。 +根据指定编码格式的字符串,创建新的Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -407,7 +407,7 @@ from(string: String, encoding?: BufferEncoding): Buffer | 类型 | 说明 | | -------- | -------- | -| Buffer | 新的Buffer实例。 | +| Buffer | 返回新的Buffer对象。 | **示例:** @@ -422,7 +422,7 @@ console.log(buf2.toString()); ``` -### isBuffer +## buffer.isBuffer isBuffer(obj: Object): boolean @@ -454,7 +454,7 @@ buffer.isBuffer([]); // false buffer.isBuffer(new Uint8Array(1024)); // false ``` -### isEncoding +## buffer.isEncoding isEncoding(encoding: string): boolean @@ -472,7 +472,7 @@ isEncoding(encoding: string): boolean | 类型 | 说明 | | -------- | -------- | -| boolean | true或者false。 | +| boolean | 是支持的编码格式返回true,反之则返回false。 | **示例:** @@ -485,11 +485,11 @@ console.log(buffer.isEncoding('utf/8').toString()); // 打印: false console.log(buffer.isEncoding('').toString()); // 打印: false ``` -### compare +## buffer.compare compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 -`this`实例对象与`target`实例对象进行比较,返回buf在排序中的顺序,-1:前排序,0:与buf相同,1:后排序。 +当前Buffer对象与目标Buffer对象进行比较,并返回Buffer在排序中的顺序结果。 **系统能力:** SystemCapability.Utils.Lang @@ -499,15 +499,15 @@ compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, s | -------- | -------- | -------- | -------- | | target | Buffer \| Uint8Array | 是 | 要比较的实例对象。 | | targetStart | number | 否 | `target`实例中开始的偏移量。 默认值: 0。 | -| targetEnd | number | 否 | `target`实例中结束的偏移量(不包括本身)。 默认值: target.length。 | +| targetEnd | number | 否 | `target`实例中结束的偏移量(不包含结束位置)。 默认值: 目标对象的字节长度。 | | sourceStart | number | 否 | `this`实例中开始的偏移量。 默认值: 0。 | -| sourceEnd | number | 否 | `this`实例中结束的偏移量(不包括本身)。 默认值: buf.length。 | +| sourceEnd | number | 否 | `this`实例中结束的偏移量(不包含结束位置)。 默认值: 当前对象的字节长度。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| number | 比较结果。-1:前排序,0:与buf相同,1:后排序。 | +| number | 返回比较结果。-1:当前排列在目标前,0:当前与目标相同,1:当前排列在目标后。 | **错误码:** @@ -530,7 +530,7 @@ console.log(buf1.compare(buf2, 0, 6, 4).toString()); // 打印: -1 console.log(buf1.compare(buf2, 5, 6, 5).toString()); // 打印: 1 ``` -### copy +## buffer.copy copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number @@ -545,7 +545,7 @@ copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sou | target | Buffer \| Uint8Array | 是 | 要复制到的Buffer或Uint8Array实例。 | | targetStart | number | 否 | `target`实例中开始写入的偏移量。 默认值: 0。 | | sourceStart | number | 否 | `this`实例中开始复制的偏移量。 默认值: 0。 | -| sourceEnd | number | 否 | `this`实例中结束复制的偏移量(不包括)。 默认值: buf.length。 | +| sourceEnd | number | 否 | `this`实例中结束复制的偏移量(不包含结束位置)。 默认值: 当前对象的字节长度。 | **返回值:** @@ -578,7 +578,7 @@ console.log(buf2.toString('ascii', 0, 25)); // 打印: !!!!!!!!qrst!!!!!!!!!!!!! ``` -### entries +## buffer.entries entries(): IterableIterator<[number, number]> @@ -586,6 +586,13 @@ entries(): IterableIterator<[number, number]> **系统能力:** SystemCapability.Utils.Lang +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 表示迭代器的key值。 | +| number | 表示迭代器的value值。 | + **示例:** ```ts @@ -597,7 +604,7 @@ for (let pair of buf.entries()) { } ``` -### equals +## buffer.equals equals(otherBuffer: Uint8Array | Buffer): boolean @@ -630,11 +637,11 @@ console.log(buf1.equals(buf2).toString()); // 打印: true console.log(buf1.equals(buf3).toString()); // 打印: false ``` -### fill +## buffer.fill fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): Buffer -用`value`填充`this`实例指定位置的数据,默认为循环填充,并返回填充后的Buffer实例。 +用`value`填充当前对象指定位置的数据,默认为循环填充,并返回填充后的Buffer对象。 **系统能力:** SystemCapability.Utils.Lang @@ -644,14 +651,14 @@ fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number | -------- | -------- | -------- | -------- | | value | string \| Buffer \| Uint8Array \| number | 是 | 用于填充的值。 | | offset | number | 否 | 起始偏移量。 默认值: 0。 | -| end | number | 否 | 结束偏移量(不包括在内)。 默认值: buf.length。 | +| end | number | 否 | 结束偏移量(不包含结束位置)。 默认值: 当前对象的字节长度。 | | encoding | [BufferEncoding](#bufferencoding) | 否 | 字符编码格式(`value`为string才有意义)。 默认值: 'utf-8'。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 填充后的Buffer实例。 | +| Buffer | 返回一个填充后的Buffer对象。 | **错误码:** @@ -671,7 +678,7 @@ console.log(b.toString()); ``` -### includes +## buffer.includes includes(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): boolean @@ -703,11 +710,11 @@ console.log(buf.includes('this').toString()); // 打印: true console.log(buf.includes('be').toString()); // 打印: false ``` -### indexOf +## buffer.indexOf indexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number -查找`this`实例中第一次出现`value`的索引,如果不包含`value`,则为-1 +查找当前对象中第一次出现`value`的索引,如果不包含`value`,则为-1。 **系统能力:** SystemCapability.Utils.Lang @@ -715,7 +722,7 @@ indexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encod | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | string \| number \| Buffer \| Uint8Array | 是 | 要搜索的内容。 | +| value | string \| number \| Buffer \| Uint8Array | 是 | 要查找的内容。 | | byteOffset | number | 否 | 字节偏移量。 如果为负数,则从末尾开始计算偏移量。 默认值: 0。 | | encoding | [BufferEncoding](#bufferencoding) | 否 | 字符编码格式。 默认值: 'utf-8'。 | @@ -735,11 +742,11 @@ console.log(buf.indexOf('this').toString()); // 打印: 0 console.log(buf.indexOf('is').toString()); // 打印: 2 ``` -### keys +## buffer.keys keys(): IterableIterator<number> -返回一个包含key值的迭代器 +返回一个包含key值的迭代器。 **系统能力:** SystemCapability.Utils.Lang @@ -747,7 +754,7 @@ keys(): IterableIterator<number> | 类型 | 说明 | | -------- | -------- | -| IterableIterator<number> | 迭代器。 | +| IterableIterator<number> | 返回一个包含key值的迭代器。 | **示例:** @@ -760,7 +767,7 @@ for (const key of buf.keys()) { } ``` -### lastIndexOf +## buffer.lastIndexOf lastIndexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number @@ -793,7 +800,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // 打印: 17 ``` -### readBigInt64BE +## buffer.readBigInt64BE readBigInt64BE(offset?: number): bigint @@ -834,7 +841,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeBigInt64BE(0x0102030405060708n, 0); ``` -### readBigInt64LE +## buffer.readBigInt64LE readBigInt64LE(offset?: number): bigint @@ -875,7 +882,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeBigInt64BE(0x0102030405060708n, 0); ``` -### readBigUInt64BE +## buffer.readBigUInt64BE readBigUInt64BE(offset?: number): bigint @@ -916,7 +923,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); ``` -### readBigUInt64LE +## buffer.readBigUInt64LE readBigUInt64LE(offset?: number): bigint @@ -957,7 +964,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); ``` -### readDoubleBE +## buffer.readDoubleBE readDoubleBE(offset?: number): number @@ -997,7 +1004,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeDoubleBE(123.456, 0); ``` -### readDoubleLE +## buffer.readDoubleLE readDoubleLE(offset?: number): number @@ -1037,7 +1044,7 @@ let buf1 = buffer.allocUninitializedFromPool(8); buf1.writeDoubleLE(123.456, 0); ``` -### readFloatBE +## buffer.readFloatBE readFloatBE(offset?: number): number @@ -1077,7 +1084,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeFloatBE(0xcabcbcbc, 0); ``` -### readFloatLE +## buffer.readFloatLE readFloatLE(offset?: number): number @@ -1117,7 +1124,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeFloatLE(0xcabcbcbc, 0); ``` -### readInt8 +## buffer.readInt8 readInt8(offset?: number): number @@ -1158,7 +1165,7 @@ let buf1 = buffer.allocUninitializedFromPool(2); buf1.writeInt8(0x12); ``` -### readInt16BE +## buffer.readInt16BE readInt16BE(offset?: number): number @@ -1198,11 +1205,11 @@ let buf1 = buffer.alloc(2); buf1.writeInt16BE(0x1234, 0); ``` -### readInt16LE +## buffer.readInt16LE readInt16LE(offset?: number): number -从指定的`offset`处读取有符号的小端序16位整数 +从指定的`offset`处读取有符号的小端序16位整数。 **系统能力:** SystemCapability.Utils.Lang @@ -1238,11 +1245,11 @@ let buf1 = buffer.alloc(2); buf1.writeInt16BE(0x1234, 0); ``` -### readInt32BE +## buffer.readInt32BE readInt32BE(offset?: number): number -从指定的`offset`处读取有符号的大端序32位整数 +从指定的`offset`处读取有符号的大端序32位整数。 **系统能力:** SystemCapability.Utils.Lang @@ -1278,11 +1285,11 @@ let buf1 = buffer.alloc(4); buf1.writeInt32BE(0x12345678, 0); ``` -### readInt32LE +## buffer.readInt32LE readInt32LE(offset?: number): number -从指定的`offset`处读取有符号的小端序32位整数 +从指定的`offset`处读取有符号的小端序32位整数。 **系统能力:** SystemCapability.Utils.Lang @@ -1318,7 +1325,7 @@ let buf1 = buffer.alloc(4); buf1.writeInt32BE(0x12345678, 0); ``` -### readIntBE +## buffer.readIntBE readIntBE(offset: number, byteLength: number): number @@ -1362,7 +1369,7 @@ buf1.writeIntBE(0x123456789011, 0, 6); ``` -### readIntLE +## buffer.readIntLE readIntLE(offset: number, byteLength: number): number @@ -1404,7 +1411,7 @@ let buf1 = buffer.allocUninitializedFromPool(6); buf1.writeIntLE(0x123456789011, 0, 6); ``` -### readUInt8 +## buffer.readUInt8 readUInt8(offset?: number): number @@ -1446,7 +1453,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUInt8(0x42); ``` -### readUInt16BE +## buffer.readUInt16BE readUInt16BE(offset?: number): number @@ -1488,7 +1495,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUInt16BE(0x1234, 0); ``` -### readUInt16LE +## buffer.readUInt16LE readUInt16LE(offset?: number): number @@ -1530,7 +1537,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUInt16LE(0x1234, 0); ``` -### readUInt32BE +## buffer.readUInt32BE readUInt32BE(offset?: number): number @@ -1571,7 +1578,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUInt32BE(0x12345678, 0); ``` -### readUInt32LE +## buffer.readUInt32LE readUInt32LE(offset?: number): number @@ -1612,7 +1619,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUInt32LE(0x12345678, 0); ``` -### readUIntBE +## buffer.readUIntBE readUIntBE(offset: number, byteLength: number): number @@ -1654,7 +1661,7 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUIntBE(0x13141516, 0, 4); ``` -### readUIntLE +## buffer.readUIntLE readUIntLE(offset: number, byteLength: number): number @@ -1696,11 +1703,11 @@ let buf1 = buffer.allocUninitializedFromPool(4); buf1.writeUIntLE(0x13141516, 0, 4); ``` -### subarray +## buffer.subarray subarray(start?: number, end?: number): Buffer -截取指定位置的`this`实例并返回。 +截取当前对象指定位置的数据并返回。 **系统能力:** SystemCapability.Utils.Lang @@ -1709,13 +1716,13 @@ subarray(start?: number, end?: number): Buffer | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | start | number | 否 | 截取开始位置。 默认值: 0。 | -| end | number | 否 | 截取结束位置(不包括在内)。 默认值: buf.length。 | +| end | number | 否 | 截取结束位置(不包含结束位置)。 默认值: 当前对象的字节长度。 | **返回值:** | 类型 | 说明 | | -------- | -------- | -| Buffer | 新的Buffer实例。 | +| Buffer | 返回新的Buffer对象。 | **示例:** @@ -1732,11 +1739,11 @@ console.log(buf2.toString('ascii', 0, buf2.length)); // 打印: abc ``` -### swap16 +## buffer.swap16 swap16(): Buffer -将`this`实例解释为无符号的16位整数数组,并就地交换字节顺序。 +将当前对象解释为无符号的16位整数数组,并交换字节顺序。 **系统能力:** SystemCapability.Utils.Lang @@ -1767,11 +1774,11 @@ buf1.swap16(); console.log(buf1.toString('hex')); // 打印: 0201040306050807 ``` -### swap32 +## buffer.swap32 swap32(): Buffer -将`this`实例解释为无符号的32位整数数组,并就地交换字节顺序 +将当前对象解释为无符号的32位整数数组,并交换字节顺序。 **系统能力:** SystemCapability.Utils.Lang @@ -1780,7 +1787,7 @@ swap32(): Buffer | 类型 | 说明 | | -------- | -------- | -| Buffer | 交换之后的Buffer实例。 | +| Buffer | 交换之后的Buffer对象。 | **错误码:** @@ -1802,11 +1809,11 @@ buf1.swap32(); console.log(buf1.toString('hex')); // 打印: 0403020108070605 ``` -### swap64 +## buffer.swap64 swap64(): Buffer -将`this`实例解释为无符号的64位整数数组,并就地交换字节顺序 +将当前对象解释为无符号的64位整数数组,并交换字节顺序。 **系统能力:** SystemCapability.Utils.Lang @@ -1815,7 +1822,7 @@ swap64(): Buffer | 类型 | 说明 | | -------- | -------- | -| Buffer | 交换之后的Buffer实例。 | +| Buffer | 交换之后的Buffer对象。 | **错误码:** @@ -1836,11 +1843,11 @@ buf1.swap64(); console.log(buf1.toString('hex')); // 打印: 0807060504030201 ``` -### toJSON +## buffer.toJSON toJSON(): Object -将buf转为JSON并返回。 +将Buffer转为JSON并返回。 **系统能力:** SystemCapability.Utils.Lang @@ -1862,11 +1869,11 @@ console.log(JSON.stringify(obj)) // 打印: {"type":"Buffer","data":[1,2,3,4,5]} ``` -### toString +## buffer.toString toString(encoding?: string, start?: number, end?: number): string -将`this`实例中指定位置数据转成指定编码格式字符串并返回。 +将当前对象中指定位置数据转成指定编码格式字符串并返回。 **系统能力:** SystemCapability.Utils.Lang @@ -1876,7 +1883,7 @@ toString(encoding?: string, start?: number, end?: number): string | -------- | -------- | -------- | -------- | | encoding | string | 否 | 字符编码格式。 默认值: 'utf-8'。 | | start | number | 否 | 开始位置。 默认值: 0。 | -| end | number | 否 | 结束位置。 默认值: buf.length。 | +| end | number | 否 | 结束位置。 默认值: Buffer.length。 | **返回值:** @@ -1897,7 +1904,7 @@ console.log(buf1.toString('utf-8')); // 打印: abcdefghijklmnopqrstuvwxyz ``` -### values +## buffer.values values(): IterableIterator<number> @@ -1922,11 +1929,11 @@ for (let value of buf1.values()) { } ``` -### write +## buffer.write write(str: string, offset?: number, length?: number, encoding?: string): number -从buf的offset偏移写入指定编码的字符串str,写入的字节长度为length +从Buffer对象的offset偏移写入指定编码的字符串str,写入的字节长度为length。 **系统能力:** SystemCapability.Utils.Lang @@ -1936,7 +1943,7 @@ write(str: string, offset?: number, length?: number, encoding?: string): number | -------- | -------- | -------- | -------- | | str | string | 是 | 要写入Buffer的字符串。 | | offset | number | 否 | 偏移量。 默认值: 0。 | -| length | number | 否 | 最大字节长度。 默认值: (buf.length - offset)。| +| length | number | 否 | 最大字节长度。 默认值: (Buffer.length - offset)。| | encoding | string | 否 | 字符编码。 默认值: 'utf-8'。 | @@ -1968,11 +1975,11 @@ let buffer1 = buffer.alloc(10); let length = buffer1.write('abcd', 8); ``` -### writeBigInt64BE +## buffer.writeBigInt64BE writeBigInt64BE(value: bigint, offset?: number): number -从buf的offset偏移写入有符号的大端序64位BigInt型数据value +从Buffer对象的offset偏移写入有符号的大端序64位BigInt型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -1980,7 +1987,7 @@ writeBigInt64BE(value: bigint, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | bigint | 是 | 写入 buf 的数字。 | +| value | bigint | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2007,11 +2014,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeBigInt64BE(0x0102030405060708n, 0); ``` -### writeBigInt64LE +## buffer.writeBigInt64LE writeBigInt64LE(value: bigint, offset?: number): number -从buf的offset偏移写入有符号的小端序64位BigInt型数据value +从Buffer对象的offset偏移写入有符号的小端序64位BigInt型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2019,7 +2026,7 @@ writeBigInt64LE(value: bigint, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | bigint | 是 | 写入 buf 的数字。 | +| value | bigint | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2046,11 +2053,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeBigInt64LE(0x0102030405060708n, 0); ``` -### writeBigUInt64BE +## buffer.writeBigUInt64BE writeBigUInt64BE(value: bigint, offset?: number): number -从buf的offset偏移写入无符号的大端序64位BigUInt型数据value +从Buffer对象的offset偏移写入无符号的大端序64位BigUInt型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2058,7 +2065,7 @@ writeBigUInt64BE(value: bigint, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | bigint | 是 | 写入 buf 的数字。 | +| value | bigint | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2085,11 +2092,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeBigUInt64BE(0xdecafafecacefaden, 0); ``` -### writeBigUInt64LE +## buffer.writeBigUInt64LE writeBigUInt64LE(value: bigint, offset?: number): number -从buf的offset偏移写入无符号的小端序64位BigUInt型数据value +从Buffer对象的offset偏移写入无符号的小端序64位BigUInt型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2097,7 +2104,7 @@ writeBigUInt64LE(value: bigint, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | bigint | 是 | 写入 buf 的数字。 | +| value | bigint | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2124,11 +2131,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeBigUInt64LE(0xdecafafecacefaden, 0); ``` -### writeDoubleBE +## buffer.writeDoubleBE writeDoubleBE(value: number, offset?: number): number -从buf的offset偏移写入大端序的64位双浮点型数据value +从Buffer对象的offset偏移写入大端序的64位双浮点型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2136,7 +2143,7 @@ writeDoubleBE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2163,11 +2170,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeDoubleBE(123.456, 0); ``` -### writeDoubleLE +## buffer.writeDoubleLE writeDoubleLE(value: number, offset?: number): number -从buf的offset偏移写入小端序的64位双浮点型数据value +从Buffer对象的offset偏移写入小端序的64位双浮点型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2175,7 +2182,7 @@ writeDoubleLE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2202,11 +2209,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeDoubleLE(123.456, 0); ``` -### writeFloatBE +## buffer.writeFloatBE writeFloatBE(value: number, offset?: number): number -从buf的offset偏移写入大端序的32位浮点型数据value +从Buffer对象的offset偏移写入大端序的32位浮点型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2214,7 +2221,7 @@ writeFloatBE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2242,11 +2249,11 @@ buf.writeFloatBE(0xcafebabe, 0); ``` -### writeFloatLE +## buffer.writeFloatLE writeFloatLE(value: number, offset?: number): number -从buf的offset偏移写入小端序的32位浮点型数据value +从Buffer对象的offset偏移写入小端序的32位浮点型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2254,7 +2261,7 @@ writeFloatLE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2281,11 +2288,11 @@ let buf = buffer.allocUninitializedFromPool(8); buf.writeFloatLE(0xcafebabe, 0); ``` -### writeInt8 +## buffer.writeInt8 writeInt8(value: number, offset?: number): number -从buf的offset偏移写入8位有符号整型数据value +从Buffer对象的offset偏移写入8位有符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2293,7 +2300,7 @@ writeInt8(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2322,11 +2329,11 @@ buf.writeInt8(-2, 1); ``` -### writeInt16BE +## buffer.writeInt16BE writeInt16BE(value: number, offset?: number): number -从buf的offset偏移写入大端序的16位有符号整型数据value +从Buffer对象的offset偏移写入大端序的16位有符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2334,7 +2341,7 @@ writeInt16BE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2362,11 +2369,11 @@ buf.writeInt16BE(0x0102, 0); ``` -### writeInt16LE +## buffer.writeInt16LE writeInt16LE(value: number, offset?: number): number -从buf的offset偏移写入小端序的16位有符号整型数据value +从Buffer对象的offset偏移写入小端序的16位有符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2374,7 +2381,7 @@ writeInt16LE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2401,11 +2408,11 @@ let buf = buffer.allocUninitializedFromPool(2); buf.writeInt16LE(0x0304, 0); ``` -### writeInt32BE +## buffer.writeInt32BE writeInt32BE(value: number, offset?: number): number -从buf的offset偏移写入大端序的32位有符号整型数据value +从Buffer对象的offset偏移写入大端序的32位有符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2413,7 +2420,7 @@ writeInt32BE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2441,11 +2448,11 @@ buf.writeInt32BE(0x01020304, 0); ``` -### writeInt32LE +## buffer.writeInt32LE writeInt32LE(value: number, offset?: number): number -从buf的offset偏移写入小端序的32位有符号整型数据value +从Buffer对象的offset偏移写入小端序的32位有符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2453,7 +2460,7 @@ writeInt32LE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2480,11 +2487,11 @@ let buf = buffer.allocUninitializedFromPool(4); buf.writeInt32LE(0x05060708, 0); ``` -### writeIntBE +## buffer.writeIntBE writeIntBE(value: number, offset: number, byteLength: number): number -从buf的offset偏移写入大端序的有符号value数据,value字节长度为byteLength +从Buffer对象的offset偏移写入大端序的有符号value数据,value字节长度为byteLength。 **系统能力:** SystemCapability.Utils.Lang @@ -2492,7 +2499,7 @@ writeIntBE(value: number, offset: number, byteLength: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 是 | 偏移量。 默认值: 0。 | | byteLength | number | 是 | 要写入的字节数。 | @@ -2521,11 +2528,11 @@ buf.writeIntBE(0x1234567890ab, 0, 6); ``` -### writeIntLE +## buffer.writeIntLE writeIntLE(value: number, offset: number, byteLength: number): number -从buf的offset偏移写入小端序的有符号value数据,value字节长度为byteLength +从Buffer对象的offset偏移写入小端序的有符号value数据,value字节长度为byteLength。 **系统能力:** SystemCapability.Utils.Lang @@ -2533,7 +2540,7 @@ writeIntLE(value: number, offset: number, byteLength: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 是 | 偏移量。 默认值: 0。 | | byteLength | number | 是 | 要写入的字节数。 | @@ -2561,11 +2568,11 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeIntLE(0x1234567890ab, 0, 6); ``` -### writeUInt8 +## buffer.writeUInt8 writeUInt8(value: number, offset?: number): number -从buf的offset偏移写入8位无符号整型数据value +从Buffer对象的offset偏移写入8位无符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2573,7 +2580,7 @@ writeUInt8(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2603,11 +2610,11 @@ buf.writeUInt8(0x23, 2); buf.writeUInt8(0x42, 3); ``` -### writeUInt16BE +## buffer.writeUInt16BE writeUInt16BE(value: number, offset?: number): number -从buf的offset偏移写入大端序的16位无符号整型数据value +从Buffer对象的offset偏移写入大端序的16位无符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2615,7 +2622,7 @@ writeUInt16BE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2643,11 +2650,11 @@ buf.writeUInt16BE(0xdead, 0); buf.writeUInt16BE(0xbeef, 2); ``` -### writeUInt16LE +## buffer.writeUInt16LE writeUInt16LE(value: number, offset?: number): number -从buf的offset偏移写入小端序的16位无符号整型数据value +从Buffer对象的offset偏移写入小端序的16位无符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2655,7 +2662,7 @@ writeUInt16LE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2683,11 +2690,11 @@ buf.writeUInt16LE(0xdead, 0); buf.writeUInt16LE(0xbeef, 2); ``` -### writeUInt32BE +## buffer.writeUInt32BE writeUInt32BE(value: number, offset?: number): number -从buf的offset偏移写入大端序的32位无符号整型数据value +从Buffer对象的offset偏移写入大端序的32位无符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2695,7 +2702,7 @@ writeUInt32BE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数据。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2722,11 +2729,11 @@ let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt32BE(0xfeedface, 0); ``` -### writeUInt32LE +## buffer.writeUInt32LE writeUInt32LE(value: number, offset?: number): number -从buf的offset偏移写入小端序的32位无符号整型数据value +从Buffer对象的offset偏移写入小端序的32位无符号整型数据value。 **系统能力:** SystemCapability.Utils.Lang @@ -2734,7 +2741,7 @@ writeUInt32LE(value: number, offset?: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数字。 | +| value | number | 是 | 写入Buffer对象的数字。 | | offset | number | 否 | 偏移量。 默认值: 0。 | @@ -2761,11 +2768,11 @@ let buf = buffer.allocUninitializedFromPool(4); buf.writeUInt32LE(0xfeedface, 0); ``` -### writeUIntBE +## buffer.writeUIntBE writeUIntBE(value: number, offset: number, byteLength: number): number -从buf的offset偏移写入大端序的无符号value数据,value字节长度为byteLength +从Buffer对象的offset偏移写入大端序的无符号value数据,value字节长度为byteLength。 **系统能力:** SystemCapability.Utils.Lang @@ -2773,7 +2780,7 @@ writeUIntBE(value: number, offset: number, byteLength: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数据。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 是 | 偏移量。 默认值: 0。 | | byteLength | number | 是 | 要写入的字节数。 | @@ -2801,11 +2808,11 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntBE(0x1234567890ab, 0, 6); ``` -### writeUIntLE +## buffer.writeUIntLE writeUIntLE(value: number, offset: number, byteLength: number): number -从buf的offset偏移写入小端序的无符号value数据,value字节长度为byteLength +从Buffer对象的offset偏移写入小端序的无符号value数据,value字节长度为byteLength。 **系统能力:** SystemCapability.Utils.Lang @@ -2813,7 +2820,7 @@ writeUIntLE(value: number, offset: number, byteLength: number): number | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| value | number | 是 | 写入 buf 的数据。 | +| value | number | 是 | 写入Buffer的数据。 | | offset | number | 是 | 偏移量。 默认值: 0。 | | byteLength | number | 是 | 要写入的字节数。 | @@ -2841,11 +2848,11 @@ let buf = buffer.allocUninitializedFromPool(6); buf.writeUIntLE(0x1234567890ab, 0, 6); ``` -### transcode +## buffer.transcode transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer -将给定的Buffer或Uint8Array实例从一种字符编码重新编码为另一种 +将给定的Buffer或Uint8Array对象从一种字符编码重新编码为另一种。 **系统能力:** SystemCapability.Utils.Lang @@ -2919,7 +2926,7 @@ arrayBuffer(): Promise<ArrayBuffer> **返回值:** | 类型 | 说明 | | -------- | -------- | -| Promise<ArrayBuffer> | 返回包含Blob数据的ArrayBuffer的Promise。 | +| Promise<ArrayBuffer> | Promise对象,返回包含Blob数据的ArrayBuffer。 | **示例:** ```ts @@ -2934,7 +2941,7 @@ pro.then(val => { slice(start?: number, end?: number, type?: string): Blob -创建并返回一个复制原blob对象中start到end位置数据的新blob实例对象。 +创建并返回一个复制原Blob对象中指定数据长度的Blob新对象。 **系统能力:** SystemCapability.Utils.Lang @@ -2962,14 +2969,14 @@ let blob3 = blob.slice(0, 2, "MIME"); text(): Promise<string> -返回一个Promise,该Promise中的值为UTF8编码类型的文本。 +使用UTF8进行解码并返回一个文本。使用Promise异步回调。 **系统能力:** SystemCapability.Utils.Lang **返回值:** | 类型 | 说明 | | -------- | -------- | -| Promise<string> | 包含以UTF8编码的文本的Promise。 | +| Promise<string> | Promise对象,返回包含以UTF8解码的文本。 | **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index b38076ade23d166d99cd81e94312f639c111207b..05d2227d309e82ee2c0091d5b0ac7a403bc5c9e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -4,307 +4,27 @@ 该模块提供以下关系型数据库相关的常用功能: -- [RdbPredicatesV9](#rdbpredicatesv99): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 -- [RdbStoreV9](#rdbstorev99):提供管理关系数据库(RDB)方法的接口。 +- [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 +- [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。 > **说明:** -> +> > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 从API Version 9开始,该接口不再维护,推荐使用新接口[@ohos.data.relationalStore](js-apis-data-relationalStore.md)。 + ## 导入模块 ```js import data_rdb from '@ohos.data.rdb'; ``` - -## data_rdb.getRdbStoreV99+ - -getRdbStoreV9(context: Context, config: StoreConfigV9, version: number, callback: AsyncCallback<RdbStoreV9>): void - -获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。
目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | -| callback | AsyncCallback<[RdbStoreV9](#rdbstorev9)> | 是 | 指定callback回调函数,返回RdbStoreV9对象。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ----------------------- | -| 14800010 | Invalid database name. | -| 14800011 | Database corrupted. | - -**示例:** - -FA模型示例: - -```js -// 获取context -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() - -// 获取context后调用getRdbStoreV9 -const STORE_CONFIGV9 = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - if (err) { - console.info("Get RdbStoreV9 failed, err: " + err) - return - } - console.log("Get RdbStoreV9 successfully.") -}) -``` - -Stage模型示例: - -```ts -// 获取context -import Ability from '@ohos.application.Ability' -let context -class MainAbility extends Ability{ - onWindowStageCreate(windowStage){ - context = this.context - } -} - -// 获取context后调用getRdbStoreV9 -const STORE_CONFIGV9 = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { - if (err) { - console.info("Get RdbStoreV9 failed, err: " + err) - return - } - console.log("Get RdbStoreV9 successfully.") -}) -``` - -## data_rdb.getRdbStoreV99+ - -getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> - -获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 | -| version | number | 是 | 数据库版本。
目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | - -**返回值**: - -| 类型 | 说明 | -| ----------------------------------------- | --------------------------------- | -| Promise<[RdbStoreV9](#rdbstorev99)> | Promise对象。返回RdbStoreV9对象。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ----------------------- | -| 14800010 | Invalid database name. | -| 14800011 | Database corrupted. | - -**示例:** - -FA模型示例: - -```js -// 获取context -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() - -// 获取context后调用getRdbStoreV9 -const STORE_CONFIGV9 = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); -promise.then(async (rdbStoreV9) => { - console.log("Get RdbStoreV9 successfully.") -}).catch((err) => { - console.log("Get RdbStoreV9 failed, err: " + err) -}) -``` - -Stage模型示例: - -```ts -// 获取context -import Ability from '@ohos.application.Ability' -let context -class MainAbility extends Ability{ - onWindowStageCreate(windowStage){ - context = this.context - } -} - -// 获取context后调用getRdbStoreV9 -const STORE_CONFIGV9 = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -let promise = data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1); -promise.then(async (rdbStoreV9) => { - console.log("Get RdbStoreV9 successfully.") -}).catch((err) => { - console.log("Get RdbStoreV9 failed, err: " + err) -}) -``` - -## data_rdb.deleteRdbStoreV99+ - -deleteRdbStoreV9(context: Context, name: string, callback: AsyncCallback<void>): void - -删除数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| name | string | 是 | 数据库名称。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ----------------------- | -| 14800010 | Invalid database name. | - -**示例:** - -FA模型示例: - -```js -// 获取context -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() - -// 获取context后调用deleteRdbStoreV9 -data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStorev9 failed, err: " + err) - return - } - console.log("Delete RdbStorev9 successfully.") -}) -``` - -Stage模型示例: - -```ts -// 获取context -import Ability from '@ohos.application.Ability' -let context -class MainAbility extends Ability{ - onWindowStageCreate(windowStage){ - context = this.context - } -} - -// 获取context后调用deleteRdbStoreV9 -data_rdb.deleteRdbStoreV9(context, "RdbTest.db", function (err) { - if (err) { - console.info("Delete RdbStoreV9 failed, err: " + err) - return - } - console.log("Delete RdbStoreV9 successfully.") -}) -``` - -## data_rdb.deleteRdbStoreV99+ - -deleteRdbStoreV9(context: Context, name: string): Promise<void> - -使用指定的数据库文件配置删除数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| name | string | 是 | 数据库名称。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ----------------------- | -| 14800010 | Invalid database name. | - -**示例:** - -FA模型示例: - -```js -// 获取context -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() - -// 获取context后调用deleteRdbStoreV9 -let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") -promise.then(()=>{ - console.log("Delete RdbStoreV9 successfully.") -}).catch((err) => { - console.info("Delete RdbStoreV9 failed, err: " + err) -}) -``` - -Stage模型示例: - -```ts -// 获取context -import Ability from '@ohos.application.Ability' -let context -class MainAbility extends Ability{ - onWindowStageCreate(windowStage){ - context = this.context - } -} - -// 获取context后调用deleteRdbStoreV9 -let promise = data_rdb.deleteRdbStoreV9(context, "RdbTest.db") -promise.then(()=>{ - console.log("Delete RdbStoreV9 successfully.") -}).catch((err) => { - console.info("Delete RdbStoreV9 failed, err: " + err) -}) -``` - -## data_rdb.getRdbStore(deprecated) +## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -359,16 +79,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { }) ``` -## data_rdb.getRdbStore(deprecated) +## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -426,16 +142,12 @@ promise.then(async (rdbStore) => { }) ``` -## data_rdb.deleteRdbStore(deprecated) +## data_rdb.deleteRdbStore deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void 删除数据库,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -487,2205 +199,65 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { }) ``` -## data_rdb.deleteRdbStore(deprecated) - -deleteRdbStore(context: Context, name: string): Promise<void> - -使用指定的数据库文件配置删除数据库,使用Promise异步回调。 - -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99-1)替代。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------- | ---- | ------------------------------------------------------------ | -| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | -| name | string | 是 | 数据库名称。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**示例:** - -FA模型示例: - -```js -// 获取context -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() - -// 获取context后调用deleteRdbStore -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(() => { - console.log("Delete RdbStore successfully.") -}).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) -}) -``` - -Stage模型示例: - -```ts -// 获取context -import Ability from '@ohos.application.Ability' -let context -class MainAbility extends Ability{ - onWindowStageCreate(windowStage){ - context = this.context - } -} - -// 获取context后调用deleteRdbStore -let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ - console.log("Delete RdbStore successfully.") -}).catch((err) => { - console.info("Delete RdbStore failed, err: " + err) -}) -``` - -## RdbPredicatesV99+ - -表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 - - -### constructor9+ - -constructor(name: string) - - -构造函数。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------ | -| name | string | 是 | 数据库表名。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -``` - -### inDevices9+ - -inDevices(devices: Array<string>): RdbPredicatesV9 - - -同步分布式数据库时连接到组网内指定的远程设备。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------------------- | ---- | -------------------------- | -| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.inDevices(['12345678abcde']) -``` - -### inAllDevices9+ - -inAllDevices(): RdbPredicatesV9 - - -同步分布式数据库时连接到组网内所有的远程设备。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesv9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.inAllDevices() -``` - -### equalTo9+ - -equalTo(field: string, value: ValueType): RdbPredicatesV9 - - -配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "lisi") -``` - - -### notEqualTo9+ - -notEqualTo(field: string, value: ValueType): RdbPredicatesV9 - - -配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.notEqualTo("NAME", "lisi") -``` - - -### beginWrap9+ - -beginWrap(): RdbPredicatesV9 - - -向谓词添加左括号。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有左括号的Rdb谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "lisi") - .beginWrap() - .equalTo("AGE", 18) - .or() - .equalTo("SALARY", 200.5) - .endWrap() -``` - -### endWrap9+ - -endWrap(): RdbPredicatesV9 - -向谓词添加右括号。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有右括号的Rdb谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "lisi") - .beginWrap() - .equalTo("AGE", 18) - .or() - .equalTo("SALARY", 200.5) - .endWrap() -``` - -### or9+ - -or(): RdbPredicatesV9 - -将或条件添加到谓词中。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有或条件的Rdb谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") - .or() - .equalTo("NAME", "Rose") -``` - -### and9+ - -and(): RdbPredicatesV9 - -向谓词添加和条件。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回带有和条件的Rdb谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") - .and() - .equalTo("SALARY", 200.5) -``` - -### contains9+ - -contains(field: string, value: string): RdbPredicatesV9 - -配置谓词以匹配数据字段为string且value包含指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.contains("NAME", "os") -``` - -### beginsWith9+ - -beginsWith(field: string, value: string): RdbPredicatesV9 - -配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.beginsWith("NAME", "os") -``` - -### endsWith9+ - -endsWith(field: string, value: string): RdbPredicatesV9 - -配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.endsWith("NAME", "se") -``` - -### isNull9+ - -isNull(field: string): RdbPredicatesV9 - -配置谓词以匹配值为null的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| field | string | 是 | 数据库表中的列名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例**: - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.isNull("NAME") -``` - -### isNotNull9+ - -isNotNull(field: string): RdbPredicatesV9 - -配置谓词以匹配值不为null的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| field | string | 是 | 数据库表中的列名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.isNotNull("NAME") -``` - -### like9+ - -like(field: string, value: string): RdbPredicatesV9 - -配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.like("NAME", "%os%") -``` - -### glob9+ - -glob(field: string, value: string): RdbPredicatesV9 - -配置RdbPredicatesV9匹配数据字段为string的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| field | string | 是 | 数据库表中的列名。 | -| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.glob("NAME", "?h*g") -``` - -### between9+ - -between(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 - -将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | -------------------------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.between("AGE", 10, 50) -``` - -### notBetween9+ - -notBetween(field: string, low: ValueType, high: ValueType): RdbPredicatesV9 - -配置RdbPredicatesV9以匹配数据字段为ValueType且value超出给定范围的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | -------------------------- | -| field | string | 是 | 数据库表中的列名。 | -| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | -| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.notBetween("AGE", 10, 50) -``` - -### greaterThan9+ - -greaterThan(field: string, value: ValueType): RdbPredicatesV9 - -配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.greaterThan("AGE", 18) -``` - -### lessThan9+ - -lessThan(field: string, value: ValueType): RdbPredicatesV9 - -配置谓词以匹配数据字段为valueType且value小于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.lessThan("AGE", 20) -``` - -### greaterThanOrEqualTo9+ - -greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 - -配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.greaterThanOrEqualTo("AGE", 18) -``` - -### lessThanOrEqualTo9+ - -lessThanOrEqualTo(field: string, value: ValueType): RdbPredicatesV9 - -配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------- | ---- | ---------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.lessThanOrEqualTo("AGE", 20) -``` - -### orderByAsc9+ - -orderByAsc(field: string): RdbPredicatesV9 - -配置谓词以匹配其值按升序排序的列。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| field | string | 是 | 数据库表中的列名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.orderByAsc("NAME") -``` - -### orderByDesc9+ - -orderByDesc(field: string): RdbPredicatesV9 - -配置谓词以匹配其值按降序排序的列。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| field | string | 是 | 数据库表中的列名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.orderByDesc("AGE") -``` - -### distinct9+ - -distinct(): RdbPredicatesV9 - -配置谓词以过滤重复记录并仅保留其中一个。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------------ | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于过滤重复记录的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Rose").distinct() -``` - -### limitAs9+ - -limitAs(value: number): RdbPredicatesV9 - -设置最大数据记录数的谓词。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------- | -| value | number | 是 | 最大数据记录数。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------------------ | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于设置最大数据记录数的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Rose").limitAs(3) -``` - -### offsetAs9+ - -offsetAs(rowOffset: number): RdbPredicatesV9 - -配置RdbPredicatesV9以指定返回结果的起始位置。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ---------------------------------- | -| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ------------------------------------ | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定返回结果起始位置的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Rose").offsetAs(3) -``` - -### groupBy9+ - -groupBy(fields: Array<string>): RdbPredicatesV9 - -配置RdbPredicatesV9按指定列分组查询结果。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------- | ---- | -------------------- | -| fields | Array<string> | 是 | 指定分组依赖的列名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | ---------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回分组查询列的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.groupBy(["AGE", "NAME"]) -``` - -### indexedBy9+ - -indexedBy(field: string): RdbPredicatesV9 - -配置RdbPredicatesV9以指定索引列。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | -------------- | -| field | string | 是 | 索引列的名称。 | - -**返回值**: - - -| 类型 | 说明 | -| ------------------------------------ | ------------------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回具有指定索引列的RdbPredicatesV9。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.indexedBy("SALARY_INDEX") -``` - -### in9+ - -in(field: string, value: Array<ValueType>): RdbPredicatesV9 - -配置RdbPredicatesV9以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------ | ---- | --------------------------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.in("AGE", [18, 20]) -``` - -### notIn9+ - -notIn(field: string, value: Array<ValueType>): RdbPredicatesV9 - -将RdbPredicatesV9配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------ | ---- | ------------------------------------- | -| field | string | 是 | 数据库表中的列名。 | -| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------ | -------------------------- | -| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.notIn("NAME", ["Lisa", "Rose"]) -``` - -## RdbStoreV99+ - -提供管理关系数据库(RDB)方法的接口。 - -在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 - -### insert9+ - -insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void - -向目标表中插入一行数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | - -**示例:** - -```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -rdbStoreV9.insert("EMPLOYEE", valueBucket, function (status, rowId) { - if (status) { - console.log("Insert is failed"); - return; - } - console.log("Insert is successful, rowId = " + rowId); -}) -``` - -### insert9+ - -insert(table: string, values: ValuesBucket):Promise<number> - -向目标表中插入一行数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ----------------------------- | ---- | -------------------------- | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ------------------------------------------------- | -| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | - -**示例:** - -```js -const valueBucket = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let promise = rdbStoreV9.insert("EMPLOYEE", valueBucket) -promise.then((rowId) => { - console.log("Insert is successful, rowId = " + rowId); -}).catch((status) => { - console.log("Insert is failed"); -}) -``` - -### batchInsert9+ - -batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void - -向目标表中插入一组数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | - -**示例:** - -```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} - -let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { - if (status) { - console.log("batchInsert is failed, status = " + status); - return; - } - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); -}) -``` - -### batchInsert9+ - -batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> - -向目标表中插入一组数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------------------ | ---- | ---------------------------- | -| table | string | 是 | 指定的目标表名。 | -| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ----------------------------------------------------------- | -| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | - -**示例:** - -```js -const valueBucket1 = { - "NAME": "Lisa", - "AGE": 18, - "SALARY": 100.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]) -} -const valueBucket2 = { - "NAME": "Jack", - "AGE": 19, - "SALARY": 101.5, - "CODES": new Uint8Array([6, 7, 8, 9, 10]) -} -const valueBucket3 = { - "NAME": "Tom", - "AGE": 20, - "SALARY": 102.5, - "CODES": new Uint8Array([11, 12, 13, 14, 15]) -} - -let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); -let promise = rdbStoreV9.batchInsert("EMPLOYEE", valueBuckets); -promise.then((insertNum) => { - console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); -}).catch((status) => { - console.log("batchInsert is failed, status = " + status); -}) -``` - -### update9+ - -update(values: ValuesBucket, predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void - -根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | - -**示例:** - -```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") -rdbStoreV9.update(valueBucket, predicatesV9, function (err, ret) { - if (err) { - console.info("Updated failed, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(values: ValuesBucket, predicates: RdbPredicatesV9):Promise<number> - -根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicatesV9 | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ----------------------------------------- | -| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | - -**示例:** - -```js -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") -let promise = rdbStoreV9.update(valueBucket, predicatesV9) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Updated failed, err: " + err) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -根据DataSharePredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | -| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStoreV9.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { - if (err) { - console.info("Updated failed, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| table | string | 是 | 指定的目标表名。 | -| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ----------------------------------------- | -| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStoreV9.update("EMPLOYEE", valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Updated failed, err: " + err) -}) -``` - -### delete9+ - -delete(predicates: RdbPredicatesV9, callback: AsyncCallback<number>):void - -根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ----------------------------------------- | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") -rdbStoreV9.delete(predicatesV9, function (err, rows) { - if (err) { - console.info("Delete failed, err: " + err) - return - } - console.log("Delete rows: " + rows) -}) -``` - -### delete9+ - -delete(predicates: RdbPredicatesV9):Promise<number> - -根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ----------------------------------------- | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ------------------------------- | -| Promise<number> | Promise对象。返回受影响的行数。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Lisa") -let promise = rdbStoreV9.delete(predicatesV9) -promise.then((rows) => { - console.log("Delete rows: " + rows) -}).catch((err) => { - console.info("Delete failed, err: " + err) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | -| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStoreV9.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Delete failed, err: " + err) - return - } - console.log("Delete rows: " + rows) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ------------------------------- | -| Promise<number> | Promise对象。返回受影响的行数。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStoreV9.delete("EMPLOYEE", predicates) -promise.then((rows) => { - console.log("Delete rows: " + rows) -}).catch((err) => { - console.info("Delete failed, err: " + err) -}) -``` - -### query9+ - -query(predicates: RdbPredicatesV9, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void - -根据指定条件查询数据库中的数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Rose") -rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}) -``` - -### query9+ - -query(predicates: RdbPredicatesV9, columns?: Array<string>):Promise<ResultSetV9> - -根据指定条件查询数据库中的数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------------------------- | -------------------------------------------------- | -| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - - ```js -let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE") -predicatesV9.equalTo("NAME", "Rose") -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSetV9) => { - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}).catch((err) => { - console.info("Query failed, err: " + err) -}) - ``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSetV9>):void - -根据指定条件查询数据库中的数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | -| table | string | 是 | 指定的目标表名。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSetV9) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}) -``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSetV9> - -根据指定条件查询数据库中的数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**系统接口:** 此接口为系统接口。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | -| table | string | 是 | 指定的目标表名。 | -| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | -| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------------------------- | -------------------------------------------------- | -| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStoreV9.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSetV9) => { - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}).catch((err) => { - console.info("Query failed, err: " + err) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string> , callback: AsyncCallback<ResultSetV9>): void - -根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | -| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') -predicatesV9.greaterThan("id", 0) -rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSetV9){ - if (err) { - console.info("Failed to remoteQuery, err: " + err) - return - } - console.info("ResultSet column names: " + resultSetV9.columnNames) - console.info("ResultSet column count: " + resultSetV9.columnCount) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> - -根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | -| device | string | 是 | 指定的远程设备的networkId。 | -| table | string | 是 | 指定的目标表名。 | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 | -| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------------------------------ | -------------------------------------------------- | -| Promise<[ResultSetV9](js-apis-data-resultset.md#resultset)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') -predicatesV9.greaterThan("id", 0) -let promise = rdbStoreV9.remoteQuery("deviceId", "EMPLOYEE", predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSetV9) => { - console.info("ResultSet column names: " + resultSetV9.columnNames) - console.info("ResultSet column count: " + resultSetV9.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` - -### querySql9+ - -querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSetV9>):void - -根据指定SQL语句查询数据库中的数据,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | -| sql | string | 是 | 指定要执行的SQL语句。 | -| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | -| callback | AsyncCallback<[ResultSetV9](js-apis-data-resultset.md)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSetV9) { - if (err) { - console.info("Query failed, err: " + err) - return - } - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}) -``` - -### querySql9+ - -querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSetV9> - -根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | --------------------- | -| sql | string | 是 | 指定要执行的SQL语句。 | -| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------------------------------------------- | -------------------------------------------------- | -| Promise<[ResultSetV9](js-apis-data-resultset.md)> | Promise对象。如果操作成功,则返回ResultSetV9对象。 | - -**示例:** - -```js -let promise = rdbStoreV9.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) -promise.then((resultSetV9) => { - console.log("ResultSet column names: " + resultSetV9.columnNames) - console.log("ResultSet column count: " + resultSetV9.columnCount) -}).catch((err) => { - console.info("Query failed, err: " + err) -}) -``` - -### executeSql9+ - -executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void - -执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | ---------------------- | -| sql | string | 是 | 指定要执行的SQL语句。 | -| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```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)" -rdbStoreV9.executeSql(SQL_CREATE_TABLE, null, function(err) { - if (err) { - console.info("ExecuteSql failed, err: " + err) - return - } - console.info('Create table done.') -}) -``` - -### executeSql9+ - -executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> - -执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------ | ---- | --------------------- | -| sql | string | 是 | 指定要执行的SQL语句。 | -| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**示例:** - -```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)" -let promise = rdbStoreV9.executeSql(SQL_CREATE_TABLE) -promise.then(() => { - console.info('Create table done.') -}).catch((err) => { - console.info("ExecuteSql failed, err: " + err) -}) -``` - -### beginTransaction9+ - -beginTransaction():void - -在开始执行SQL语句之前,开始事务。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**示例:** - -```js -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { - rdbStoreV9.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStoreV9.insert("test", valueBucket) - rdbStoreV9.commit() -}) -``` - -### commit9+ - -commit():void - -提交已执行的SQL语句。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**示例:** - -```js -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { - rdbStoreV9.beginTransaction() - const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStoreV9.insert("test", valueBucket) - rdbStoreV9.commit() -}) -``` - -### rollBack9+ - -rollBack():void - -回滚已经执行的SQL语句。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**示例:** - -```js -import featureAbility from '@ohos.ability.featureAbility' -let context = featureAbility.getContext() -const STORE_CONFIG = { name: "RdbTest.db", - securityLevel: data_rdb.SecurityLevel.S1} -data_rdb.getRdbStoreV9(context, STORE_CONFIG, 1, async function (err, rdbStoreV9) { - try { - rdbStoreV9.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStoreV9.insert("test", valueBucket) - rdbStoreV9.commit() - } catch (e) { - rdbStoreV9.rollBack() - } -}) -``` - -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -以指定名称备份数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------ | -| destName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStoreV9.backup("dbBackup.db", function(err) { - if (err) { - console.info('Backup failed, err: ' + err) - return - } - console.info('Backup success.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -以指定名称备份数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------ | -| destName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**示例:** - -```js -let promiseBackup = rdbStoreV9.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backup success.') -}).catch((err)=>{ - console.info('Backup failed, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -从指定的数据库备份文件恢复数据库,使用callback异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------ | -| srcName | string | 是 | 指定数据库的备份文件名。 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStoreV9.restore("dbBackup.db", function(err) { - if (err) { - console.info('Restore failed, err: ' + err) - return - } - console.info('Restore success.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -从指定的数据库备份文件恢复数据库,使用Promise异步回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | ------ | ---- | ------------------------ | -| srcName | string | 是 | 指定数据库的备份文件名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**示例:** - -```js -let promiseRestore = rdbStoreV9.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restore success.') -}).catch((err)=>{ - console.info('Restore failed, err: ' + err) -}) -``` - -### setDistributedTables9+ - -setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void - -设置分布式列表,使用callback异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------------------- | -| tables | Array<string> | 是 | 要设置的分布式列表表名 | -| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | - -**示例:** - -```js -rdbStoreV9.setDistributedTables(["EMPLOYEE"], function (err) { - if (err) { - console.info('SetDistributedTables failed, err: ' + err) - return - } - console.info('SetDistributedTables successfully.') -}) -``` - -### setDistributedTables9+ - - setDistributedTables(tables: Array<string>): Promise<void> - -设置分布式列表,使用Promise异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------- | ---- | ------------------------ | -| tables | Array<string> | 是 | 要设置的分布式列表表名。 | - -**返回值**: - -| 类型 | 说明 | -| ------------------- | ------------------------- | -| Promise<void> | 无返回结果的Promise对象。 | - -**示例:** - -```js -let promise = rdbStoreV9.setDistributedTables(["EMPLOYEE"]) -promise.then(() => { - console.info("SetDistributedTables successfully.") -}).catch((err) => { - console.info("SetDistributedTables failed, err: " + err) -}) -``` - -### obtainDistributedTableName9+ - -obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void - -根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| device | string | 是 | 远程设备 。 | -| table | string | 是 | 本地表名。 | -| callback | AsyncCallback<string> | 是 | 指定的callback回调函数。如果操作成功,返回远程设备的分布式表名。 | - -**示例:** - -```js -rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { - if (err) { - console.info('ObtainDistributedTableName failed, err: ' + err) - return - } - console.info('ObtainDistributedTableName successfully, tableName=.' + tableName) -}) -``` - -### obtainDistributedTableName9+ - - obtainDistributedTableName(device: string, table: string): Promise<string> - -根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------- | -| device | string | 是 | 远程设备。 | -| table | string | 是 | 本地表名。 | - -**返回值**: - -| 类型 | 说明 | -| --------------------- | ----------------------------------------------------- | -| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | - -**示例:** - -```js -let promise = rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE") -promise.then((tableName) => { - console.info('ObtainDistributedTableName successfully, tableName= ' + tableName) -}).catch((err) => { - console.info('ObtainDistributedTableName failed, err: ' + err) -}) -``` - -### sync9+ - -sync(mode: SyncMode, predicates: RdbPredicatesV9, callback: AsyncCallback<Array<[string, number]>>): void - -在设备之间同步数据, 使用callback异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | -| callback | AsyncCallback<Array<[string, number]>> | 是 | 指定的callback回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') -predicatesV9.inDevices(['12345678abcde']) -rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9, function (err, result) { - if (err) { - console.log('Sync failed, err: ' + err) - return - } - console.log('Sync done.') - for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + ' status=' + result[i][1]) - } -}) -``` - -### sync9+ - - sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise<Array<[string, number]>> - -在设备之间同步数据,使用Promise异步回调。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------------------ | ---- | ------------------------------ | -| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 | -| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 | - -**返回值**: - -| 类型 | 说明 | -| -------------------------------------------- | ------------------------------------------------------------ | -| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | - -**示例:** - -```js -let predicatesV9 = new data_rdb.RdbPredicatesV9('EMPLOYEE') -predicatesV9.inDevices(['12345678abcde']) -let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicatesV9) -promise.then((resultSetV9) =>{ - console.log('Sync done.') - for (let i = 0; i < resultSetV9.length; i++) { - console.log('device=' + resultSetV9[i][0] + ' status=' + resultSetV9[i][1]) - } -}).catch((err) => { - console.log('Sync failed') -}) -``` - -### on('dataChange')9+ - -on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void - -注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------------------------------- | -| event | string | 是 | 取值为'dataChange',表示数据更改。 | -| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | -| observer | Callback<Array<string>> | 是 | 指分布式数据库中数据更改事件的观察者。 | - -**示例:** - -```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } -} -try { - rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) -} catch (err) { - console.log('Register observer failed') -} -``` - -### off('dataChange')9+ +## data_rdb.deleteRdbStore -off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void +deleteRdbStore(context: Context, name: string): Promise<void> -从数据库中删除指定类型的指定观察者, 使用callback异步回调。 +使用指定的数据库文件配置删除数据库,使用Promise异步回调。 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------- | ---- | ------------------------------------------- | -| event | string | 是 | 取值为'dataChange',表示数据更改。 | -| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | -| observer | Callback<Array<string>> | 是 | 指已注册的数据更改观察者。 | +**参数** -**示例:** +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | -```js -function storeObserver(devices) { - for (let i = 0; i < devices.length; i++) { - console.log('device=' + devices[i] + ' data changed') - } -} -try { - rdbStoreV9.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) -} catch (err) { - console.log('Unregister observer failed') -} -``` +**返回值**: -## StoreConfigV99+ +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | -管理关系数据库配置。 +**示例:** -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core +FA模型示例: -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------- | ---- | --------------------------------------------------------- | -| name | string | 是 | 数据库文件名。 | -| securityLevel | SecurityLevel | 是 | 设置数据库安全级别 | -| encrypt | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() -## SecurityLevel9+ +// 获取context后调用deleteRdbStore +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(() => { + console.log("Delete RdbStore successfully.") +}).catch((err) => { + console.info("Delete RdbStore failed, err: " + err) +}) +``` -数据库的安全级别枚举。 +Stage模型示例: -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} -| 名称 | 值 | 说明 | -| ---- | ---- | ------------------------------------------------------------ | -| S1 | 1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | -| S2 | 2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | -| S3 | 3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | -| S4 | 4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | +// 获取context后调用deleteRdbStore +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStore successfully.") +}).catch((err) => { + console.info("Delete RdbStore failed, err: " + err) +}) +``` ## ValueType @@ -2714,7 +286,7 @@ try { 指数据库同步模式。 -**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core | 名称 | 值 | 说明 | | -------------- | ---- | ---------------------------------- | @@ -2733,25 +305,26 @@ try { | --------------------- | ---- | ------------------ | | SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | -## RdbPredicates(deprecated) +## StoreConfig -表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 +管理关系数据库配置。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[RdbPredicatesV9](#rdbpredicatesv99)替代。 +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| name | string | 是 | 数据库文件名。 | +## RdbPredicates -### constructor(deprecated) +表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 + +### constructor constructor(name: string) 构造函数。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[constructor](#constructor9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2766,16 +339,12 @@ constructor(name: string) let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ``` -### inDevices(deprecated) +### inDevices8+ inDevices(devices: Array<string>): RdbPredicates 同步分布式数据库时连接到组网内指定的远程设备。 -> **说明:** -> -> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inDevices](#indevices9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2797,16 +366,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inDevices(['12345678abcde']) ``` -### inAllDevices(deprecated) +### inAllDevices8+ inAllDevices(): RdbPredicates 同步分布式数据库时连接到组网内所有的远程设备。 -> **说明:** -> -> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inAllDevices](#inalldevices9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -2822,16 +387,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inAllDevices() ``` -### equalTo(deprecated) +### equalTo equalTo(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[equalTo](#equalto9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2855,16 +416,12 @@ predicates.equalTo("NAME", "lisi") ``` -### notEqualTo(deprecated) +### notEqualTo notEqualTo(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[notEqualTo](#notequalto9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -2888,16 +445,12 @@ predicates.notEqualTo("NAME", "lisi") ``` -### beginWrap(deprecated) +### beginWrap beginWrap(): RdbPredicates 向谓词添加左括号。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[beginWrap](#beginwrap9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -2918,16 +471,12 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### endWrap(deprecated) +### endWrap endWrap(): RdbPredicates 向谓词添加右括号。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[endWrap](#endwrap9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -2948,16 +497,12 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -### or(deprecated) +### or or(): RdbPredicates 将或条件添加到谓词中。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[or](#or9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -2975,16 +520,12 @@ predicates.equalTo("NAME", "Lisa") .equalTo("NAME", "Rose") ``` -### and(deprecated) +### and and(): RdbPredicates 向谓词添加和条件。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[and](#and9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -3002,16 +543,12 @@ predicates.equalTo("NAME", "Lisa") .equalTo("SALARY", 200.5) ``` -### contains(deprecated) +### contains contains(field: string, value: string): RdbPredicates 配置谓词以匹配数据字段为string且value包含指定值的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[contains](#contains9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3034,16 +571,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.contains("NAME", "os") ``` -### beginsWith(deprecated) +### beginsWith beginsWith(field: string, value: string): RdbPredicates 配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[beginsWith](#beginswith9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3066,16 +599,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.beginsWith("NAME", "os") ``` -### endsWith(deprecated) +### endsWith endsWith(field: string, value: string): RdbPredicates 配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[endsWith](#endswith9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3098,16 +627,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.endsWith("NAME", "se") ``` -### isNull(deprecated) +### isNull isNull(field: string): RdbPredicates 配置谓词以匹配值为null的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNull](#isnull9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3128,16 +653,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNull("NAME") ``` -### isNotNull(deprecated) +### isNotNull isNotNull(field: string): RdbPredicates 配置谓词以匹配值不为null的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNotNull](#isnotnull9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3159,16 +680,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNotNull("NAME") ``` -### like(deprecated) +### like like(field: string, value: string): RdbPredicates 配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[like](#like9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3191,16 +708,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.like("NAME", "%os%") ``` -### glob(deprecated) +### glob glob(field: string, value: string): RdbPredicates 配置RdbPredicates匹配数据字段为string的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[glob](#glob9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3223,16 +736,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.glob("NAME", "?h*g") ``` -### between(deprecated) +### between between(field: string, low: ValueType, high: ValueType): RdbPredicates 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[between](#between9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3256,16 +765,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.between("AGE", 10, 50) ``` -### notBetween(deprecated) +### notBetween notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates 配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notBetween](#notbetween9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3289,16 +794,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notBetween("AGE", 10, 50) ``` -### greaterThan(deprecated) +### greaterThan greaterThan(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThan](#greaterthan9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3321,16 +822,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThan("AGE", 18) ``` -### lessThan(deprecated) +### lessThan lessThan(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为valueType且value小于指定值的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThan](#lessthan9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3353,16 +850,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThan("AGE", 20) ``` -### greaterThanOrEqualTo(deprecated) +### greaterThanOrEqualTo greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThanOrEqualTo](#greaterthanorequalto9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3385,16 +878,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThanOrEqualTo("AGE", 18) ``` -### lessThanOrEqualTo(deprecated) +### lessThanOrEqualTo lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThanOrEqualTo](#lessthanorequalto9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3417,16 +906,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThanOrEqualTo("AGE", 20) ``` -### orderByAsc(deprecated) +### orderByAsc orderByAsc(field: string): RdbPredicates 配置谓词以匹配其值按升序排序的列。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByAsc](#orderbyasc9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3448,16 +933,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByAsc("NAME") ``` -### orderByDesc(deprecated) +### orderByDesc orderByDesc(field: string): RdbPredicates 配置谓词以匹配其值按降序排序的列。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByDesc](#orderbydesc9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3479,16 +960,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByDesc("AGE") ``` -### distinct(deprecated) +### distinct distinct(): RdbPredicates 配置谓词以过滤重复记录并仅保留其中一个。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[distinct](#distinct9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值**: @@ -3504,16 +981,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct() ``` -### limitAs(deprecated) +### limitAs limitAs(value: number): RdbPredicates 设置最大数据记录数的谓词。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[limitAs](#limitas9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3535,16 +1008,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").limitAs(3) ``` -### offsetAs(deprecated) +### offsetAs offsetAs(rowOffset: number): RdbPredicates 配置RdbPredicates以指定返回结果的起始位置。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[offsetAs](#offsetas9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3566,16 +1035,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").offsetAs(3) ``` -### groupBy(deprecated) +### groupBy groupBy(fields: Array<string>): RdbPredicates 配置RdbPredicates按指定列分组查询结果。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[groupBy](#groupby9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3597,16 +1062,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.groupBy(["AGE", "NAME"]) ``` -### indexedBy(deprecated) +### indexedBy indexedBy(field: string): RdbPredicates 配置RdbPredicates以指定索引列。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[indexedBy](#indexedby9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3629,16 +1090,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.indexedBy("SALARY_INDEX") ``` -### in(deprecated) +### in in(field: string, value: Array<ValueType>): RdbPredicates 配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[in](#in9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3661,16 +1118,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.in("AGE", [18, 20]) ``` -### notIn(deprecated) +### notIn notIn(field: string, value: Array<ValueType>): RdbPredicates 将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notIn](#notin9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3693,26 +1146,18 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notIn("NAME", ["Lisa", "Rose"]) ``` -## RdbStore(deprecated) +## RdbStore 提供管理关系数据库(RDB)方法的接口。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[RdbStoreV9](#rdbstorev99)替代。 - -在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 +在使用以下相关接口前,请使用[executeSql](#executesql8)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 -### insert(deprecated) +### insert insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void 向目标表中插入一行数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3741,16 +1186,12 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { }) ``` -### insert(deprecated) +### insert insert(table: string, values: ValuesBucket):Promise<number> 向目标表中插入一行数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3783,16 +1224,12 @@ promise.then((rowId) => { }) ``` -### batchInsert(deprecated) +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void 向目标表中插入一组数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3835,16 +1272,12 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { }) ``` -### batchInsert(deprecated) +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> 向目标表中插入一组数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3891,16 +1324,12 @@ promise.then((insertNum) => { }) ``` -### update(deprecated) +### update update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void 根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3922,25 +1351,21 @@ const valueBucket = { } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +rdbStore.update(valueBucket, predicates, function (err, rows) { if (err) { console.info("Updated failed, err: " + err) return } - console.log("Updated row count: " + ret) + console.log("Updated row count: " + rows) }) ``` -### update(deprecated) +### update update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -3968,23 +1393,19 @@ const valueBucket = { let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) }).catch((err) => { console.info("Updated failed, err: " + err) }) ``` -### delete(deprecated) +### delete delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void 根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4008,16 +1429,12 @@ rdbStore.delete(predicates, function (err, rows) { }) ``` -### delete(deprecated) +### delete delete(predicates: RdbPredicates):Promise<number> 根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4045,16 +1462,12 @@ promise.then((rows) => { }) ``` -### query(deprecated) +### query query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void 根据指定条件查询数据库中的数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4080,16 +1493,12 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e }) ``` -### query(deprecated) +### query query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> 根据指定条件查询数据库中的数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4119,16 +1528,12 @@ query(predicates: RdbPredicates, columns?: Array<string>):Promise<Resul }) ``` -### querySql(deprecated) +### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void 根据指定SQL语句查询数据库中的数据,使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4152,16 +1557,12 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", }) ``` -### querySql(deprecated) +### querySql8+ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4189,16 +1590,12 @@ promise.then((resultSet) => { }) ``` -### executeSql(deprecated) +### executeSql8+ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void 执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-1)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4222,16 +1619,12 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql(deprecated) +### executeSql8+ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> 执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-2)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4259,16 +1652,12 @@ promise.then(() => { }) ``` -### beginTransaction(deprecated) +### beginTransaction8+ beginTransaction():void 在开始执行SQL语句之前,开始事务。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[beginTransaction](#begintransaction9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** @@ -4290,16 +1679,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### commit(deprecated) +### commit8+ commit():void 提交已执行的SQL语句。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[commit](#commit9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** @@ -4321,16 +1706,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### rollBack(deprecated) +### rollBack8+ rollBack():void 回滚已经执行的SQL语句。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[rollBack](#rollback9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** @@ -4357,16 +1738,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### setDistributedTables(deprecated) +### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void 设置分布式列表,使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-1)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4390,16 +1767,12 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { }) ``` -### setDistributedTables(deprecated) +### setDistributedTables8+ setDistributedTables(tables: Array<string>): Promise<void> 设置分布式列表,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-2)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4427,16 +1800,12 @@ promise.then(() => { }) ``` -### obtainDistributedTableName(deprecated) +### obtainDistributedTableName8+ obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-1)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4461,16 +1830,12 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, }) ``` -### obtainDistributedTableName(deprecated) +### obtainDistributedTableName8+ obtainDistributedTableName(device: string, table: string): Promise<string> 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-2)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4499,16 +1864,12 @@ promise.then((tableName) => { }) ``` -### sync(deprecated) +### sync8+ sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void 在设备之间同步数据, 使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-1)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4538,16 +1899,12 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul }) ``` -### sync(deprecated) +### sync8+ sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> 在设备之间同步数据,使用Promise异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-2)替代。 - **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -4581,16 +1938,12 @@ promise.then((result) =>{ }) ``` -### on('dataChange')(deprecated) +### on('dataChange')8+ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[on](#ondatachange9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4598,7 +1951,7 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | string | 是 | 取值为'dataChange',表示数据更改。 | -| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| type | [SubscribeType](#subscribetype8) | 是 | 订阅类型。 | | observer | Callback<Array<string>> | 是 | 指分布式数据库中数据更改事件的观察者。 | **示例:** @@ -4616,16 +1969,12 @@ try { } ``` -### off('dataChange')(deprecated) +### off('dataChange')8+ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void 从数据库中删除指定类型的指定观察者, 使用callback异步回调。 -> **说明:** -> -> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[off](#offdatachange9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -4633,7 +1982,7 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | event | string | 是 | 取值为'dataChange',表示数据更改。 | -| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | +| type | [SubscribeType](#subscribetype8) | 是 | 订阅类型。 | | observer | Callback<Array<string>> | 是 | 指已注册的数据更改观察者。| **示例:** @@ -4650,18 +1999,3 @@ try { console.log('Unregister observer failed') } ``` - -## StoreConfig(deprecated) - -管理关系数据库配置。 - -**说明:** - -从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[StoreConfigV9](#storeconfigv99)替代。 - -**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------- | -------- | -------- | -| name | string | 是 | 数据库文件名。 | - diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..13995ff9dae2f33fb6228b41b3b18647c0fba075 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -0,0 +1,3194 @@ +# @ohos.data.relationalStore (关系型数据库) + +关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。 + +该模块提供以下关系型数据库相关的常用功能: + +- [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 +- [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。 +- [Resultset](#resultset):提供用户调用关系型数据库查询接口之后返回的结果集合。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import data_rdb from '@ohos.data.relationalStore'; +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void + +获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStore +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +data_rdb.getRdbStore(context, STORE_CONFIG, function (err, RdbStore) { + if (err) { + console.info("Get RdbStore failed, err: " + err) + return + } + if (rdbStore.openStatus == OpenStatus.ON_CREATA) { + console.log("RdbStore status is ON_CREATA") + } else if (rdbStore.openStatus == OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Get RdbStore successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStore +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +data_rdb.getRdbStore(context, STORE_CONFIG, function (err, RdbStore) { + if (err) { + console.info("Get RdbStore failed, err: " + err) + return + } + if (rdbStore.openStatus == OpenStatus.ON_CREATA) { + console.log("RdbStore status is ON_CREATA") + } else if (rdbStore.openStatus == OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Get RdbStore successfully.") +}) +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> + +获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise对象。返回RdbStore对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用getRdbStore +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == OpenStatus.ON_CREATA) { + console.log("RdbStore status is ON_CREATA") + } else if (rdbStore.openStatus == OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Get RdbStore successfully.") +}).catch((err) => { + console.log("Get RdbStore failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用getRdbStore +const STORE_CONFIG = { + name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1 +} +let promise = data_rdb.getRdbStore(context, STORE_CONFIG); +promise.then(async (rdbStore) => { + if (rdbStore.openStatus == OpenStatus.ON_CREATA) { + console.log("RdbStore status is ON_CREATA") + } else if (rdbStore.openStatus == OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Get RdbStore successfully.") +}).catch((err) => { + console.log("Get RdbStore failed, err: " + err) +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void + +删除数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStore +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStore failed, err: " + err) + return + } + console.log("Delete RdbStore successfully.") +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStore +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Delete RdbStore failed, err: " + err) + return + } + console.log("Delete RdbStore successfully.") +}) +``` + +## data_rdb.deleteRdbStore + +deleteRdbStore(context: Context, name: string): Promise<void> + +使用指定的数据库文件配置删除数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)。
Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 | +| name | string | 是 | 数据库名称。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**示例:** + +FA模型示例: + +```js +// 获取context +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 获取context后调用deleteRdbStore +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStore successfully.") +}).catch((err) => { + console.info("Delete RdbStore failed, err: " + err) +}) +``` + +Stage模型示例: + +```ts +// 获取context +import Ability from '@ohos.application.Ability' +let context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 获取context后调用deleteRdbStore +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Delete RdbStore successfully.") +}).catch((err) => { + console.info("Delete RdbStore failed, err: " + err) +}) +``` + +## StoreConfig + +管理关系数据库配置。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | 是 | 数据库文件名。 | +| securityLevel | [SecurityLevel](#securitylevel) | 是 | 设置数据库安全级别 | +| encrypt | boolean | 否 | 指定数据库是否加密。
true:加密。
false:非加密。 | + +## SecurityLevel + +数据库的安全级别枚举。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | +| S2 | 2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | +| S3 | 3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | +| S4 | 4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | + +## ValueType + +用于表示允许的数据字段类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 类型 | 说明 | +| ------- | -------------------- | +| number | 表示值类型为数字。 | +| string | 表示值类型为字符。 | +| boolean | 表示值类型为布尔值。 | + +## ValuesBucket + +用于存储键值对的类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 键类型 | 值类型 | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode + +指数据库同步模式。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | 表示数据从本地设备推送到远程设备。 | +| SYNC_MODE_PULL | 1 | 表示数据从远程设备拉至本地设备。 | + +## SubscribeType + +描述订阅类型。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | + +## ConflictResolution10+ + +插入和修改接口的冲突解决方式。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| -------------------- | ---- | ------------------------------------------------------------ | +| ON_CONFLICT_NONE | 0 | 表示当冲突发生时,不做任何处理。 | +| ON_CONFLICT_ROLLBACK | 1 | 表示当冲突发生时,中止SQL语句并回滚当前事务。 | +| ON_CONFLICT_ABORT | 2 | 表示当冲突发生时,中止当前SQL语句,并撤销当前 SQL 语句所做的任何更改,但是由同一事务中先前的 SQL 语句引起的更改被保留并且事务保持活动状态。 | +| ON_CONFLICT_FAIL | 3 | 表示当冲突发生时,中止当前 SQL 语句。但它不会撤销失败的 SQL 语句的先前更改,也不会结束事务。 | +| ON_CONFLICT_IGNORE | 4 | 表示当冲突发生时,跳过包含违反约束的行并继续处理 SQL 语句的后续行。 | +| ON_CONFLICT_REPLACE | 5 | 表示当冲突发生时,在插入或更新当前行之前删除导致约束违例的预先存在的行,并且命令会继续正常执行。 | + +## OpenStatus10+ + +RdbStore的状态枚举。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 值 | 说明 | +| --------- | ---- | --------------------------------------------------- | +| ON_CREATE | 0 | 表示RdbStore首次创建,处于ON_CREATE状态。 | +| ON_OPEN | 1 | 表示RdbStore非首次创建,处于ON_OPEN状态。 | + +## RdbPredicates + +表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 + +### constructor + +constructor(name: string) + +构造函数。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------ | +| name | string | 是 | 数据库表名。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices + +inDevices(devices: Array<string>): RdbPredicates + + +同步分布式数据库时连接到组网内指定的远程设备。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | 是 | 指定的组网内的远程设备ID。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices + +inAllDevices(): RdbPredicates + + +同步分布式数据库时连接到组网内所有的远程设备。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + + +配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo + +notEqualTo(field: string, value: ValueType): RdbPredicates + + +配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +向谓词添加左括号。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap + +endWrap(): RdbPredicates + +向谓词添加右括号。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or + +or(): RdbPredicates + +将或条件添加到谓词中。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +向谓词添加和条件。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains + +contains(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且value包含指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith + +beginsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith + +endsWith(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull + +isNull(field: string): RdbPredicates + +配置谓词以匹配值为null的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例**: + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +配置谓词以匹配值不为null的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like + +like(field: string, value: string): RdbPredicates + +配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob + +glob(field: string, value: string): RdbPredicates + +配置RdbPredicates匹配数据字段为string的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | 是 | 数据库表中的列名。 | +| value | string | 是 | 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| low | [ValueType](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan + +greaterThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan + +lessThan(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为valueType且value小于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +配置谓词以匹配其值按升序排序的列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +配置谓词以匹配其值按降序排序的列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct + +distinct(): RdbPredicates + +配置谓词以过滤重复记录并仅保留其中一个。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +设置最大数据记录数的谓词。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| value | number | 是 | 最大数据记录数。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs + +offsetAs(rowOffset: number): RdbPredicates + +配置RdbPredicates以指定返回结果的起始位置。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | 是 | 返回结果的起始位置,取值为正整数。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy + +groupBy(fields: Array<string>): RdbPredicates + +配置RdbPredicates按指定列分组查询结果。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | 是 | 指定分组依赖的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ---------------------- | +| [RdbPredicates](#rdbpredicates) | 返回分组查询列的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +配置RdbPredicates以指定索引列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------------- | +| field | string | 是 | 索引列的名称。 | + +**返回值**: + + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in + +in(field: string, value: Array<ValueType>): RdbPredicates + +配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | Array<[ValueType](#valuetype)> | 是 | 以ValueType数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore + +提供管理关系数据库(RDB)方法的接口。 + +在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)。 + +### 属性10+ + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ----------- | ---- | -------------------------------- | +| openStatus10+ | number | 是 | RdbStore的状态。值为0时,表示RdbStore首次创建,处于ON_CREATE状态。值为1时,表示RdbStore非首次创建,处于ON_OPEN状态。 | + +### insert + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +向目标表中插入一行数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Insert is failed"); + return; + } + console.log("Insert is successful, rowId = " + rowId); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +向目标表中插入一行数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (status, rowId) { + if (status) { + console.log("Insert is failed"); + return; + } + console.log("Insert is successful, rowId = " + rowId); +}) +``` + +### insert + +insert(table: string, values: ValuesBucket):Promise<number> + +向目标表中插入一行数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Insert is successful, rowId = " + rowId); +}).catch((status) => { + console.log("Insert is failed"); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise<number> + +向目标表中插入一行数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then((rowId) => { + console.log("Insert is successful, rowId = " + rowId); +}).catch((status) => { + console.log("Insert is failed"); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +向目标表中插入一组数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("batchInsert is failed, status = " + status); + return; + } + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +向目标表中插入一组数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**示例:** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("batchInsert is failed, status = " + status); +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Updated failed, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { + if (err) { + console.info("Updated failed, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Updated failed, err: " + err) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise<number> + +根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**示例:** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Updated failed, err: " + err) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +根据DataSharePredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Updated failed, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Updated failed, err: " + err) +}) +``` + +### delete + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.delete(predicates, function (err, rows) { + if (err) { + console.info("Delete failed, err: " + err) + return + } + console.log("Delete rows: " + rows) +}) +``` + +### delete + +delete(predicates: RdbPredicates):Promise<number> + +根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) +}).catch((err) => { + console.info("Delete failed, err: " + err) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.info("Delete failed, err: " + err) + return + } + console.log("Delete rows: " + rows) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Delete rows: " + rows) +}).catch((err) => { + console.info("Delete failed, err: " + err) +}) +``` + +### query + +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +根据指定条件查询数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> + +根据指定条件查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + + ```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) + ``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +根据指定条件查询数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +根据指定条件查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**系统接口:** 此接口为系统接口。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +根据指定条件查询远程设备数据库中的数据。使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSet){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | 是 | 指定的远程设备的networkId。 | +| table | string | 是 | 指定的目标表名。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void + +根据指定SQL语句查询数据库中的数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { + if (err) { + console.info("Query failed, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### querySql + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> + +根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```js +let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Query failed, err: " + err) +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 是 | SQL语句中参数的值。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```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)" +rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("ExecuteSql failed, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | 是 | 指定要执行的SQL语句。 | +| bindArgs | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```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)" +let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("ExecuteSql failed, err: " + err) +}) +``` + +### beginTransaction + +beginTransaction():void + +在开始执行SQL语句之前,开始事务。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### commit + +commit():void + +提交已执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### rollBack + +rollBack():void + +回滚已经执行的SQL语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +}) +``` + +### backup + +backup(destName:string, callback: AsyncCallback<void>):void + +以指定名称备份数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup + +backup(destName:string): Promise<void> + +以指定名称备份数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| destName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore + +restore(srcName:string, callback: AsyncCallback<void>):void + +从指定的数据库备份文件恢复数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore + +restore(srcName:string): Promise<void> + +从指定的数据库备份文件恢复数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | 是 | 指定数据库的备份文件名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +设置分布式列表,使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | 是 | 要设置的分布式列表表名 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**示例:** + +```js +rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.info('SetDistributedTables failed, err: ' + err) + return + } + console.info('SetDistributedTables successfully.') +}) +``` + +### setDistributedTables + + setDistributedTables(tables: Array<string>): Promise<void> + +设置分布式列表,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | 是 | 要设置的分布式列表表名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```js +let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("SetDistributedTables successfully.") +}).catch((err) => { + console.info("SetDistributedTables failed, err: " + err) +}) +``` + +### obtainDistributedTableName + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | 是 | 远程设备 。 | +| table | string | 是 | 本地表名。 | +| callback | AsyncCallback<string> | 是 | 指定的callback回调函数。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('ObtainDistributedTableName failed, err: ' + err) + return + } + console.info('ObtainDistributedTableName successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName + + obtainDistributedTableName(device: string, table: string): Promise<string> + +根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------- | +| device | string | 是 | 远程设备。 | +| table | string | 是 | 本地表名。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise对象。如果操作成功,返回远程设备的分布式表名。 | + +**示例:** + +```js +let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('ObtainDistributedTableName successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('ObtainDistributedTableName failed, err: ' + err) +}) +``` + +### sync + +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void + +在设备之间同步数据, 使用callback异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | 约束同步数据和设备。 | +| callback | AsyncCallback<Array<[string, number]>> | 是 | 指定的callback回调函数,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { + if (err) { + console.log('Sync failed, err: ' + err) + return + } + console.log('Sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } +}) +``` + +### sync + + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> + +在设备之间同步数据,使用Promise异步回调。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode) | 是 | 指同步模式。该值可以是推、拉。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | 约束同步数据和设备。 | + +**返回值**: + +| 类型 | 说明 | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise对象,用于向调用者发送同步结果。string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | + +**示例:** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) +promise.then((resultSet) =>{ + console.log('Sync done.') + for (let i = 0; i < resultSet.length; i++) { + console.log('device=' + resultSet[i][0] + ' status=' + resultSet[i][1]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype) | 是 | 订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指分布式数据库中数据更改事件的观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Register observer failed') +} +``` + +### off('dataChange') + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +从数据库中删除指定类型的指定观察者, 使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------- | ---- | ------------------------------------------ | +| event | string | 是 | 取值为'dataChange',表示数据更改。 | +| type | [SubscribeType](#subscribetype) | 是 | 订阅类型。 | +| observer | Callback<Array<string>> | 是 | 指已注册的数据更改观察者。 | + +**示例:** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Unregister observer failed') +} +``` + +## ResultSet + +提供通过查询数据库生成的数据库结果集的访问方法。结果集是指用户调用关系型数据库查询接口之后返回的结果集合,提供了多种灵活的数据访问方式,以便用户获取各项数据。 + +### 使用说明 + +需要通过[RdbStore.query()](#query)获取resultSet对象。 + +```js +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +predicates.equalTo("AGE", 18); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); +``` + +### 属性 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | 是 | 获取结果集中所有列的名称。 | +| columnCount | number | 是 | 获取结果集中的列数。 | +| rowCount | number | 是 | 获取结果集中的行数。 | +| rowIndex | number | 是 | 获取结果集当前行的索引。 | +| isAtFirstRow | boolean | 是 | 检查结果集是否位于第一行。 | +| isAtLastRow | boolean | 是 | 检查结果集是否位于最后一行。 | +| isEnded | boolean | 是 | 检查结果集是否位于最后一行之后。 | +| isStarted | boolean | 是 | 检查指针是否移动过。 | +| isClosed | boolean | 是 | 检查当前结果集是否关闭。 | + +### getColumnIndex + +getColumnIndex(columnName: string): number + +根据指定的列名获取列索引。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | 是 | 表示结果集中指定列的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 返回指定列的索引。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +resultSet.goToFirstRow(); +const id = resultSet.getLong(resultSet.getColumnIndex("ID")); +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### getColumnName + +getColumnName(columnIndex: number): string + +根据指定的列索引获取列名。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | 是 | 表示结果集中指定列的索引。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| string | 返回指定列的名称。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const id = resultSet.getColumnName(0); +const name = resultSet.getColumnName(1); +const age = resultSet.getColumnName(2); + ``` + +### goTo + +goTo(offset:number): boolean + +向前或向后转至结果集的指定行,相对于其当前位置偏移。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | 是 | 表示相对于当前位置的偏移量。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goTo(1); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow + +goToRow(position: number): boolean + +转到结果集的指定行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| position | number | 是 | 表示要移动到的指定位置。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.(5); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow + +goToFirstRow(): boolean + + +转到结果集的第一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToFirstRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow + +goToLastRow(): boolean + +转到结果集的最后一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToLastRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow + +goToNextRow(): boolean + +转到结果集的下一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToNextRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +转到结果集的上一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToPreviousRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +以字节数组的形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------------------- | +| Uint8Array | 以字节数组的形式返回指定列的值。 | + +**示例:** + + ```js +const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); + ``` + +### getString + +getString(columnIndex: number): string + +以字符串形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| string | 以字符串形式返回指定列的值。 | + +**示例:** + + ```js +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + ``` + +### getLong + +getLong(columnIndex: number): number + +以Long形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------------- | +| number | 以Long形式返回指定列的值。 | + +**示例:** + + ```js +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + ``` + +### getDouble + +getDouble(columnIndex: number): number + +以double形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ---------------------------- | +| number | 以double形式返回指定列的值。 | + +**示例:** + + ```js +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +检查当前行中指定列的值是否为null。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------------------- | +| boolean | 如果当前行中指定列的值为null,则返回true,否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + + ```js +const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); + ``` + +### close + +close(): void + +关闭结果集。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + + ```js +let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); +let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSet) => { + resultSet.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md index a54d63f77393df9988887fc17877a4e4d4bf3cc5..a556ae2da71a5e4f4e4862dc015ae82c792a852c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @@ -5,545 +5,13 @@ > **说明:** > > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 从API Version 9开始,该接口不再维护,推荐使用新接口[@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset)。 -## ResultSetV99+ - -提供通过查询数据库生成的数据库结果集的访问方法。 - -### 使用说明 - -需要通过[RdbStoreV9.query()](js-apis-data-rdb.md#query)获取resultSetV9对象。 - -```js -import dataRdb from '@ohos.data.rdb'; -let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -predicatesV9.equalTo("AGE", 18); -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSetV9) => { - console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); -}); -``` - -### 属性9+ - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -| 名称 | 类型 | 必填 | 说明 | -| ------------ | ------------------- | ---- | -------------------------------- | -| columnNames | Array<string> | 是 | 获取结果集中所有列的名称。 | -| columnCount | number | 是 | 获取结果集中的列数。 | -| rowCount | number | 是 | 获取结果集中的行数。 | -| rowIndex | number | 是 | 获取结果集当前行的索引。 | -| isAtFirstRow | boolean | 是 | 检查结果集是否位于第一行。 | -| isAtLastRow | boolean | 是 | 检查结果集是否位于最后一行。 | -| isEnded | boolean | 是 | 检查结果集是否位于最后一行之后。 | -| isStarted | boolean | 是 | 检查指针是否移动过。 | -| isClosed | boolean | 是 | 检查当前结果集是否关闭。 | - -### getColumnIndex9+ - -getColumnIndex(columnName: string): number - -根据指定的列名获取列索引。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | -------------------------- | -| columnName | string | 是 | 表示结果集中指定列的名称。 | - -**返回值:** - -| 类型 | 说明 | -| ------ | ------------------ | -| number | 返回指定列的索引。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -resultSetV9.goToFirstRow(); -const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### getColumnName9+ - -getColumnName(columnIndex: number): string - -根据指定的列索引获取列名。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | -------------------------- | -| columnIndex | number | 是 | 表示结果集中指定列的索引。 | - -**返回值:** - -| 类型 | 说明 | -| ------ | ------------------ | -| string | 返回指定列的名称。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const id = resultSetV9.getColumnName(0); -const name = resultSetV9.getColumnName(1); -const age = resultSetV9.getColumnName(2); - ``` - -### goTo9+ - -goTo(offset:number): boolean - -向前或向后转至结果集的指定行,相对于其当前位置偏移。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ---------------------------- | -| offset | number | 是 | 表示相对于当前位置的偏移量。 | - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoto.then((resultSetV9) => { - resultSetV9.goTo(1); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToRow9+ - -goToRow(position: number): boolean - -转到结果集的指定行。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------------------ | -| position | number | 是 | 表示要移动到的指定位置。 | - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygotorow.then((resultSetV9) => { - resultSetV9.goToRow(5); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToFirstRow9+ - -goToFirstRow(): boolean - - -转到结果集的第一行。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoFirst.then((resultSetV9) => { - resultSetV9.goToFirstRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToLastRow9+ - -goToLastRow(): boolean - -转到结果集的最后一行。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoLast.then((resultSetV9) => { - resultSetV9.goToLastRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToNextRow9+ - -goToNextRow(): boolean - -转到结果集的下一行。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoNext.then((resultSetV9) => { - resultSetV9.goToNextRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToPreviousRow9+ - -goToPreviousRow(): boolean - -转到结果集的上一行。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------- | -| boolean | 如果成功移动结果集,则为true;否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**示例:** - - ```js -let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoPrev.then((resultSetV9) => { - resultSetV9.goToPreviousRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### getBlob9+ - -getBlob(columnIndex: number): Uint8Array - -以字节数组的形式获取当前行中指定列的值。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | 是 | 指定的列索引,从0开始。 | - -**返回值:** - -| 类型 | 说明 | -| ---------- | -------------------------------- | -| Uint8Array | 以字节数组的形式返回指定列的值。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); - ``` - -### getString9+ - -getString(columnIndex: number): string - -以字符串形式获取当前行中指定列的值。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | 是 | 指定的列索引,从0开始。 | - -**返回值:** - -| 类型 | 说明 | -| ------ | ---------------------------- | -| string | 以字符串形式返回指定列的值。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); - ``` - -### getLong9+ - -getLong(columnIndex: number): number - -以Long形式获取当前行中指定列的值。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | 是 | 指定的列索引,从0开始。 | - -**返回值:** - -| 类型 | 说明 | -| ------ | -------------------------- | -| number | 以Long形式返回指定列的值。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); - ``` - -### getDouble9+ - -getDouble(columnIndex: number): number - -以double形式获取当前行中指定列的值。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | 是 | 指定的列索引,从0开始。 | - -**返回值:** - -| 类型 | 说明 | -| ------ | ---------------------------- | -| number | 以double形式返回指定列的值。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### isColumnNull9+ - -isColumnNull(columnIndex: number): boolean - -检查当前行中指定列的值是否为null。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | 是 | 指定的列索引,从0开始。 | - -**返回值:** - -| 类型 | 说明 | -| ------- | --------------------------------------------------------- | -| boolean | 如果当前行中指定列的值为null,则返回true,否则返回false。 | - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**示例:** - - ```js -const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); - ``` - -### close9+ - -close(): void - -关闭结果集。 - -**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core - -**示例:** - - ```js -let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSetV9) => { - resultSetV9.close(); -}).catch((err) => { - console.log('resultset close failed'); -}); - ``` - -**错误码:** - -以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 - -| **错误码ID** | **错误信息** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -## ResultSet(deprecated) +## ResultSet 提供通过查询数据库生成的数据库结果集的访问方法。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[ResultSetV9](#resultsetv99)替代。 - ### 使用说明 需要通过[RdbStore.query()](js-apis-data-rdb.md#query)获取resultSet对象。 @@ -559,11 +27,7 @@ promise.then((resultSet) => { }); ``` -### 属性(deprecated) - -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[属性](#属性9)替代。 +### 属性 **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core @@ -579,16 +43,12 @@ promise.then((resultSet) => { | isStarted | boolean | 是 | 检查指针是否移动过。 | | isClosed | boolean | 是 | 检查当前结果集是否关闭。 | -### getColumnIndex(deprecated) +### getColumnIndex getColumnIndex(columnName: string): number 根据指定的列名获取列索引。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnIndex](#getcolumnindex9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -613,16 +73,12 @@ getColumnIndex(columnName: string): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName(deprecated) +### getColumnName getColumnName(columnIndex: number): string 根据指定的列索引获取列名。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnName](#getcolumnname9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -645,16 +101,12 @@ getColumnName(columnIndex: number): string const age = resultSet.getColumnName(2); ``` -### goTo(deprecated) +### goTo goTo(offset:number): boolean 向前或向后转至结果集的指定行,相对于其当前位置偏移。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goTo](#goto9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -682,16 +134,12 @@ goTo(offset:number): boolean }); ``` -### goToRow(deprecated) +### goToRow goToRow(position: number): boolean 转到结果集的指定行。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToRow](#gotorow9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -719,16 +167,12 @@ goToRow(position: number): boolean }); ``` -### goToFirstRow(deprecated) +### goToFirstRow goToFirstRow(): boolean 转到结果集的第一行。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToFirstRow](#gotofirstrow9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -750,16 +194,12 @@ goToFirstRow(): boolean }); ``` -### goToLastRow(deprecated) +### goToLastRow goToLastRow(): boolean 转到结果集的最后一行。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToLastRow](#gotolastrow9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -781,16 +221,12 @@ goToLastRow(): boolean }); ``` -### goToNextRow(deprecated) +### goToNextRow goToNextRow(): boolean 转到结果集的下一行。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToNextRow](#gotonextrow9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -812,16 +248,12 @@ goToNextRow(): boolean }); ``` -### goToPreviousRow(deprecated) +### goToPreviousRow goToPreviousRow(): boolean 转到结果集的上一行。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToPreviousRow](#gotopreviousrow9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **返回值:** @@ -843,16 +275,12 @@ goToPreviousRow(): boolean }); ``` -### getBlob(deprecated) +### getBlob getBlob(columnIndex: number): Uint8Array 以字节数组的形式获取当前行中指定列的值。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getBlob](#getblob9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -873,16 +301,12 @@ getBlob(columnIndex: number): Uint8Array const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString(deprecated) +### getString getString(columnIndex: number): string 以字符串形式获取当前行中指定列的值。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getString](#getstring9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -903,16 +327,12 @@ getString(columnIndex: number): string const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong(deprecated) +### getLong getLong(columnIndex: number): number 以Long形式获取当前行中指定列的值。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getLong](#getlong9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -933,16 +353,12 @@ getLong(columnIndex: number): number const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble(deprecated) +### getDouble getDouble(columnIndex: number): number 以double形式获取当前行中指定列的值。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getDouble](#getdouble9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -963,16 +379,12 @@ getDouble(columnIndex: number): number const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull(deprecated) +### isColumnNull isColumnNull(columnIndex: number): boolean 检查当前行中指定列的值是否为null。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[isColumnNull](#iscolumnnull9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **参数:** @@ -993,16 +405,12 @@ isColumnNull(columnIndex: number): boolean const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close(deprecated) +### close close(): void 关闭结果集。 -> **说明:** -> -> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[close](#close9)替代。 - **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md index 5e0784c672fede2fc0e66d665176a12e02fd157f..17779dc827bbfde193ca2cc19e5c33bf9ff629f7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md +++ b/zh-cn/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -1,8 +1,8 @@ # FormExtensionContext -FormExtensionContext模块是FormExtension的上下文环境,继承自ExtensionContext。 +FormExtensionContext模块是FormExtensionAbility的上下文环境,继承自ExtensionContext。 -FormExtensionContext模块提供FormExtension具有的接口和能力。 +FormExtensionContext模块提供FormExtensionAbility具有的接口和能力。 > **说明:** > @@ -11,23 +11,24 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。 ## 使用说明 -在使用FormExtensionContext的功能前,需要通过FormExtension获取。 +在使用FormExtensionContext的功能前,需要通过FormExtensionAbility获取。 ```ts import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import formBindingData from '@ohos.app.form.formBindingData'; + export default class MyFormExtensionAbility extends FormExtensionAbility { - onAddForm() { - let formContext = this.context; // 获取FormExtensionContext - // ... - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} + onAddForm(want) { + let formContext = this.context; // 获取FormExtensionContext + // ... + let dataObj1 = { + temperature: "11c", + "time": "11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +}; ``` ## startAbility @@ -50,23 +51,29 @@ startAbility(want: Want, callback: AsyncCallback<void>): void **示例:** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want, (error, data) => { - if (error) { - console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); - } else { - console.log(`FormExtensionContext startAbility success`); - } -}) +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // 当触发卡片message事件时,执行startAbility + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "MainAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want, (error, data) => { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log('FormExtensionContext startAbility success'); + } + }); + } +}; ``` ## startAbility @@ -89,24 +96,30 @@ startAbility(want: Want): Promise<void> | 类型 | 说明 | | ------------ | ---------------------------------- | -| Promise<void< | 无返回结果的Promise对象。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** ```ts -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); -}).catch((error) => { - console.info("StartAbility failed"); -}); +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // 当触发卡片message事件时,执行startAbility + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "MainAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want).then(() => { + console.info("StartAbility Success"); + }).catch((error) => { + console.info("StartAbility failed"); + }); + } +}; ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md index 912fbf127bff109c6b29d84c8b658509d4921959..ede65b4423d427eeab3615a47c90b97f86d6e186 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -275,7 +275,7 @@ let result = lightWeightMap.get("sparrow"); getIndexOfKey(key: K): number -查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 +查找key元素第一次出现的下标值,如果没有找到该元素返回-1。 **系统能力:** SystemCapability.Utils.Lang @@ -289,7 +289,7 @@ getIndexOfKey(key: K): number | 类型 | 说明 | | -------- | -------- | -| number | 返回指定元素第一次出现时的下标值,查找失败返回-1。 | +| number | 返回key元素第一次出现时的下标值,查找失败返回-1。 | **错误码:** @@ -313,7 +313,7 @@ let result = lightWeightMap.getIndexOfKey("sparrow"); getIndexOfValue(value: V): number -查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 +查找value元素第一次出现的下标值,如果没有找到该元素返回-1。 **系统能力:** SystemCapability.Utils.Lang @@ -327,7 +327,7 @@ getIndexOfValue(value: V): number | 类型 | 说明 | | -------- | -------- | -| number | 返回指定元素第一次出现时的下标值,查找失败返回-1。 | +| number | 返回value元素第一次出现时的下标值,查找失败返回-1。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md index f216067bbc4604d56abf7c4b757dad6b19df3fbf..7a9eaabb026f8513589b8d5854ebc4cc06522c1b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,4 +1,4 @@ -# @ohos.util.LightWeightSet (非线性容器LightWeightSet)@ohos.util.LightWeightSet (非线性容器LightWeightSet) +# @ohos.util.LightWeightSet (非线性容器LightWeightSet) > **说明:** > 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md index fd09fcdb427fab0839e3b7aa5ad976f26d1dc885..b6c47634264863083e9a81d534c526b638fa1411 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -7,7 +7,7 @@ LinkedList底层通过双向链表实现,双向链表的每个节点都包含 LinkedList和[List](js-apis-list.md)相比,LinkedList是双向链表,可以快速地在头尾进行增删,而List是单向链表,无法双向操作。 -LinkedList和[ArrayList](js-apis-arraylist.md)相比,存取数据的效率不如ArrayList。 +LinkedList和[ArrayList](js-apis-arraylist.md)相比,插入数据效率LinkedList优于ArrayList,而查询效率ArrayList优于LinkedList。 **推荐使用场景:** 当需要频繁的插入删除时,推荐使用LinkedList高效操作。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md index c7847c749b6da20bfa7b345a4c64d89e7d7a15df..60535897fdd5b43b9b79e641a6ed67f53a307a29 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-list.md +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -15,7 +15,7 @@ List和[LinkedList](js-apis-linkedlist.md)相比,LinkedList是双向链表, ## 导入模块 ```ts -import List from '@ohos.util.List'; +import List from '@ohos.util.List'; ``` @@ -546,8 +546,8 @@ list.add(2); list.add(4); list.add(5); list.add(4); -list.sort((a: number, b: number) => a - b); -list.sort((a: number, b: number) => b - a); +list.sort((a: number, b: number) => a - b); // 结果为升序排列 +list.sort((a: number, b: number) => b - a); // 结果为降序排列 ``` ### getSubList diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md index 9aa58d239b0f5945356f76f12908b71ba120874c..61eaf7a1f035fabaccf9e265360dc8dc4010c838 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -242,7 +242,7 @@ let result = plainArray.getIndexOfValue("squirrel"); getKeyAt(index: number): number -查找指定下标的元素键值对中key值。 +查找指定下标元素键值对中的key值。 **系统能力:** SystemCapability.Utils.Lang @@ -256,7 +256,7 @@ getKeyAt(index: number): number | 类型 | 说明 | | -------- | -------- | -| number | 返回该下标对应的元素键值对中key值,失败返回-1。 | +| number | 返回该下标元素键值对中的key值,失败返回-1。 | **错误码:** @@ -279,7 +279,7 @@ let result = plainArray.getKeyAt(1); getValueAt(index: number): T -查找指定下标元素键值对中Value值,否则返回undefined。 +查找指定下标元素键值对中的Value值,失败返回undefined。 **系统能力:** SystemCapability.Utils.Lang @@ -293,7 +293,7 @@ getValueAt(index: number): T | 类型 | 说明 | | -------- | -------- | - | T | 返回该下标对应的元素键值对中key值,失败返回undefined。 | + | T | 返回该下标元素键值对中的value值,失败返回undefined。 | **错误码:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index 5b8172b9062acdf39530aa73eb7bffd4c2b61f63..a24fee456db549f237f499346f916b8fcac4ef3d 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -78,8 +78,8 @@ delete(name: string): void ```js let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsobject = new Url.URLParams(urlObject.search.slice(1)); -paramsobject.delete('fod'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.delete('fod'); ``` @@ -87,7 +87,7 @@ paramsobject.delete('fod'); getAll(name: string): string[] -获取指定名称的所有键值对。 +获取指定名称的所有键对应值的集合。 **系统能力:** SystemCapability.Utils.Lang @@ -101,7 +101,7 @@ getAll(name: string): string[] | 类型 | 说明 | | -------- | -------- | -| string[] | 返回指定名称的所有键值对。 | +| string[] | 返回指定名称的所有键对应值的集合。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb.md b/zh-cn/application-dev/reference/apis/js-apis-usb.md index d0331a03cdd608b1dd7bd467af0ff552e9e51ab5..827b7fb62a07a5ac57bda59fb2b8ef51e4936693 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usb.md @@ -585,7 +585,7 @@ let ret = usb.usbFunctionsToString(funcs); ## usb.setCurrentFunctions -setCurrentFunctions(funcs: FunctionType): Promise\ +setCurrentFunctions(funcs: FunctionType): Promise\ 在设备模式下,设置当前的USB功能列表。 @@ -601,15 +601,19 @@ setCurrentFunctions(funcs: FunctionType): Promise\ **返回值:** -| 类型 | 说明 | -| ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise对象,返回设置成功与否的结果。true表示设置成功,false表示设置失败。 | +| 类型 | 说明 | +| --------------- | ------------- | +| Promise\ | Promise对象。 | **示例:** ```js let funcs = HDC; -let ret = usb.setCurrentFunctions(funcs); +usb.setCurrentFunctions(funcs).then(() => { + console.info('usb setCurrentFunctions successfully.'); +}).catch(err => { + console.error('usb setCurrentFunctions failed: ' + err.code + ' message: ' + err.message); +}); ``` ## usb.getCurrentFunctions @@ -686,7 +690,7 @@ let ret = usb.getSupportedModes(0); ## usb.setPortRoles -setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ +setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ 设置指定的端口支持的角色模式,包含充电角色、数据传输角色。 @@ -704,14 +708,19 @@ setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): **返回值:** -| 类型 | 说明 | -| ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise对象,返回设置成功与否的结果。true表示设置成功,false表示设置失败。 | +| 类型 | 说明 | +| --------------- | ------------- | +| Promise\ | Promise对象。 | **示例:** ```js -let ret = usb.getSupportedModes(0); +let portId = 1; +usb.usb.setPortRoles(portId, usb.PowerRoleType.SOURCE, usb.DataRoleType.HOST).then(() => { + console.info('usb setPortRoles successfully.'); +}).catch(err => { + console.error('usb setPortRoles failed: ' + err.code + ' message: ' + err.message); +}); ``` ## USBEndpoint diff --git a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md index 7a67ad66eb81f3aca814479cbe1c3d2482f06295..0ffb8c8275efcce862ca1ae1054d9233bf26a697 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @@ -24,7 +24,7 @@ getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------------------------- | ---- | ----------------------- | -| info | WantAgentInfo | 是 | WantAgent信息。 | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | 是 | WantAgent信息。 | | callback | AsyncCallback\ | 是 | 创建WantAgent的回调方法。 | **示例:** @@ -34,27 +34,31 @@ import WantAgent from '@ohos.wantAgent'; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + if (err.code) { + console.info('getWantAgent Callback err:' + JSON.stringify(err)) + } else { + console.info('getWantAgent Callback success') + } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -64,7 +68,7 @@ var wantAgentInfo = { wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); ``` @@ -81,7 +85,7 @@ getWantAgent(info: WantAgentInfo): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ---- | ------------- | ---- | ------------- | -| info | WantAgentInfo | 是 | WantAgent信息。 | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | 是 | WantAgent信息。 | **返回值:** @@ -96,24 +100,24 @@ import WantAgent from '@ohos.wantAgent'; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -124,7 +128,7 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); }); ``` @@ -152,11 +156,11 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -164,24 +168,24 @@ function getWantAgentCallback(err, data) { } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -195,9 +199,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) //getBundleName回调 function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); } -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -228,27 +232,27 @@ getBundleName(agent: WantAgent): Promise\ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -259,12 +263,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); }); ``` @@ -292,11 +296,11 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -304,24 +308,24 @@ function getWantAgentCallback(err, data) { } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -335,9 +339,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) //getUid回调 function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); } -WantAgent.getUid(wantAgent, getUidCallback) +WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -369,27 +373,27 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -400,162 +404,16 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); }); ``` - -## WantAgent.getWant - -getWant(agent: WantAgent, callback: AsyncCallback\): void - -获取WantAgent对象的want(callback形式)。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ---- | ------------------------------- | -| agent | WantAgent | 是 | WantAgent对象。 | -| callback | AsyncCallback\ | 是 | 获取WantAgent对象want的回调方法。 | - -**示例:** - -```ts -import WantAgent from '@ohos.wantAgent'; - - -//wantAgent对象 -var wantAgent; - -//getWantAgent回调 -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -//WantAgentInfo对象 -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -//getWant回调 -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent): Promise\ - -获取WantAgent对象的want(Promise形式)。 - -**系统能力**:SystemCapability.Ability.AbilityRuntime.Core - -**系统API**: 此接口为系统接口,三方应用不支持调用。 - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ----- | --------- | ---- | ------------- | -| agent | WantAgent | 是 | WantAgent对象。 | - -**返回值:** - -| 类型 | 说明 | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | 以Promise形式返回获取WantAgent对象的want。 | - -**示例:** - -```ts -import WantAgent from '@ohos.wantAgent'; - - -//wantAgent对象 -var wantAgent; - -//WantAgentInfo对象 -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); - -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); -}); -``` - - - ## WantAgent.cancel cancel(agent: WantAgent, callback: AsyncCallback\): void @@ -578,11 +436,11 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -590,24 +448,24 @@ function getWantAgentCallback(err, data) { } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -621,9 +479,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) //cancel回调 function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); } -WantAgent.cancel(wantAgent, cancelCallback) +WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -655,27 +513,27 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -686,12 +544,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); }); ``` @@ -720,11 +578,11 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -732,24 +590,24 @@ function getWantAgentCallback(err, data) { } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -763,7 +621,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) //trigger回调 function triggerCallback(data) { - console.info("==========================>triggerCallback=======================>"); + console.info('==========================>triggerCallback=======================>'); } var triggerInfo = { @@ -778,7 +636,7 @@ WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -判断两个WantAgent实例是否相等(callback形式)。 +判断两个WantAgent实例是否相等(callback形式),以此来判断是否是来自同一应用的相同操作。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -797,12 +655,12 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; //getWantAgent回调 function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent1 = data; wantAgent2 = data; @@ -811,24 +669,24 @@ function getWantAgentCallback(err, data) { } } //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -842,7 +700,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) //equal回调 function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); } WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -853,7 +711,7 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback) equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -判断两个WantAgent实例是否相等(Promise形式)。 +判断两个WantAgent实例是否相等(Promise形式),以此来判断是否是来自同一应用的相同操作。 **系统能力**:SystemCapability.Ability.AbilityRuntime.Core @@ -877,28 +735,28 @@ import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -909,13 +767,13 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); }); ``` @@ -940,27 +798,27 @@ getOperationType(agent: WantAgent, callback: AsyncCallback\): void; import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -971,7 +829,7 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); @@ -1006,27 +864,27 @@ getOperationType(agent: WantAgent): Promise\; import WantAgent from '@ohos.wantAgent'; //wantAgent对象 -var wantAgent; +let wantAgent; //WantAgentInfo对象 -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.MainAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1037,15 +895,14 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + WantAgent.getOperationType(wantAgent).then((OperationType) => { + console.log('getOperationType success, OperationType: ' + OperationType); + }).catch((err) => { + console.log('getOperationType fail, err: ' + err); + }) }); - -WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); -}).catch((err) => { - console.log('getOperationType fail, err: ' + err); -}) ``` diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md b/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md index ad8fb47ea9149b0bf14fd1907c681f4b1a76a613..c387747a3624faee64a3540945112c879c8a073f 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @@ -70,7 +70,7 @@ Not found. **可能原因** -在调用删除数据库、数据查询、数据删除等接口时未找到相关数据,可能原因如下。 +在调用删除数据库、数据查询、数据同步等接口时未找到相关数据,可能原因如下。 1. 删除数据库操作时,数据库不存在或已删除。 2. 数据库数据查询操作时,相关数据不存在或已删除。 3. 数据库数据同步操作时,数据库不存在或已删除。 diff --git a/zh-cn/application-dev/security/permission-verify-guidelines.md b/zh-cn/application-dev/security/permission-verify-guidelines.md index 5f738e40c602a18331b4abcb0d529e756a9d32e4..f36c97d7b88ad29230df4cd600d802e22b96c50a 100644 --- a/zh-cn/application-dev/security/permission-verify-guidelines.md +++ b/zh-cn/application-dev/security/permission-verify-guidelines.md @@ -18,6 +18,8 @@ 进行权限校验的开发步骤为: 1. 获取调用者的身份标识:tokenId。 + > **说明:**
+ > 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。 2. 待校验的权限名:ohos.permission.PERMISSION。 3. 使用verifyAccessToken接口对当前调用者进行权限校验。 4. 根据权限校验结果采取对应的措施。 @@ -42,5 +44,3 @@ } ``` -> **说明:** -> 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。 \ No newline at end of file diff --git a/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md new file mode 100644 index 0000000000000000000000000000000000000000..3308c108cee6092ab70333ecd33f6ba9864362a1 --- /dev/null +++ b/zh-cn/release-notes/changelogs/OpenHarmony_3.2.10.3/changelogs-camera-sync.md @@ -0,0 +1,522 @@ +# 媒体子系统 JS API 变更 Changelog + +OpenHarmony3.2.10.3 相对 OpenHarmony3.2 Beta4 版本,媒体子系统 camera 部件 API 变更如下 + +## cl.subsystemname.1 camera 接口变更 + +基于以下原因新增部分功能接口以及废弃部分接口: + +1. 提升开发者使用相机接口的便利。 +2. 帮助开发者快速掌握相机开发接口,快速投入到开发当中。 +3. 易于后续版本中框架功能的扩展,降低框架模块之间的耦合度。 + +具体参考下方变更内容,开发者需要根据以下说明对应用进行适配。 + +**变更影响** + +影响 API9 版本的 JS 接口,应用需要进行适配才可以在新版本 SDK 环境正常实现功能。 + +**关键的接口/组件变更** + +| 模块名 | 类名 | 方法/属性/枚举/常量 | 是否为 SystemApi | 变更类型 | +| ---------------------- | ----------------------- | ------------------------------------------------------------ | --------------- | -------- | +| ohos.multimedia.camera | camera | function getCameraManager(context: Context): CameraManager; | 是 | 新增 | +| ohos.multimedia.camera | camera | function getCameraManager(context: Context, callback: AsyncCallback): void;
function getCameraManager(context: Context): Promise; | 是 | 废弃 | +| ohos.multimedia.camera | CameraErrorCode | INVALID_ARGUMENT = 7400101,
OPERATION_NOT_ALLOWED = 7400102,
SESSION_NOT_CONFIG = 7400103,
SESSION_NOT_RUNNING = 7400104,
SESSION_CONFIG_LOCKED = 7400105,
DEVICE_SETTING_LOCKED = 7400106,
CONFILICT_CAMERA = 7400107,
DEVICE_DISABLED = 7400108,
SERVICE_FATAL_ERROR = 7400201 | 是 | 新增 | +| ohos.multimedia.camera | CameraManager | getSupportedCameras(): Array;
getSupportedOutputCapability(camera: CameraDevice): CameraOutputCapability;
createCameraInput(camera: CameraDevice): CameraInput;
createCameraInput(position: CameraPosition, type: CameraType): CameraInput;
createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput;
createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput;
createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput;
createMetadataOutput(metadataObjectTypes: Array): MetadataOutput;
createCaptureSession(): CaptureSession; | 是 | 新增 | +| ohos.multimedia.camera | CameraManager | getSupportedCameras(callback: AsyncCallback>): void;
getSupportedCameras(): Promise>;
getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback): void;
getSupportedOutputCapability(camera: CameraDevice): Promise;
createCameraInput(camera: CameraDevice, callback: AsyncCallback): void;
createCameraInput(camera: CameraDevice): Promise;
createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void;
createCameraInput(position: CameraPosition, type: CameraType): Promise;
createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void;
createPreviewOutput(profile: Profile, surfaceId: string): Promise;
createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void;
createPhotoOutput(profile: Profile, surfaceId: string): Promise;
createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void;
createVideoOutput(profile: VideoProfile, surfaceId: string): Promise;
createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void;
createMetadataOutput(metadataObjectTypes: Array): Promise;
createCaptureSession(callback: AsyncCallback): void;
createCaptureSession(): Promise; | 是 | 废弃 | +| ohos.multimedia.camera | CameraType | CAMERA_TYPE_DEFAULT = 0 | 是 | 新增 | +| ohos.multimedia.camera | CameraType | CAMERA_TYPE_UNSPECIFIED = 0 | 是 | 废弃 | +| ohos.multimedia.camera | CameraInput | on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | CameraInput | release(callback: AsyncCallback): void;
release(): Promise;
on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | CameraInputErrorCode | ERROR_UNKNOWN = -1
ERROR_NO_PERMISSION = 0
ERROR_DEVICE_PREEMPTED = 1
ERROR_DEVICE_DISCONNECTED = 2
ERROR_DEVICE_IN_USE = 3
ERROR_DRIVER_ERROR = 4 | 是 | 废弃 | +| ohos.multimedia.camera | CameraInputError | code: CameraInputErrorCode | 是 | 废弃 | +| ohos.multimedia.camera | CaptureSession | beginConfig(): void;
addInput(cameraInput: CameraInput): void;
removeInput(cameraInput: CameraInput): void;
addOutput(cameraOutput: CameraOutput): void;
removeOutput(cameraOutput: CameraOutput): void;
hasFlash(): boolean;
isFlashModeSupported(flashMode: FlashMode): boolean;
getFlashMode(): FlashMode;
setFlashMode(flashMode: FlashMode): void;
isExposureModeSupported(aeMode: ExposureMode): boolean;
getExposureMode(): ExposureMode;
setExposureMode(aeMode: ExposureMode): void;
getMeteringPoint(): Point;
setMeteringPoint(point: Point): void;
getExposureBiasRange(): Array;
setExposureBias(exposureBias: number): void;
getExposureValue(): number;
isFocusModeSupported(afMode: FocusMode): boolean;
getFocusMode(): FocusMode;
setFocusMode(afMode: FocusMode): void;
setFocusPoint(point: Point): void;
getFocusPoint(): Point;
getFocalLength(): number;
getZoomRatioRange(): Array;
getZoomRatio(): number;
setZoomRatio(zoomRatio: number): void;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean;
getActiveVideoStabilizationMode(): VideoStabilizationMode;
setVideoStabilizationMode(mode: VideoStabilizationMode): void;
on(type: 'error', callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | CaptureSession | beginConfig(callback: AsyncCallback): void;
beginConfig(): Promise;
addInput(cameraInput: CameraInput, callback: AsyncCallback): void;
addInput(cameraInput: CameraInput): Promise;
removeInput(cameraInput: CameraInput, callback: AsyncCallback): void;
removeInput(cameraInput: CameraInput): Promise;
addOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void;
addOutput(cameraOutput: CameraOutput): Promise;
removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void;
removeOutput(cameraOutput: CameraOutput): Promise;
hasFlash(callback: AsyncCallback): void;
hasFlash(): Promise;
isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void;
isFlashModeSupported(flashMode: FlashMode): Promise;
getFlashMode(callback: AsyncCallback): void;
getFlashMode(): Promise;
setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void;
setFlashMode(flashMode: FlashMode): Promise;
isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void;
isExposureModeSupported(aeMode: ExposureMode): Promise;
getExposureMode(callback: AsyncCallback): void;
getExposureMode(): Promise;
setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void;
setExposureMode(aeMode: ExposureMode): Promise;
getMeteringPoint(callback: AsyncCallback): void;
getMeteringPoint(): Promise;
setMeteringPoint(point: Point, callback: AsyncCallback): void;
setMeteringPoint(point: Point): Promise;
getExposureBiasRange(callback: AsyncCallback>): void;
getExposureBiasRange(): Promise>;
setExposureBias(exposureBias: number, callback: AsyncCallback): void;
setExposureBias(exposureBias: number): Promise;
getExposureValue(callback: AsyncCallback): void;
getExposureValue(): Promise;
isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void;
isFocusModeSupported(afMode: FocusMode): Promise;
getFocusMode(callback: AsyncCallback): void;
getFocusMode(): Promise;
setFocusMode(afMode: FocusMode, callback: AsyncCallback): void;
setFocusMode(afMode: FocusMode): Promise;
setFocusPoint(point: Point, callback: AsyncCallback): void;
setFocusPoint(point: Point): Promise;
getFocusPoint(callback: AsyncCallback): void;
getFocusPoint(): Promise;
getFocalLength(callback: AsyncCallback): void;
getFocalLength(): Promise;
getZoomRatioRange(callback: AsyncCallback>): void;
getZoomRatioRange(): Promise>;
getZoomRatio(callback: AsyncCallback): void;
getZoomRatio(): Promise;
setZoomRatio(zoomRatio: number, callback: AsyncCallback): void;
setZoomRatio(zoomRatio: number): Promise;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void;
isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise;
getActiveVideoStabilizationMode(callback: AsyncCallback): void;
getActiveVideoStabilizationMode(): Promise;
setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void;
setVideoStabilizationMode(mode: VideoStabilizationMode): Promise;
on(type: 'error', callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | CaptureSessionErrorCode | ERROR_UNKNOWN = -1
ERROR_INSUFFICIENT_RESOURCES = 0
ERROR_TIMEOUT = 1 | 是 | 废弃 | +| ohos.multimedia.camera | CaptureSessionError | code: CaptureSessionErrorCode | 是 | 废弃 | +| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | PreviewOutputErrorCode | ERROR_UNKNOWN = -1 | 是 | 废弃 | +| ohos.multimedia.camera | PreviewOutputError | code: PreviewOutputErrorCode | 是 | 废弃 | +| ohos.multimedia.camera | PhotoOutput | capture(): Promise;
isMirrorSupported(): boolean;
on(type: 'error', callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | PhotoOutput | isMirrorSupported(callback: AsyncCallback): void;
isMirrorSupported(): Promise;
on(type: 'error', callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_DRIVER_ERROR = 0
ERROR_INSUFFICIENT_RESOURCES = 1
ERROR_TIMEOUT = 2 | 是 | 废弃 | +| ohos.multimedia.camera | PhotoOutputError | code: PhotoOutputErrorCode | 是 | 废弃 | +| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | VideoOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_DRIVER_ERROR = 0 | 是 | 废弃 | +| ohos.multimedia.camera | VideoOutputError | code: VideoOutputErrorCode | 是 | 废弃 | +| ohos.multimedia.camera | MetadataObject | readonly type: MetadataObjectType;
readonly timestamp: number; | 是 | 新增 | +| ohos.multimedia.camera | MetadataObject | getType(callback: AsyncCallback): void;
getType(): Promise;
getTimestamp(callback: AsyncCallback): void;
getTimestamp(): Promise;
getBoundingBox(callback: AsyncCallback): void;
getBoundingBox(): Promise; | 是 | 废弃 | +| ohos.multimedia.camera | MetadataFaceObject | readonly boundingBox: Rect | 是 | 新增 | +| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 新增 | +| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback): void; | 是 | 废弃 | +| ohos.multimedia.camera | MetadataOutputErrorCode | ERROR_UNKNOWN = -1
ERROR_INSUFFICIENT_RESOURCES = 0 | 是 | 废弃 | +| ohos.multimedia.camera | MetadataOutputError | code: MetadataOutputErrorCode | 是 | 废弃 | + +**适配指导** + +除新增接口,和废弃接口之外,开发者需要关注变更的接口的适配: + +从 Beta4 版本开始,对以下接口进行调整: + +**新增接口** + +1. CameraErrorCode 枚举 + + 枚举值名称:INVALID_ARGUMENT, 值:7400101; + + 枚举值名称:OPERATION_NOT_ALLOWED, 值:7400102; + + 枚举值名称:SESSION_NOT_CONFIG, 值:7400103; + + 枚举值名称:SESSION_NOT_RUNNING, 值:7400104; + + 枚举值名称:SESSION_CONFIG_LOCKED, 值:7400105; + + 枚举值名称:DEVICE_SETTING_LOCKED, 值:7400106; + + 枚举值名称:CONFILICT_CAMERA, 值:7400107; + + 枚举值名称:DEVICE_DISABLED, 值:7400108; + + 枚举值名称:SERVICE_FATAL_ERROR, 值:7400201; + +2. PhotoOutput 接口新增 capture(): Promise; + +3. MetadataObject 接口中新增 readonly type: MetadataObjectType; + +4. MetadataObject 接口中新增 readonly timestamp: number; + +5. MetadataObject 接口中新增 readonly boundingBox: Rect; + +**废弃接口** + +1. CameraInput 中废弃接口 release(callback: AsyncCallback): void; 以及 release(): Promise; + +2. 废弃枚举 CameraInputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_NO_PERMISSION = 0,ERROR_DEVICE_PREEMPTED = 1,ERROR_DEVICE_DISCONNECTED = 2,ERROR_DEVICE_IN_USE = 3,ERROR_DRIVER_ERROR = 4); + +3. 废弃接口 CameraInputError 以及接口属性 code:CameraInputErrorCode; + +4. 废弃枚举 CaptureSessionErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_INSUFFICIENT_RESOURCES = 0,ERROR_TIMEOUT = 1); + +5. 废弃接口 CaptureSessionError 以及接口属性 code: CaptureSessionErrorCode; + +6. 废弃枚举 PreviewOutputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1); + +7. 废弃接口 PreviewOutputError 以及接口属性 code: PreviewOutputErrorCode; + +8. 废弃枚举 PhotoOutputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_DRIVER_ERROR = 0,ERROR_INSUFFICIENT_RESOURCES = 1,ERROR_TIMEOUT = 2); + +9. 废弃接口 PhotoOutputError 以及接口属性 code:PhotoOutputErrorCode; + +10. 废弃枚举 VideoOutputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_DRIVER_ERROR = 0); + +11. 废弃接口 VideoOutputError 以及接口属性 code:VideoOutputErrorCode; + +12. 废弃接口 MetadataObject 中 getType(callback: AsyncCallback): void; + +13. 废弃接口 MetadataObject 中 getType(): Promise; + +14. 废弃接口 MetadataObject 中 getTimestamp(callback: AsyncCallback): void; + +15. 废弃接口 MetadataObject 中 getTimestamp(): Promise; + +16. 废弃接口 MetadataObject 中 getBoundingBox(callback: AsyncCallback): void; + +17. 废弃接口 MetadataObject 中 getBoundingBox(): Promise; + +18. 废弃枚举 MetadataOutputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_INSUFFICIENT_RESOURCES = 0); + +19. 废弃接口 MetadataOutputError 以及接口属性 code:MetadataOutputErrorCode; + +**接口变更** + +1. camera 模块中接口 getCameraManager 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getCameraManager(context: Context, callback: AsyncCallback): void; 以及 getCameraManager(context: Context): Promise; 变更为 getCameraManager(context: Context): CameraManager; + + 参考代码如下: + + ``` + let cameraManager = camera.getCameraManager(context); + ``` + +2. CameraManager 中接口 getSupportedCameras 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getSupportedCameras(callback: AsyncCallback>): void; 以及 getSupportedCameras(): Promise>; 变更为 getSupportedCameras(): Array; + + 参考代码如下: + + ``` + let cameras = cameraManager.getSupportedCameras(); + ``` + +3. CameraManager 中接口 getSupportedOutputCapability 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback): void; 以及 getSupportedOutputCapability(camera: CameraDevice): Promise; 变更为 getSupportedOutputCapability(camera: CameraDevice): CameraOutputCapability; + + 参考代码如下: + + ``` + let cameraDevice = cameras[0]; + let CameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice); + ``` + +4. CameraManager 中接口 createCameraInput(camera: CameraDevice) 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createCameraInput(camera: CameraDevice, callback: AsyncCallback): void; 以及 createCameraInput(camera: CameraDevice): Promise; 变更为 createCameraInput(camera: CameraDevice): CameraInput; + + 参考代码如下: + + ``` + let cameraDevice = cameras[0]; + let cameraInput = cameraManager.createCameraInput(cameraDevice); + ``` + +5. CameraManager 中接口 createCameraInput(position: CameraPosition, type: CameraType) 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void; 以及 createCameraInput(position: CameraPosition, type: CameraType): Promise; 变更为 createCameraInput(position: CameraPosition, type: CameraType): CameraInput; + + 参考代码如下: + + ``` + let cameraDevice = cameras[0]; + let position = cameraDevice.cameraPosition; + let type = cameraDevice.cameraType; + let cameraInput = cameraManager.createCameraInput(position, type); + ``` + +6. CameraManager 中接口 createPreviewOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void; 以及 createPreviewOutput(profile: Profile, surfaceId: string): Promise; 变更为 createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput; + + 参考代码如下: + + ``` + let profile = cameraoutputcapability.previewProfiles[0]; + let previewOutput = cameraManager.createPreviewOutput(profile, surfaceId); + ``` + +7. CameraManager 中接口 createPhotoOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void; 以及 createPhotoOutput(profile: Profile, surfaceId: string): Promise; 变更为 createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput; + + 参考代码如下: + + ``` + let profile = cameraoutputcapability.photoProfiles[0]; + let photoOutput = cameraManager.createPhotoOutput(profile, surfaceId); + ``` + +8. CameraManager 中接口 createVideoOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void; 以及 createVideoOutput(profile: VideoProfile, surfaceId: string): Promise; 变更为 createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput; + + 参考代码如下: + + ``` + let profile = cameraoutputcapability.videoProfiles[0]; + let videoOutput = cameraManager.createVideoOutput(profile, surfaceId); + ``` + +9. CameraManager 中接口 createMetadataOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void; 以及 createMetadataOutput(metadataObjectTypes: Array): Promise; 变更为 createMetadataOutput(metadataObjectTypes: Array): MetadataOutput; + + 参考代码如下: + + ``` + let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes; + let metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes); + ``` + +10. CameraManager 中接口 createCaptureSession 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createCaptureSession(callback: AsyncCallback): void; 以及 createCaptureSession(): Promise; 变更为 createCaptureSession(): CaptureSession; + + 参考代码如下: + + ``` + let captureSession = cameraManager.createCaptureSession(); + ``` + +11. 枚举 CameraType 中,枚举值名称 CAMERA_TYPE_UNSPECIFIED 变更为 CAMERA_TYPE_DEFAULT。 + +12. CameraInput 中,on 接口返回值类型由 CameraInputError 变更为 BusinessError,因此旧接口 on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; 变更为 on(type: 'error', camera: CameraDevice, callback: ErrorCallback): void; + + 参考代码如下: + + ``` + let cameraDevice = cameras[0]; + cameraInput.on('error', cameraDevice, (BusinessError) => { + + }) + ``` + +13. CaptureSession 中接口 beginConfig 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 beginConfig(callback: AsyncCallback): void; 以及 beginConfig(): Promise; 变更为 beginConfig(): void; + + 参考代码如下: + + ``` + captureSession.beginConfig(); + ``` + +14. CaptureSession 中接口 addInput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 addInput(cameraInput: CameraInput, callback: AsyncCallback): void; 以及 addInput(cameraInput: CameraInput): Promise; 变更为 addInput(cameraInput: CameraInput): void; + + 参考代码如下: + + ``` + captureSession.addInput(cameraInput); + ``` + +15. CaptureSession 中接口 removeInput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 removeInput(cameraInput: CameraInput, callback: AsyncCallback): void; 以及 removeInput(cameraInput: CameraInput): Promise; 变更为 removeInput(cameraInput: CameraInput): void; + + 参考代码如下: + + ``` + captureSession.removeInput(cameraInput); + ``` + +16. CaptureSession 中接口 addOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 addOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void; 以及 addOutput(cameraOutput: CameraOutput): Promise; 变更为 addOutput(cameraOutput: CameraOutput): void; + + 参考代码如下: + + ``` + captureSession.addOutput(previewOutput); + ``` + +17. CaptureSession 中接口 removeOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback): void; 以及 removeOutput(cameraOutput: CameraOutput): Promise; 变更为 removeOutput(cameraOutput: CameraOutput): void; + + 参考代码如下: + + ``` + captureSession.removeOutput(previewOutput); + ``` + +18. CaptureSession 中接口 hasFlash 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 hasFlash(callback: AsyncCallback): void; 以及 hasFlash(): Promise; 变更为 hasFlash(): boolean; + + 参考代码如下: + + ``` + let status = captureSession.hasFlash(); + ``` + +19. CaptureSession 中接口 isFlashModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void; 以及 isFlashModeSupported(flashMode: FlashMode): Promise; 变更为 isFlashModeSupported(flashMode: FlashMode): boolean; + + 参考代码如下: + + ``` + let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO); + ``` + +20. CaptureSession 中接口 getFlashMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFlashMode(callback: AsyncCallback): void; 以及 getFlashMode(): Promise; 变更为 getFlashMode(): FlashMode; + + 参考代码如下: + + ``` + let flashMode = captureSession.getFlashMode(); + ``` + +21. CaptureSession 中接口 isExposureModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; 以及 isExposureModeSupported(aeMode: ExposureMode): Promise; 变更为 isExposureModeSupported(aeMode: ExposureMode): boolean; + + 参考代码如下: + + ``` + let isSupported = captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED); + ``` + +22. CaptureSession 中接口 getExposureMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureMode(callback: AsyncCallback): void; 以及 getExposureMode(): Promise; 变更为 getExposureMode(): ExposureMode; + + 参考代码如下: + + ``` + let exposureMode = captureSession.getExposureMode(); + ``` + +23. CaptureSession 中接口 setExposureMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void; 以及 setExposureMode(aeMode: ExposureMode): Promise; 变更为 setExposureMode(aeMode: ExposureMode): void; + + 参考代码如下: + + ``` + captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED); + ``` + +24. CaptureSession 中接口 getMeteringPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getMeteringPoint(callback: AsyncCallback): void; 以及 getMeteringPoint(): Promise; 变更为 getMeteringPoint(): Point; + + 参考代码如下: + + ``` + let exposurePoint = captureSession.getMeteringPoint(); + ``` + +25. CaptureSession 中接口 setMeteringPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setMeteringPoint(point: Point, callback: AsyncCallback): void; 以及 setMeteringPoint(point: Point): Promise; 变更为 setMeteringPoint(point: Point): void; + + 参考代码如下: + + ``` + let Point2 = {x: 2, y: 2}; + captureSession.setMeteringPoint(Point2); + ``` + +26. CaptureSession 中接口 getExposureBiasRange 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureBiasRange(callback: AsyncCallback>): void; 以及 getExposureBiasRange(): Promise>; 变更为 getExposureBiasRange(): Array; + + 参考代码如下: + + ``` + let biasRangeArray = captureSession.getExposureBiasRange(); + ``` + +27. CaptureSession 中接口 setExposureBias 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setExposureBias(exposureBias: number, callback: AsyncCallback): void; 以及 setExposureBias(exposureBias: number): Promise; 变更为 setExposureBias(exposureBias: number): void; + + 参考代码如下: + + ``` + let exposureBias = biasRangeArray[0]; + captureSession.setExposureBias(exposureBias); + ``` + +28. CaptureSession 中接口 getExposureValue 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureValue(callback: AsyncCallback): void; 以及 getExposureValue(): Promise; 变更为 getExposureValue(): number; + + 参考代码如下: + + ``` + let exposureValue = captureSession.getExposureValue(); + ``` + +29. CaptureSession 中接口 isFocusModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void; 以及 isFocusModeSupported(afMode: FocusMode): Promise; 变更为 isFocusModeSupported(afMode: FocusMode): boolean; + + 参考代码如下: + + ``` + let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO); + ``` + +30. CaptureSession 中接口 getFocusMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocusMode(callback: AsyncCallback): void; 以及 getFocusMode(): Promise; 变更为 getFocusMode(): FocusMode; + + 参考代码如下: + + ``` + let afMode = captureSession.getFocusMode(); + ``` + +31. CaptureSession 中接口 setFocusMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setFocusMode(afMode: FocusMode, callback: AsyncCallback): void; 以及 setFocusMode(afMode: FocusMode): Promise; 变更为 setFocusMode(afMode: FocusMode): void; + + 参考代码如下: + + ``` + captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO); + ``` + +32. CaptureSession 中接口 setFocusPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setFocusPoint(point: Point, callback: AsyncCallback): void; 以及 setFocusPoint(point: Point): Promise; 变更为 setFocusPoint(point: Point): void; + + 参考代码如下: + + ``` + let Point2 = {x: 2, y: 2}; + captureSession.setFocusPoint(Point2); + ``` + +33. CaptureSession 中接口 getFocusPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocusPoint(callback: AsyncCallback): void; 以及 getFocusPoint(): Promise; 变更为 getFocusPoint(): Point; + + 参考代码如下: + + ``` + let point = captureSession.getFocusPoint(); + ``` + +34. CaptureSession 中接口 getFocalLength 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocalLength(callback: AsyncCallback): void; 以及 getFocalLength(): Promise; 变更为 getFocalLength(): number; + + 参考代码如下: + + ``` + let focalLength = captureSession.getFocalLength(); + ``` + +35. CaptureSession 中接口 getZoomRatioRange 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getZoomRatioRange(callback: AsyncCallback>): void; 以及 getZoomRatioRange(): Promise>; 变更为 getZoomRatioRange(): Array; + + 参考代码如下: + + ``` + let zoomRatioRange = captureSession.getZoomRatioRange(); + ``` + +36. CaptureSession 中接口 getZoomRatio 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getZoomRatio(callback: AsyncCallback): void; 以及 getZoomRatio(): Promise; 变更为 getZoomRatio(): number; + + 参考代码如下: + + ``` + let zoomRatio = captureSession.getZoomRatio(); + ``` + +37. CaptureSession 中接口 setZoomRatio 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setZoomRatio(zoomRatio: number, callback: AsyncCallback): void; 以及 setZoomRatio(zoomRatio: number): Promise; 变更为 setZoomRatio(zoomRatio: number): void; + + 参考代码如下: + + ``` + let zoomRatio = zoomRatioRange[0]; + captureSession.setZoomRatio(zoomRatio); + ``` + +38. CaptureSession 中接口 isVideoStabilizationModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void; 以及 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise; 变更为 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean; + + 参考代码如下: + + ``` + let isSupported = captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF); + ``` + +39. CaptureSession 中接口 getActiveVideoStabilizationMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getActiveVideoStabilizationMode(callback: AsyncCallback): void; 以及 getActiveVideoStabilizationMode(): Promise; 变更为 getActiveVideoStabilizationMode(): VideoStabilizationMode; + + 参考代码如下: + + ``` + let vsMode = captureSession.getActiveVideoStabilizationMode(); + ``` + +40. CaptureSession 中接口 setVideoStabilizationMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void; 以及 setVideoStabilizationMode(mode: VideoStabilizationMode): Promise; 变更为 setVideoStabilizationMode(mode: VideoStabilizationMode): void; + + 参考代码如下: + + ``` + captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF); + ``` + +41. CaptureSession 中,on(type: 'error') callback 类型由 ErrorCallback 变更为 ErrorCallback,因此旧接口 on(type: 'error', callback: ErrorCallback): void; 变更为 on(type: 'error', callback: ErrorCallback): void; + + 参考代码如下: + + ``` + captureSession.on('error', (BusinessError) => { + + }) + ``` + +42. PreviewOutput 中,on(type: 'error') callback 类型由 ErrorCallback 变更为 ErrorCallback,因此旧接口 on(type: 'error', callback: ErrorCallback): void; 变更为 on(type: 'error', callback: ErrorCallback): void; + + 参考代码如下: + + ``` + previewOutput.on('error', (BusinessError) => { + + }) + ``` + +43. PhotoOutput 中接口 isMirrorSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isMirrorSupported(callback: AsyncCallback): void; 以及 isMirrorSupported(): Promise; 变更为 isMirrorSupported(): boolean; + + 参考代码如下: + + ``` + let isSupported = photoOutput.isMirrorSupported(); + ``` + +44. PhotoOutput 中,on(type: 'error') callback 类型由 ErrorCallback 变更为 ErrorCallback,因此旧接口 on(type: 'error', callback: ErrorCallback): void; 变更为 on(type: 'error', callback: ErrorCallback): void; + + 参考代码如下: + + ``` + PhotoOutput.on('error', (BusinessError) => { + + }) + ``` + +45. VideoOutput 中,on(type: 'error') callback 类型由 ErrorCallback 变更为 ErrorCallback,因此旧接口 on(type: 'error', callback: ErrorCallback): void; 变更为 on(type: 'error', callback: ErrorCallback): void; + + 参考代码如下: + + ``` + VideoOutput.on('error', (BusinessError) => { + + }) + ``` + +46. MetadataOutput 中,on(type: 'error') callback 类型由 ErrorCallback 变更为 ErrorCallback,因此旧接口 on(type: 'error', callback: ErrorCallback): void; 变更为 on(type: 'error', callback: ErrorCallback): void; + + 参考代码如下: + + ``` + MetadataOutput.on('error', (BusinessError) => { + + }) + ``` \ No newline at end of file