提交 d6527c60 编写于 作者: S shawn_he 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into 11845-a

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
...@@ -17,7 +17,7 @@ The application recovery APIs are provided by the **appRecovery** module, which ...@@ -17,7 +17,7 @@ The application recovery APIs are provided by the **appRecovery** module, which
| API | Description | | 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. | | 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.| | 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.|
......
...@@ -6,7 +6,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5 ...@@ -6,7 +6,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5
1. Locate the crash-related code based on the service log. 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? ## Why cannot access controls in the UiTest test framework?
......
...@@ -51,9 +51,9 @@ build() { ...@@ -51,9 +51,9 @@ build() {
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 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) Reference: [Resource Manager](../reference/apis/js-apis-resource-manager.md)
......
...@@ -19,112 +19,121 @@ const color = new ArrayBuffer(96); // Create a buffer to store image pixel data. ...@@ -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. let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data.
// Create a PixelMap object. // 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) => { image.createPixelMap(color, opts, (err, pixelmap) => {
console.log('Succeeded in creating pixelmap.'); console.log('Succeeded in creating pixelmap.');
}) // Failed to create the PixelMap object.
if (err) {
// Read pixels. console.info('create pixelmap failed, err' + err);
const area = { return
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;
}
}
} }
})
// Read pixels.
// Store pixels. const area = {
const readBuffer = new ArrayBuffer(96); pixels: new ArrayBuffer(8),
pixelmap.readPixelsToBuffer(readBuffer,() => { offset: 0,
var bufferArr = new Uint8Array(readBuffer); stride: 8,
var res = true; region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
for (var i = 0; i < bufferArr.length; i++) {
if(res) {
if (bufferArr[i] !== 0) {
res = false;
console.log('readPixelsToBuffer end.');
break;
}
}
} }
}) pixelmap.readPixels(area,() => {
let bufferArr = new Uint8Array(area.pixels);
// Write pixels. let res = true;
pixelmap.writePixels(area,() => { for (let i = 0; i < bufferArr.length; i++) {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} console.info(' buffer ' + bufferArr[i]);
pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels);
var res = true;
for (var i = 0; i < readArr.length; i++) {
if(res) { if(res) {
if (readArr[i] !== 0) { if(bufferArr[i] == 0) {
res = false; res = false;
console.log('readPixels end.please check buffer'); console.log('readPixels end.');
break; break;
} }
} }
} }
}) })
})
// Store pixels.
// Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96); const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => { pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer); let bufferArr = new Uint8Array(readBuffer);
var res = true; let res = true;
for (var i = 0; i < bufferArr.length; i++) { for (let i = 0; i < bufferArr.length; i++) {
if(res) { if(res) {
if (bufferArr[i] !== i) { if (bufferArr[i] !== 0) {
res = false; res = false;
console.log('readPixels end.please check buffer'); console.log('readPixelsToBuffer end.');
break; 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. const writeColor = new ArrayBuffer(96); // Pixel data of the image.
pixelmap.getImageInfo((error, imageInfo) => { // Write pixels to the buffer.
if (imageInfo !== null) { pixelmap.writeBufferToPixels(writeColor).then(() => {
console.log('Succeeded in getting imageInfo'); 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. // Obtain image information.
pixelmap.release(()=>{ pixelmap.getImageInfo((err, imageInfo) => {
console.log('Succeeded in releasing pixelmap'); // 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). // Create an image source (uri).
let path = '/data/local/tmp/test.jpg'; let path = '/data/local/tmp/test.jpg';
const imageSourceApi = image.createImageSource(path); const imageSourceApi1 = image.createImageSource(path);
// Create an image source (fd). // Create an image source (fd).
let fd = 29; let fd = 29;
const imageSourceApi = image.createImageSource(fd); const imageSourceApi2 = image.createImageSource(fd);
// Create an image source (data). // Create an image source (data).
const data = new ArrayBuffer(96); const data = new ArrayBuffer(96);
const imageSourceApi = image.createImageSource(data); const imageSourceApi3 = image.createImageSource(data);
// Release the image source. // Release the image source.
imageSourceApi.release(() => { imageSourceApi3.release(() => {
console.log('Succeeded in releasing imagesource'); console.log('Succeeded in releasing imagesource');
}) })
...@@ -133,6 +142,10 @@ const imagePackerApi = image.createImagePacker(); ...@@ -133,6 +142,10 @@ const imagePackerApi = image.createImagePacker();
const imageSourceApi = image.createImageSource(0); const imageSourceApi = image.createImageSource(0);
let packOpts = { format:"image/jpeg", quality:98 }; let packOpts = { format:"image/jpeg", quality:98 };
imagePackerApi.packing(imageSourceApi, packOpts, (err, data) => { imagePackerApi.packing(imageSourceApi, packOpts, (err, data) => {
if (err) {
console.info('packing from imagePackerApi failed, err' + err);
return
}
console.log('Succeeded in packing'); console.log('Succeeded in packing');
}) })
...@@ -161,36 +174,33 @@ let decodingOptions = { ...@@ -161,36 +174,33 @@ let decodingOptions = {
// Create a pixel map in callback mode. // Create a pixel map in callback mode.
imageSourceApi.createPixelMap(decodingOptions, (err, pixelmap) => { 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.'); console.log('Succeeded in creating pixelmap.');
}) })
// Create a pixel map in promise mode. // Create a pixel map in promise mode.
imageSourceApi.createPixelMap().then(pixelmap => { imageSourceApi.createPixelMap().then(pixelmap => {
console.log('Succeeded in creating 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. // Obtain the number of bytes in each line of pixels.
var num = pixelmap.getBytesNumberPerRow(); let num = pixelmap.getBytesNumberPerRow();
// Obtain the total number of pixel bytes. // Obtain the total number of pixel bytes.
var pixelSize = pixelmap.getPixelBytesNumber(); let pixelSize = pixelmap.getPixelBytesNumber();
// Obtain the pixel map information. // Obtain the pixel map information.
pixelmap.getImageInfo().then( imageInfo => {}); pixelmap.getImageInfo().then( imageInfo => {});
// Release the PixelMap object. // Release the PixelMap object.
pixelmap.release(()=>{ pixelmap.release(()=>{
console.log('Succeeded in releasing pixelmap'); console.log('Succeeded in releasing pixelmap');
}) })
}).catch(error => {
// Capture release failure information. console.log('Failed in creating pixelmap.' + error);
catch(error => {
console.log('Failed in releasing pixelmap.' + error);
}) })
``` ```
...@@ -216,7 +226,7 @@ if (imagePackerApi == null) { ...@@ -216,7 +226,7 @@ if (imagePackerApi == null) {
} }
// Set encoding parameters if the image packer is successfully created. // 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. quality:98 } // Image quality, which ranges from 0 to 100.
// Encode the image. // Encode the image.
...@@ -233,8 +243,9 @@ imageSourceApi.getImageInfo((err, imageInfo) => { ...@@ -233,8 +243,9 @@ imageSourceApi.getImageInfo((err, imageInfo) => {
console.log('Succeeded in getting imageInfo'); console.log('Succeeded in getting imageInfo');
}) })
const array = new ArrayBuffer(100); // Incremental data.
// Update 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 ...@@ -246,10 +257,15 @@ Example scenario: The camera functions as the client to transmit image data to t
public async init(surfaceId: any) { public async init(surfaceId: any) {
// (Server code) Create an ImageReceiver object. // (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. // Obtain the surface ID.
receiver.getReceivingSurfaceId((err, surfaceId) => { receiver.getReceivingSurfaceId((err, surfaceId) => {
// Failed to obtain the surface ID.
if (err) {
console.info('getReceivingSurfaceId failed, err' + err);
return
}
console.info("receiver getReceivingSurfaceId success"); console.info("receiver getReceivingSurfaceId success");
}); });
// Register a surface listener, which is triggered after the buffer of the surface is ready. // Register a surface listener, which is triggered after the buffer of the surface is ready.
......
...@@ -230,27 +230,27 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile( ...@@ -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. > 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 ```ts
Text($r('app.string.string_hello')) Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello')) .fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello')) .fontSize($r('app.float.font_hello'))
}
Text($r('app.string.string_world')) Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world')) .fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_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 of the clock")) // Reference string resources. The second parameter of $r is used to replace %s. Text($r('app.string.message_arrive', "five'o clock"))
.fontColor($r('app.color.color_hello')) .fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_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.
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. // The value is "5 apple" in singular form and "5 apples" in plural form.
.fontColor($r('app.color.color_world')) Text($r('app.plural.eat_apple', 5, 5))
.fontSize($r('app.float.font_world')) .fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
} }
Image($r('app.media.my_background_image')) // Reference media resources. 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. ...@@ -274,14 +274,20 @@ To reference a system resource, use the **"$r('sys.type.resource_id')"** format.
```ts ```ts
Text('Hello') Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize')) .fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1')) .fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium')) .fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1')) .backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon')) 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}) .border({
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')}) color: $r('sys.color.ohos_id_color_palette_aux1'),
.height(200) radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2
.width(300) })
.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)
``` ```
...@@ -55,7 +55,7 @@ Initiates a call based on the specified options. This API uses an asynchronous c ...@@ -55,7 +55,7 @@ Initiates a call based on the specified options. This API uses an asynchronous c
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- | | ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. | | 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&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure | | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure |
**Example** **Example**
...@@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the specified p ...@@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the specified p
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | | ----------- | -------------------------------------------------- | ---- | -------------------------------------------- |
| phoneNumber | string | Yes | Phone number. | | phoneNumber | string | Yes | Phone number. |
| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | | options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number options. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br> - **true**: The called number is an emergency number.<br>- **false**: The called number is not an emergency number. | | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br> - **true**: The called number is an emergency number.<br>- **false**: The called number is not an emergency number. |
**Example** **Example**
...@@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. ...@@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ----------- | -------------------------------------------- | ---- | ------------------------------------ | | ----------- | -------------------------------------------- | ---- | ------------------------------------ |
| phoneNumber | string | Yes | Phone number. | | 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&lt;string&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -566,33 +566,6 @@ promise.then(data => { ...@@ -566,33 +566,6 @@ promise.then(data => {
}); });
``` ```
## call.answer<sup>7+</sup>
answer\(callback: AsyncCallback<void\>\): 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&lt;void&gt; | 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.answer<sup>7+</sup> ## call.answer<sup>7+</sup>
answer\(callId: number, callback: AsyncCallback<void\>\): void answer\(callId: number, callback: AsyncCallback<void\>\): void
...@@ -658,7 +631,7 @@ promise.then(data => { ...@@ -658,7 +631,7 @@ promise.then(data => {
## call.hangup<sup>7+</sup> ## call.hangup<sup>7+</sup>
hangup\(callback: AsyncCallback<void\>\): void hangup\(callId: number, callback: AsyncCallback<void\>\): void
Ends 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.
...@@ -672,22 +645,23 @@ This is a system API. ...@@ -672,22 +645,23 @@ This is a system API.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------- | | -------- | ------------------------- | ---- | ---------- |
| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
```js ```js
call.hangup((err, data) => { call.hangup(1, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
## call.hangup<sup>7+</sup> ## call.answer<sup>9+</sup>
hangup\(callId: number, callback: AsyncCallback<void\>\): void answer\(callback: AsyncCallback<void\>\): 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. This is a system API.
...@@ -699,13 +673,12 @@ This is a system API. ...@@ -699,13 +673,12 @@ This is a system API.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------------------------------- | | -------- | ------------------------- | ---- | ----------------------------------------------- |
| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example** **Example**
```js ```js
call.hangup(1, (err, data) => { call.answer((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -746,11 +719,11 @@ promise.then(data => { ...@@ -746,11 +719,11 @@ promise.then(data => {
}); });
``` ```
## call.reject<sup>7+</sup> ## call.hangup<sup>9+</sup>
reject\(callback: AsyncCallback<void\>\): void hangup\(callback: AsyncCallback<void\>\): 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. This is a system API.
...@@ -767,38 +740,7 @@ This is a system API. ...@@ -767,38 +740,7 @@ This is a system API.
**Example** **Example**
```js ```js
call.reject((err, data) => { call.hangup((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.reject<sup>7+</sup>
reject\(options: RejectMessageOptions, callback: AsyncCallback<void\>\): 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&lt;void&gt; | 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)}`); console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -903,6 +845,65 @@ promise.then(data => { ...@@ -903,6 +845,65 @@ promise.then(data => {
}); });
``` ```
## call.reject<sup>9+</sup>
reject\(callback: AsyncCallback<void\>\): 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&lt;void&gt; | 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.reject<sup>9+</sup>
reject\(options: RejectMessageOptions, callback: AsyncCallback<void\>\): 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&lt;void&gt; | 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.holdCall<sup>7+</sup> ## call.holdCall<sup>7+</sup>
holdCall\(callId: number, callback: AsyncCallback<void\>\): void holdCall\(callId: number, callback: AsyncCallback<void\>\): void
...@@ -1344,8 +1345,8 @@ This is a system API. ...@@ -1344,8 +1345,8 @@ This is a system API.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2 | | slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2 |
| callback | AsyncCallback&lt;[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.<br><br>- **0**: Call waiting is disabled.<br>- **1**: Call waiting is enabled.| | callback | AsyncCallback&lt;[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.<br>- **0**: Call waiting is disabled.<br>- **1**: Call waiting is enabled.|
**Example** **Example**
...@@ -2399,7 +2400,7 @@ promise.then(data => { ...@@ -2399,7 +2400,7 @@ promise.then(data => {
}); });
``` ```
## call.setAudioDevice<sup>8+</sup> ## call.setAudioDevice<sup>9+</sup>
setAudioDevice\(device: AudioDevice, callback: AsyncCallback<void\>\): void setAudioDevice\(device: AudioDevice, callback: AsyncCallback<void\>\): void
...@@ -2425,7 +2426,7 @@ call.setAudioDevice(1, (err, data) => { ...@@ -2425,7 +2426,7 @@ call.setAudioDevice(1, (err, data) => {
``` ```
## call.setAudioDevice<sup>8+</sup> ## call.setAudioDevice<sup>9+</sup>
setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback<void\>\): void setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback<void\>\): void
......
# Internationalization – I18N # 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. 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** > **NOTE**
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - 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).
## Modules to Import ## Modules to Import
...@@ -247,9 +244,9 @@ This is a system API. ...@@ -247,9 +244,9 @@ This is a system API.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Mandatory | Description |
| -------- | ------ | ----- | | -------- | ------ | ----- | ----- |
| language | string | Language ID.| | language | string | Yes | Language ID.|
**Error codes** **Error codes**
...@@ -313,9 +310,9 @@ This is a system API. ...@@ -313,9 +310,9 @@ This is a system API.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ----- | | -------- | ------ | ----- | ----- |
| region | string | Region ID.| | region | string | Yes | Region ID.|
**Error codes** **Error codes**
...@@ -379,9 +376,9 @@ This is a system API. ...@@ -379,9 +376,9 @@ This is a system API.
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | --------------- | | -------- | ------ | ----- | ----- |
| locale | string | System locale ID, for example, **zh-CN**.| | locale | string | Yes | System locale ID, for example, **zh-CN**.|
**Error codes** **Error codes**
...@@ -713,9 +710,9 @@ Checks whether the localized script for the specified language is displayed from ...@@ -713,9 +710,9 @@ Checks whether the localized script for the specified language is displayed from
**Parameters** **Parameters**
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ------- | | -------- | ------ | ----- | ----- |
| locale | string | Locale ID.| | locale | string | Yes | Locale ID.|
**Return value** **Return value**
...@@ -905,7 +902,7 @@ Sets the start day of a week for this **Calendar** object. ...@@ -905,7 +902,7 @@ Sets the start day of a week for this **Calendar** object.
| Name | Type | Mandatory | Description | | 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** **Example**
```js ```js
...@@ -947,7 +944,7 @@ Sets the minimum number of days in the first week of a year. ...@@ -947,7 +944,7 @@ Sets the minimum number of days in the first week of a year.
| Name | Type | Mandatory | Description | | 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** **Example**
```js ```js
......
# Internationalization – Intl # 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. 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.
......
...@@ -332,7 +332,6 @@ connection.getDefaultNet().then(function (netHandle) { ...@@ -332,7 +332,6 @@ connection.getDefaultNet().then(function (netHandle) {
}); });
``` ```
## connection.reportNetConnected ## connection.reportNetConnected
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt; reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
...@@ -490,7 +489,6 @@ connection.getAddressesByName(host).then(function (addresses) { ...@@ -490,7 +489,6 @@ connection.getAddressesByName(host).then(function (addresses) {
}) })
``` ```
## connection.enableAirplaneMode ## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void enableAirplaneMode(callback: AsyncCallback\<void>): void
...@@ -539,7 +537,6 @@ connection.enableAirplaneMode().then(function (error) { ...@@ -539,7 +537,6 @@ connection.enableAirplaneMode().then(function (error) {
}) })
``` ```
## connection.disableAirplaneMode ## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void disableAirplaneMode(callback: AsyncCallback\<void>): void
...@@ -588,7 +585,6 @@ connection.disableAirplaneMode().then(function (error) { ...@@ -588,7 +585,6 @@ connection.disableAirplaneMode().then(function (error) {
}) })
``` ```
## connection.createNetConnection ## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
...@@ -825,7 +821,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** ...@@ -825,7 +821,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle**
| Name| Type | Description | | 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 ### bindSocket
...@@ -847,33 +843,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -847,33 +843,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "xxxx"; let socketType = "TCPSocket";
if (socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: "xxxx", port: xxxx, family: xxxx address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => { }, err => {
netHandle.bindSocket(tcp, function (error, data) { if (err) {
console.log(JSON.stringify(error)) console.log('bind fail');
console.log(JSON.stringify(data)) }
netHandle.bindSocket(tcp, (error, data)=>{
if (error) {
console.log(JSON.stringify(error));
} else {
console.log(JSON.stringify(data));
}
})
}) })
} else { } else {
let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: "xxxx", port: xxxx, family: xxxx address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => { }, err => {
if (err) {
console.log('bind fail');
}
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data))
});
netHandle.bindSocket(udp, function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
}); });
netHandle.bindSocket(udp,(error, data)=>{
if (error) {
console.log(JSON.stringify(error));
} else {
console.log(JSON.stringify(data));
}
})
}) })
} }
} })
``` ```
### bindSocket ### bindSocket
...@@ -901,31 +914,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses ...@@ -901,31 +914,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
**Example** **Example**
```js ```js
connection.getDefaultNet().then(function (netHandle) { import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
var tcp = socket.constructTCPSocketInstance(); var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance(); var udp = socket.constructUDPSocketInstance();
let socketType = "xxxx"; let socketType = "TCPSocket";
if(socketType == "TCPSocket") { if (socketType == "TCPSocket") {
tcp.bind({ tcp.bind({
address: "xxxx", port: xxxx, family: xxxx address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => { }, err => {
netHandle.bindSocket(tcp).then(err, data) { if (err) {
console.log(JSON.stringify(data)) console.log('bind fail');
}
netHandle.bindSocket(tcp).then((err, data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
})
}) })
} else { } else {
let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback); udp.on('message', callback);
udp.bind({ udp.bind({
address: "xxxx", port: xxxx, family: xxxx address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => { }, err => {
if (err) {
console.log('bind fail');
}
udp.on('message', (data) => { udp.on('message', (data) => {
console.log(JSON.stringify(data)) console.log(JSON.stringify(data));
}); })
netHandle.bindSocket(tcp).then(err, data) { netHandle.bindSocket(udp).then((err, data) => {
console.log(JSON.stringify(data)) if (err) {
}); console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
})
}) })
} }
} })
``` ```
......
# Network Sharing Management # 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** > **NOTE**
> >
...@@ -405,7 +405,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses ...@@ -405,7 +405,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses
**Example** **Example**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
...@@ -498,7 +498,7 @@ Obtains the network sharing state of the specified type. This API uses a promise ...@@ -498,7 +498,7 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js ```js
import SharingIfaceType from '@ohos.net.sharing' 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)); console.log(JSON.stringify(data));
}).catch(error => { }).catch(error => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
...@@ -525,8 +525,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch ...@@ -525,8 +525,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
**Example** **Example**
```js ```js
import SharingIfaceState from '@ohos.net.sharing' import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error)); console.log(JSON.stringify(error));
console.log(JSON.stringify(data)); console.log(JSON.stringify(data));
}); });
...@@ -565,7 +565,7 @@ sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { ...@@ -565,7 +565,7 @@ sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => {
}); });
``` ```
## on('sharingStateChange') ## sharing.on('sharingStateChange')
on(type: 'sharingStateChange', callback: Callback\<boolean>): void on(type: 'sharingStateChange', callback: Callback\<boolean>): void
...@@ -591,7 +591,7 @@ sharing.on('sharingStateChange', (error, data) => { ...@@ -591,7 +591,7 @@ sharing.on('sharingStateChange', (error, data) => {
}); });
``` ```
## off('sharingStateChange') ## sharing.off('sharingStateChange')
off(type: 'sharingStateChange', callback?: Callback\<boolean>): void off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
...@@ -617,7 +617,7 @@ sharing.off('sharingStateChange', (error, data) => { ...@@ -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 on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void
...@@ -643,7 +643,7 @@ sharing.on('interfaceSharingStateChange', (error, data) => { ...@@ -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 off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void
...@@ -669,7 +669,7 @@ sharing.off('interfaceSharingStateChange', (error, data) => { ...@@ -669,7 +669,7 @@ sharing.off('interfaceSharingStateChange', (error, data) => {
}); });
``` ```
## on('sharingUpstreamChange') ## sharing.on('sharingUpstreamChange')
on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
...@@ -695,7 +695,7 @@ sharing.on('sharingUpstreamChange', (error, data) => { ...@@ -695,7 +695,7 @@ sharing.on('sharingUpstreamChange', (error, data) => {
}); });
``` ```
## off('sharingUpstreamChange') ## sharing.off('sharingUpstreamChange')
off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
...@@ -735,12 +735,12 @@ Enumerates the network sharing states of an NIC. ...@@ -735,12 +735,12 @@ Enumerates the network sharing states of an NIC.
## SharingIfaceType ## SharingIfaceType
Enumerates the network sharing types of an NIC. Enumerates the network sharing types of an NIC.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description | | Name | Value | Description |
| ------------------------ | ---- | ---------------------- | | ------------------------ | ---- | ---------------------- |
| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| | 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.| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.|
...@@ -531,8 +531,8 @@ Enumerates SIM card types and states. ...@@ -531,8 +531,8 @@ Enumerates SIM card types and states.
**System capability**: SystemCapability.Telephony.StateRegistry **System capability**: SystemCapability.Telephony.StateRegistry
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ----------------- | --------------------- | ------------------------------------------------------------ | | -------- | ------- | --------- | ----------- |
| type | [CardType](js-apis-sim.md#cardtype) | SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| | 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) | SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| | state | [SimState](js-apis-sim.md#simstate) | Yes| SIM card status. For details, see [SimState](js-apis-sim.md#simstate).|
| reason<sup>8+</sup> | [LockReason](#lockreason8) | SIM card lock type.| | reason<sup>8+</sup> | [LockReason](#lockreason8) | Yes| SIM card lock type.|
...@@ -142,7 +142,7 @@ Sets the mouse movement speed. This API uses an asynchronous callback to return ...@@ -142,7 +142,7 @@ Sets the mouse movement speed. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------------------- | | -------- | ------------------------- | ---- | ------------------------------------- |
| speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**. | | speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**. |
| callback | AysncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -349,7 +349,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t ...@@ -349,7 +349,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t
| ------------ | ------------------------------ | ---- | ----------------------------------- | | ------------ | ------------------------------ | ---- | ----------------------------------- |
| windowId | number | Yes | Window ID. | | windowId | number | Yes | Window ID. |
| pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. | | pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. |
| callback | AysncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example** **Example**
......
...@@ -1734,8 +1734,8 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci ...@@ -1734,8 +1734,8 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci
**Example** **Example**
```js ```js
radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1763,8 +1763,8 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec ...@@ -1763,8 +1763,8 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec
**Example** **Example**
```js ```js
radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); console.log(`callback: data->${JSON.stringify(data)}`);
}); });
``` ```
...@@ -1797,10 +1797,10 @@ Defines the signal strength. ...@@ -1797,10 +1797,10 @@ Defines the signal strength.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ----------- | --------------------------- | ------------------ | | -------- | ------- | --------- | ----------- |
| signalType | [NetworkType](#networktype) | Signal strength type.| | signalType | [NetworkType](#networktype) | Yes| Signal strength type.|
| signalLevel | number | Signal strength level.| | signalLevel | number | Yes| Signal strength level.|
## NetworkType ## NetworkType
...@@ -1825,17 +1825,17 @@ Defines the network status. ...@@ -1825,17 +1825,17 @@ Defines the network status.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ----------------- | --------------------- | ------------------------------------------------------------ | | -------- | ------- | --------- | ----------- |
| longOperatorName | string | Long carrier name of the registered network.| | longOperatorName | string | Yes | Long carrier name of the registered network.|
| shortOperatorName | string | Short carrier name of the registered network.| | shortOperatorName | string | Yes | Short carrier name of the registered network.|
| plmnNumeric | string | PLMN code of the registered network.| | plmnNumeric | string | Yes | PLMN code of the registered network.|
| isRoaming | boolean | Whether the user is roaming.| | isRoaming | boolean | Yes | Whether the user is roaming.|
| regState | [RegState](#regstate) | Network registration status of the device.| | regState | [RegState](#regstate) | Yes | Network registration status of the device.|
| cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | RAT of the device.| | cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | Yes | RAT of the device.|
| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.| | nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device.|
| isCaActive | boolean | CA status.| | isCaActive | boolean | Yes | CA status.|
| isEmergency | boolean | Whether only emergency calls are allowed.| | isEmergency | boolean | Yes | Whether only emergency calls are allowed.|
## RegState ## RegState
...@@ -1933,13 +1933,13 @@ Defines the cell information. ...@@ -1933,13 +1933,13 @@ Defines the cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | -------- | ------- | --------- | ----------- |
| networkType | [NetworkType](#networktype) | Network type of the cell. | | networkType | [NetworkType](#networktype) | Yes | Network type of the cell. |
| isCamped | boolean | Status of the cell. | | isCamped | boolean | Yes | Status of the cell. |
| timeStamp | number | Timestamp when cell information is obtained. | | timeStamp | number | Yes | Timestamp when cell information is obtained. |
| signalInformation | [SignalInformation](#signalinformation) | Signal information. | | signalInformation | [SignalInformation](#signalinformation) | Yes | 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| | 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|
## CdmaCellInformation<sup>8+</sup> ## CdmaCellInformation<sup>8+</sup>
...@@ -1949,13 +1949,13 @@ Defines the CDMA cell information. ...@@ -1949,13 +1949,13 @@ Defines the CDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ------------ | | -------- | ------- | --------- | ----------- |
| baseId | number | Base station ID. | | baseId | number | Yes | Base station ID. |
| latitude | number | Longitude. | | latitude | number | Yes | Longitude. |
| longitude | number | Latitude. | | longitude | number | Yes | Latitude. |
| nid | number | Network ID.| | nid | number | Yes | Network ID.|
| sid | number | System ID.| | sid | number | Yes | System ID.|
## GsmCellInformation<sup>8+</sup> ## GsmCellInformation<sup>8+</sup>
...@@ -1965,14 +1965,14 @@ Defines the GSM cell information. ...@@ -1965,14 +1965,14 @@ Defines the GSM cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | -------------------- | | -------- | ------- | --------- | ----------- |
| lac | number | Location area code. | | lac | number | Yes | Location area code. |
| cellId | number | Cell ID. | | cellId | number | Yes | Cell ID. |
| arfcn | number | Absolute radio frequency channel number.| | arfcn | number | Yes | Absolute radio frequency channel number.|
| bsic | number | Base station ID. | | bsic | number | Yes | Base station ID. |
| mcc | string | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## LteCellInformation<sup>8+</sup> ## LteCellInformation<sup>8+</sup>
...@@ -1982,16 +1982,16 @@ Defines the LTE cell information. ...@@ -1982,16 +1982,16 @@ Defines the LTE cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------------- | ------- | ----------------------- | | -------- | ------- | --------- | ----------- |
| cgi | number | Cell global identification. | | cgi | number | Yes | Cell global identification. |
| pci | number | Physical cell ID. | | pci | number | Yes | Physical cell ID. |
| tac | number | Tracking area code. | | tac | number | Yes | Tracking area code. |
| earfcn | number | Absolute radio frequency channel number. | | earfcn | number | Yes | Absolute radio frequency channel number. |
| bandwidth | number | Bandwidth. | | bandwidth | number | Yes | Bandwidth. |
| mcc | string | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Mobile network code. | | mnc | string | Yes | Mobile network code. |
| isSupportEndc | boolean | Support New Radio_Dual Connectivity| | isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity. |
## NrCellInformation<sup>8+</sup> ## NrCellInformation<sup>8+</sup>
...@@ -2001,14 +2001,14 @@ Defines the NR cell information. ...@@ -2001,14 +2001,14 @@ Defines the NR cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------- | ------ | ---------------- | | -------- | ------- | --------- | ----------- |
| nrArfcn | number | 5G frequency number. | | nrArfcn | number | Yes | 5G frequency number. |
| pci | number | Physical cell ID. | | pci | number | Yes | Physical cell ID. |
| tac | number | Tracking area code. | | tac | number | Yes | Tracking area code. |
| nci | number | 5G network cell ID.| | nci | number | Yes | 5G network cell ID.|
| mcc | string | Mobile country code. | | mcc | string | Yes | Mobile country code. |
| mnc | string | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## TdscdmaCellInformation<sup>8+</sup> ## TdscdmaCellInformation<sup>8+</sup>
...@@ -2018,14 +2018,14 @@ Defines the TD-SCDMA cell information. ...@@ -2018,14 +2018,14 @@ Defines the TD-SCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ------------ | | -------- | ------- | --------- | ----------- |
| lac | number | Location area code.| | lac | number | Yes | Location area code.|
| cellId | number | Cell ID. | | cellId | number | Yes | Cell ID. |
| cpid | number | Cell parameter ID.| | cpid | number | Yes | Cell parameter ID.|
| uarfcn | number | Absolute radio frequency number.| | uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Mobile country code.| | mcc | string | Yes | Mobile country code.|
| mnc | string | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## WcdmaCellInformation<sup>8+</sup> ## WcdmaCellInformation<sup>8+</sup>
...@@ -2035,14 +2035,14 @@ Defines the WCDMA cell information. ...@@ -2035,14 +2035,14 @@ Defines the WCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ------------ | | -------- | ------- | --------- | ----------- |
| lac | number | Location area code.| | lac | number | Yes | Location area code.|
| cellId | number | Cell ID. | | cellId | number | Yes | Cell ID. |
| psc | number | Primary scrambling code. | | psc | number | Yes | Primary scrambling code. |
| uarfcn | number | Absolute radio frequency number.| | uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Mobile country code.| | mcc | string | Yes | Mobile country code.|
| mnc | string | Mobile network code. | | mnc | string | Yes | Mobile network code. |
## NrOptionMode<sup>8+</sup> ## NrOptionMode<sup>8+</sup>
...@@ -2067,10 +2067,10 @@ Defines the network search result. ...@@ -2067,10 +2067,10 @@ Defines the network search result.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ---------------------- | ------------------------------------------------- | -------------- | | -------- | ------- | --------- | ----------- |
| isNetworkSearchSuccess | boolean | Successful network search.| | isNetworkSearchSuccess | boolean | Yes | Successful network search.|
| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.| | networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.|
## NetworkInformation ## NetworkInformation
...@@ -2080,12 +2080,12 @@ Defines the network information. ...@@ -2080,12 +2080,12 @@ Defines the network information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| --------------- | ----------------------------------------- | -------------- | | -------- | ------- | --------- | ----------- |
| operatorName | string | Carrier name.| | operatorName | string | Yes | Carrier name.|
| operatorNumeric | string | Carrier number. | | operatorNumeric | string | Yes | Carrier number. |
| state | [NetworkInformation](#networkinformationstate) | Network information status.| | state | [NetworkInformation](#networkinformationstate) | Yes | Network information status.|
| radioTech | string | Radio technology. | | radioTech | string | Yes | Radio technology. |
## NetworkInformationState ## NetworkInformationState
...@@ -2110,12 +2110,12 @@ Defines the network selection mode. ...@@ -2110,12 +2110,12 @@ Defines the network selection mode.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------------------ | --------------------------------------------- | -------------------------------------- | | -------- | ------- | --------- | ----------- |
| slotId | number | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2| | slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. | | selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. |
| networkInformation | [NetworkInformation](#networkinformation) | Network information. | | networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. |
| resumeSelection | boolean | Whether to resume selection. | | resumeSelection | boolean | Yes | Whether to resume selection. |
## ImsRegState<sup>9+</sup> ## ImsRegState<sup>9+</sup>
...@@ -2153,10 +2153,10 @@ Defines the IMS registration information. ...@@ -2153,10 +2153,10 @@ Defines the IMS registration information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ----------- | ---------------------------- | ------------- | | -------- | ------- | --------- | ----------- |
| imsRegState | [ImsRegState](#imsregstate9) | IMS registration state.| | imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.|
| imsRegTech | [ImsRegTech](#imsregtech9) | IMS registration technology.| | imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.|
## ImsServiceType<sup>9+</sup> ## ImsServiceType<sup>9+</sup>
......
...@@ -15,8 +15,10 @@ import resourceManager from '@ohos.resourceManager'; ...@@ -15,8 +15,10 @@ import resourceManager from '@ohos.resourceManager';
## Instruction ## 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. 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].
For details about how to reference **context** in the stage model, see Context in the Stage Model.
```ts ```ts
import Ability from '@ohos.application.Ability'; import Ability from '@ohos.application.Ability';
...@@ -97,6 +99,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom ...@@ -97,6 +99,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
**System capability**: SystemCapability.Global.ResourceManager **System capability**: SystemCapability.Global.ResourceManager
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ----------------- | | ---------------------------------------- | ----------------- |
| Promise&lt;[ResourceManager](#resourcemanager)&gt; | Promise used to return the result.| | Promise&lt;[ResourceManager](#resourcemanager)&gt; | Promise used to return the result.|
...@@ -134,6 +137,7 @@ Obtains the **ResourceManager** object of an application based on the specified ...@@ -134,6 +137,7 @@ Obtains the **ResourceManager** object of an application based on the specified
| bundleName | string | Yes | Bundle name of the application.| | bundleName | string | Yes | Bundle name of the application.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------ | | ---------------------------------------- | ------------------ |
| Promise&lt;[ResourceManager](#resourcemanager)&gt; | Promise used to return the result.| | Promise&lt;[ResourceManager](#resourcemanager)&gt; | Promise used to return the result.|
...@@ -305,7 +309,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco ...@@ -305,7 +309,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example (stage)** **Example (stage)**
```ts ```ts
try { 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) { if (error != null) {
console.log("error is " + error); console.log("error is " + error);
} else { } else {
...@@ -333,6 +337,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p ...@@ -333,6 +337,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ----------- | | --------------------- | ----------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -423,6 +428,7 @@ Obtains the string corresponding to the specified resource object. This API uses ...@@ -423,6 +428,7 @@ Obtains the string corresponding to the specified resource object. This API uses
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------------- | | --------------------- | ---------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -512,6 +518,7 @@ Obtains the string array corresponding to the specified resource ID. This API us ...@@ -512,6 +518,7 @@ Obtains the string array corresponding to the specified resource ID. This API us
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------------- | | ---------------------------------- | ------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
...@@ -599,6 +606,7 @@ Obtains the string array corresponding to the specified resource object. This AP ...@@ -599,6 +606,7 @@ Obtains the string array corresponding to the specified resource object. This AP
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------------------ | | ---------------------------------- | ------------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
...@@ -687,6 +695,7 @@ Obtains the content of the media file corresponding to the specified resource ID ...@@ -687,6 +695,7 @@ Obtains the content of the media file corresponding to the specified resource ID
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | -------------- | | ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | Promise used to return the result.|
...@@ -772,6 +781,7 @@ Obtains the content of the media file corresponding to the specified resource ob ...@@ -772,6 +781,7 @@ Obtains the content of the media file corresponding to the specified resource ob
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | ------------------- | | ------------------------- | ------------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | Promise used to return the result.|
...@@ -859,6 +869,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. ...@@ -859,6 +869,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------------- | | --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -944,6 +955,7 @@ Obtains the Base64 code of the image corresponding to the specified resource obj ...@@ -944,6 +955,7 @@ Obtains the Base64 code of the image corresponding to the specified resource obj
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -1014,6 +1026,7 @@ Obtains the device configuration. This API uses a promise 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 **System capability**: SystemCapability.Global.ResourceManager
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ---------------- | | ---------------------------------------- | ---------------- |
| Promise&lt;[Configuration](#configuration)&gt; | Promise used to return the result.| | Promise&lt;[Configuration](#configuration)&gt; | Promise used to return the result.|
...@@ -1069,6 +1082,7 @@ Obtains the device capability. This API uses a promise 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 **System capability**: SystemCapability.Global.ResourceManager
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------- | | ---------------------------------------- | ------------------- |
| Promise&lt;[DeviceCapability](#devicecapability)&gt; | Promise used to return the result.| | Promise&lt;[DeviceCapability](#devicecapability)&gt; | Promise used to return the result.|
...@@ -1144,6 +1158,7 @@ Obtains the singular-plural string corresponding to the specified resource ID ba ...@@ -1144,6 +1158,7 @@ Obtains the singular-plural string corresponding to the specified resource ID ba
| num | number | Yes | Number. | | num | number | Yes | Number. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -1234,6 +1249,7 @@ Obtains the singular-plural string corresponding to the specified resource objec ...@@ -1234,6 +1249,7 @@ Obtains the singular-plural string corresponding to the specified resource objec
| num | number | Yes | Number. | | num | number | Yes | Number. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------------ | | --------------------- | ------------------------------ |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -1321,6 +1337,7 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | ----------- | | ------------------------- | ----------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | Promise used to return the result.|
...@@ -1402,6 +1419,7 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------- | | ---------------------------------------- | ------------------- |
| Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.| | Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.|
...@@ -1470,6 +1488,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---- | | ------------------- | ---- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
...@@ -1538,6 +1557,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---- | | ------------------- | ---- |
| Promise&lt;void&gt; | Promise that returns no value.| | Promise&lt;void&gt; | Promise that returns no value.|
...@@ -1634,6 +1654,7 @@ Obtains the string corresponding to the specified resource name. This API uses a ...@@ -1634,6 +1654,7 @@ Obtains the string corresponding to the specified resource name. This API uses a
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------- | | --------------------- | ---------- |
| Promise&lt;string&gt; | String corresponding to the resource name.| | Promise&lt;string&gt; | String corresponding to the resource name.|
...@@ -1716,6 +1737,7 @@ Obtains the string array corresponding to the specified resource name. This API ...@@ -1716,6 +1737,7 @@ Obtains the string array corresponding to the specified resource name. This API
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------------ | | ---------------------------------- | ------------ |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
...@@ -1798,6 +1820,7 @@ Obtains the content of the media file corresponding to the specified resource na ...@@ -1798,6 +1820,7 @@ Obtains the content of the media file corresponding to the specified resource na
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | ------------- | | ------------------------- | ------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | Promise used to return the result.|
...@@ -1880,6 +1903,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam ...@@ -1880,6 +1903,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------- | | --------------------- | ------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -1965,6 +1989,7 @@ Obtains the plural string corresponding to the specified resource name based on ...@@ -1965,6 +1989,7 @@ Obtains the plural string corresponding to the specified resource name based on
| num | number | Yes | Number. | | num | number | Yes | Number. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ---------------------- | | --------------------- | ---------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -2007,6 +2032,7 @@ Obtains the string corresponding to the specified resource ID. This API returns ...@@ -2007,6 +2032,7 @@ Obtains the string corresponding to the specified resource ID. This API returns
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ----------- | | ------ | ----------- |
| string | Promise used to return the result.| | string | Promise used to return the result.|
...@@ -2045,6 +2071,7 @@ Obtains the string corresponding to the specified resource object. This API retu ...@@ -2045,6 +2071,7 @@ Obtains the string corresponding to the specified resource object. This API retu
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------------- | | ------ | ---------------- |
| string | Promise used to return the result.| | string | Promise used to return the result.|
...@@ -2088,6 +2115,7 @@ Obtains the string corresponding to the specified resource name. This API return ...@@ -2088,6 +2115,7 @@ Obtains the string corresponding to the specified resource name. This API return
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| string | String corresponding to the specified resource name.| | string | String corresponding to the specified resource name.|
...@@ -2126,6 +2154,7 @@ Obtains the Boolean result corresponding to the specified resource ID. This API ...@@ -2126,6 +2154,7 @@ Obtains the Boolean result corresponding to the specified resource ID. This API
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------ | | ------- | ------------ |
| boolean | Boolean result corresponding to the specified resource ID.| | boolean | Boolean result corresponding to the specified resource ID.|
...@@ -2163,6 +2192,7 @@ Obtains the Boolean result corresponding to the specified resource object. This ...@@ -2163,6 +2192,7 @@ Obtains the Boolean result corresponding to the specified resource object. This
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------------- | | ------- | ----------------- |
| boolean | Boolean result corresponding to the specified resource object.| | 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 ...@@ -2206,6 +2236,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------- | | ------- | ----------- |
| boolean | Boolean result corresponding to the specified resource name.| | 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 ...@@ -2244,6 +2275,7 @@ Obtains the integer or float value corresponding to the specified resource ID. T
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ---------- | | ------ | ---------- |
| number | Integer or float value corresponding to the specified resource ID.| | 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 ...@@ -2288,6 +2320,7 @@ Obtains the integer or float value corresponding to the specified resource objec
| resource | [Resource](#resource9) | Yes | Resource object.| | resource | [Resource](#resource9) | Yes | Resource object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------------- | | ------ | --------------- |
| number | Integer or float value corresponding to the specified resource object.| | 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. ...@@ -2331,6 +2364,7 @@ Obtains the integer or float value corresponding to the specified resource name.
| resName | string | Yes | Resource name.| | resName | string | Yes | Resource name.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------- | | ------ | --------- |
| number | Integer or float value corresponding to the specified resource name.| | 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 ...@@ -2409,6 +2443,7 @@ This API is deprecated since API version 9. You are advised to use [getStringVal
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ----------- | | --------------------- | ----------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -2473,6 +2508,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr ...@@ -2473,6 +2508,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ------------- | | ---------------------------------- | ------------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.| | Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the result.|
...@@ -2495,7 +2531,7 @@ getMedia(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void ...@@ -2495,7 +2531,7 @@ getMedia(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2526,7 +2562,7 @@ getMedia(resId: number): Promise&lt;Uint8Array&gt; ...@@ -2526,7 +2562,7 @@ getMedia(resId: number): Promise&lt;Uint8Array&gt;
Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2537,6 +2573,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont ...@@ -2537,6 +2573,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | -------------- | | ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | Promise used to return the result.|
...@@ -2559,7 +2596,7 @@ getMediaBase64(resId: number, callback: AsyncCallback&lt;string&gt;): void ...@@ -2559,7 +2596,7 @@ getMediaBase64(resId: number, callback: AsyncCallback&lt;string&gt;): void
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2590,7 +2627,7 @@ getMediaBase64(resId: number): Promise&lt;string&gt; ...@@ -2590,7 +2627,7 @@ getMediaBase64(resId: number): Promise&lt;string&gt;
Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2601,6 +2638,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont ...@@ -2601,6 +2638,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
| resId | number | Yes | Resource ID.| | resId | number | Yes | Resource ID.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | -------------------- | | --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -2623,7 +2661,7 @@ getPluralString(resId: number, num: number): Promise&lt;string&gt; ...@@ -2623,7 +2661,7 @@ getPluralString(resId: number, num: number): Promise&lt;string&gt;
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. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2635,6 +2673,7 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr ...@@ -2635,6 +2673,7 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr
| num | number | Yes | Number. | | num | number | Yes | Number. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| --------------------- | ------------------------- | | --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.| | Promise&lt;string&gt; | Promise used to return the result.|
...@@ -2657,7 +2696,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback&lt;string&gt ...@@ -2657,7 +2696,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback&lt;string&gt
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. 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 **System capability**: SystemCapability.Global.ResourceManager
...@@ -2731,6 +2770,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------- | ----------- | | ------------------------- | ----------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.| | Promise&lt;Uint8Array&gt; | 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 ...@@ -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.| | path | string | Yes | Path of the raw file.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------------- | ------------------- | | ---------------------------------------- | ------------------- |
| Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.| | Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.|
......
...@@ -2847,10 +2847,10 @@ Defines the lock status response. ...@@ -2847,10 +2847,10 @@ Defines the lock status response.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| --------------- | ------ | ------------------ | | -------- | ------- | --------- | ----------- |
| result | number | Operation result. | | result | number | Yes | Operation result. |
| remain?: number | number | Remaining attempts (can be null).| | remain?: number | number | Yes | Remaining attempts (can be null).|
## LockInfo<sup>8+</sup> ## LockInfo<sup>8+</sup>
...@@ -2860,11 +2860,11 @@ Defines the lock information. ...@@ -2860,11 +2860,11 @@ Defines the lock information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------ | ------ | | -------- | ------- | --------- | ----------- |
| lockType | [LockType](#locktype8) | Lock type.| | lockType | [LockType](#locktype8) | Yes | Lock type.|
| password | string | Password. | | password | string | Yes | Password. |
| state | [LockState](#lockstate8) | Lock state.| | state | [LockState](#lockstate8) | Yes | Lock state.|
## PersoLockInfo<sup>8+</sup> ## PersoLockInfo<sup>8+</sup>
...@@ -2874,10 +2874,10 @@ Defines the personalized lock information. ...@@ -2874,10 +2874,10 @@ Defines the personalized lock information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ------------ | | -------- | ------- | --------- | ----------- |
| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.| | lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.|
| password | string | Password. | | password | string | Yes | Password. |
## IccAccountInfo<sup>7+</sup> ## IccAccountInfo<sup>7+</sup>
...@@ -2887,15 +2887,15 @@ Defines the ICC account information. ...@@ -2887,15 +2887,15 @@ Defines the ICC account information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ---------- | ------- | ---------------- | | -------- | ------- | --------- | ----------- |
| simId | number | SIM card ID. | | simId | number | Yes | SIM card ID. |
| slotIndex | number | Card slot ID. | | slotIndex | number | Yes | Card slot ID. |
| isEsim | boolean | Whether the SIM card is an eSim card.| | isEsim | boolean | Yes | Whether the SIM card is an eSim card.|
| isActive | boolean | Whether the card is activated. | | isActive | boolean | Yes | Whether the card is activated. |
| iccId | string | ICCID number. | | iccId | string | Yes | ICCID number. |
| showName | string | SIM card display name. | | showName | string | Yes | SIM card display name. |
| showNumber | string | SIM card display number. | | showNumber | string | Yes | SIM card display number. |
## OperatorConfig<sup>8+</sup> ## OperatorConfig<sup>8+</sup>
...@@ -2905,10 +2905,10 @@ Defines the carrier configuration. ...@@ -2905,10 +2905,10 @@ Defines the carrier configuration.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description| | Name | Type | Mandatory | Description |
| ----- | ------ | ---- | | -------- | ------- | --------- | ----------- |
| field | string | Field| | field | string | Yes | Field. |
| value | string | Value | | value | string | Yes | Value. |
## DiallingNumbersInfo<sup>8+</sup> ## DiallingNumbersInfo<sup>8+</sup>
...@@ -2918,12 +2918,12 @@ Defines the contact number information. ...@@ -2918,12 +2918,12 @@ Defines the contact number information.
**System capability**: SystemCapability.Telephony.CoreService **System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------------ | ------ | -------- | | -------- | ------- | --------- | ----------- |
| alphaTag | string | Alpha tag. | | alphaTag | string | Yes | Alpha tag. |
| number | string | Contact number. | | number | string | Yes | Contact number. |
| recordNumber | number | Record number.| | recordNumber | number | Yes | Record number.|
| pin2 | string | PIN 2.| | pin2 | string | Yes | PIN 2.|
## ContactType<sup>8+</sup> ## ContactType<sup>8+</sup>
......
...@@ -1116,19 +1116,19 @@ Defines an SMS message instance. ...@@ -1116,19 +1116,19 @@ Defines an SMS message instance.
**System capability**: SystemCapability.Telephony.SmsMms **System capability**: SystemCapability.Telephony.SmsMms
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------------------------ | --------------------------------------- | ------------------------------------------------------------ | | -------- | ------- | --------- | ----------- |
| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.<br>**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| | hasReplyPath | boolean | Yes |Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.<br>**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**.<br>For details, see section 9.2.3.9 in **3GPP TS 23.040**.| | isReplaceMessage | boolean | Yes |Whether the received SMS message is a **replace short message**. The default value is **false**.<br>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**.<br>**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| | isSmsStatusReportMessage | boolean | Yes |Whether the received SMS message is an SMS delivery status report. The default value is **false**.<br>**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. | | messageClass | [ShortMessageClass](#shortmessageclass) | Yes | SMS message type. |
| pdu | Array&lt;number&gt; | PDU in the SMS message. | | pdu | Array&lt;number&gt; | Yes | PDU in the SMS message. |
| protocolId | number | Protocol identifier used for delivering the SMS message. | | protocolId | number | Yes | Protocol identifier used for delivering the SMS message. |
| scAddress | string | SMSC address. | | scAddress | string | Yes | SMSC address. |
| scTimestamp | number | SMSC timestamp. | | scTimestamp | number | Yes | SMSC timestamp. |
| status | number | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| | status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.|
| visibleMessageBody | string | SMS message body. | | visibleMessageBody | string | Yes | SMS message body. |
| visibleRawAddress | string | Sender address. | | visibleRawAddress | string | Yes | Sender address. |
## ShortMessageClass ## ShortMessageClass
......
...@@ -70,7 +70,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput ...@@ -70,7 +70,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput
| toolHeight | number | Yes| No| Height of the tool area.| | toolHeight | number | Yes| No| Height of the tool area.|
| rawX | number | Yes| No| X coordinate of the input device.| | rawX | number | Yes| No| X coordinate of the input device.|
| rawY | number | Yes| No| Y 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 ## TouchEvent
......
...@@ -638,16 +638,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain ...@@ -638,16 +638,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------------- | ------------------------------------------- | ------------- | | -------- | ------- | --------- | ----------- |
| address | number | Endpoint address. | | address | number | Yes | Endpoint address. |
| attributes | number | Endpoint attributes. | | attributes | number | Yes | Endpoint attributes. |
| interval | number | Endpoint interval. | | interval | number | Yes | Endpoint interval. |
| maxPacketSize | number | Maximum size of data packets on the endpoint. | | maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. | | direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. |
| number | number | Endpoint number. | | number | number | Yes | Endpoint number. |
| type | number | Endpoint type. | | type | number | Yes | Endpoint type. |
| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| | interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.|
## USBInterface ## USBInterface
...@@ -655,15 +655,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U ...@@ -655,15 +655,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ---------------- | ---------------------------------------- | --------------------- | | -------- | ------- | --------- | ----------- |
| id | number | Unique ID of the USB interface. | | id | number | Yes | Unique ID of the USB interface. |
| protocol | number | Interface protocol. | | protocol | number | Yes | Interface protocol. |
| clazz | number | Device type. | | clazz | number | Yes | Device type. |
| subClass | number | Device subclass. | | subClass | number | Yes | Device subclass. |
| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| | alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.|
| name | string | Interface name. | | name | string | Yes | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Endpoints that belong to the USB interface. | | endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. |
## USBConfig ## USBConfig
...@@ -671,15 +671,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip ...@@ -671,15 +671,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| -------------- | ------------------------------------------------ | --------------- | | -------- | ------- | --------- | ----------- |
| id | number | Unique ID of the USB configuration. | | id | number | Yes | Unique ID of the USB configuration. |
| attributes | number | Configuration attributes. | | attributes | number | Yes | Configuration attributes. |
| maxPower | number | Maximum power consumption, in mA. | | maxPower | number | Yes | Maximum power consumption, in mA. |
| name | string | Configuration name, which can be left empty. | | name | string | Yes | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Support for remote wakeup.| | isRemoteWakeup | boolean | Yes | Support for remote wakeup.|
| isSelfPowered | boolean | Support for independent power supplies.| | isSelfPowered | boolean | Yes | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Supported interface attributes. | | interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. |
## USBDevice ## USBDevice
...@@ -687,21 +687,21 @@ Represents the USB device information. ...@@ -687,21 +687,21 @@ Represents the USB device information.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ---------------- | ------------------------------------ | ---------- | | -------- | ------- | --------- | ----------- |
| busNum | number | Bus address. | | busNum | number | Yes | Bus address. |
| devAddress | number | Device address. | | devAddress | number | Yes | Device address. |
| serial | string | Sequence number. | | serial | string | Yes | Sequence number. |
| name | string | Device name. | | name | string | Yes | Device name. |
| manufacturerName | string | Device manufacturer. | | manufacturerName | string | Yes | Device manufacturer. |
| productName | string | Product name. | | productName | string | Yes | Product name. |
| version | string | Version number. | | version | string | Yes | Version number. |
| vendorId | number | Vendor ID. | | vendorId | number | Yes | Vendor ID. |
| productId | number | Product ID. | | productId | number | Yes | Product ID. |
| clazz | number | Device class. | | clazz | number | Yes | Device class. |
| subClass | number | Device subclass. | | subClass | number | Yes | Device subclass. |
| protocol | number | Device protocol code. | | protocol | number | Yes | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Device configuration descriptor information.| | configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.|
## USBDevicePipe ## USBDevicePipe
...@@ -709,10 +709,10 @@ Represents a USB device pipe, which is used to determine a USB device. ...@@ -709,10 +709,10 @@ Represents a USB device pipe, which is used to determine a USB device.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ----- | | -------- | ------- | --------- | ----------- |
| busNum | number | Bus address.| | busNum | number | Yes | Bus address.|
| devAddress | number | Device address.| | devAddress | number | Yes | Device address.|
## USBControlParams ## USBControlParams
...@@ -720,14 +720,14 @@ Represents control transfer parameters. ...@@ -720,14 +720,14 @@ Represents control transfer parameters.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| ------- | ----------------------------------------------- | ---------------- | | -------- | ------- | --------- | ----------- |
| request | number | Request type. | | request | number | Yes | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. | | target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. | | reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. |
| value | number | Request parameter value. | | value | number | Yes | Request parameter value. |
| index | number | Index of the request parameter value.| | index | number | Yes | Index of the request parameter value.|
| data | Uint8Array | Buffer for writing or reading data. | | data | Uint8Array | Yes | Buffer for writing or reading data. |
## USBPort<sup>9+</sup> ## USBPort<sup>9+</sup>
...@@ -737,11 +737,11 @@ Represents a USB port. ...@@ -737,11 +737,11 @@ Represents a USB port.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type | Description | | Name | Type | Mandatory | Description |
| -------------- | -------------------------------- | ----------------------------------- | | -------- | ------- | --------- | ----------- |
| id | number | Unique identifier of a USB port. | | id | number | Yes | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.| | supportedModes | [PortModeType](#portmodetype9) | Yes | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus9) | USB port role. | | status | [USBPortStatus](#usbportstatus9) | Yes | USB port role. |
## USBPortStatus<sup>9+</sup> ## USBPortStatus<sup>9+</sup>
...@@ -751,11 +751,11 @@ Enumerates USB port roles. ...@@ -751,11 +751,11 @@ Enumerates USB port roles.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Type| Description | | Name | Type | Mandatory | Description |
| ---------------- | -------- | ---------------------- | | -------- | ------- | --------- | ----------- |
| currentMode | number | Current USB mode. | | currentMode | number | Yes | Current USB mode. |
| currentPowerRole | number | Current power role. | | currentPowerRole | number | Yes | Current power role. |
| currentDataRole | number | Current data role.| | currentDataRole | number | Yes | Current data role. |
## USBRequestTargetType ## USBRequestTargetType
......
...@@ -720,14 +720,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain ...@@ -720,14 +720,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- | | ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes|Endpoint address. | | address | number | Yes | Endpoint address. |
| attributes | number | Yes|Endpoint attributes. | | attributes | number | Yes | Endpoint attributes. |
| interval | number | Yes|Endpoint interval. | | interval | number | Yes | Endpoint interval. |
| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. | | maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. | | direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. |
| number | number | Yes|Endpoint number. | | number | number | Yes | Endpoint number. |
| type | number | Yes|Endpoint type. | | type | number | Yes | Endpoint type. |
| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.| | interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.|
## USBInterface ## USBInterface
...@@ -737,13 +737,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U ...@@ -737,13 +737,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- | | ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes|Unique ID of the USB interface. | | id | number | Yes | Unique ID of the USB interface. |
| protocol | number | Yes|Interface protocol. | | protocol | number | Yes | Interface protocol. |
| clazz | number | Yes|Device type. | | clazz | number | Yes | Device type. |
| subClass | number | Yes|Device subclass. | | subClass | number | Yes | Device subclass. |
| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.| | alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes|Interface name. | | name | string | Yes | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. | | endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. |
## USBConfig ## USBConfig
...@@ -753,13 +753,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip ...@@ -753,13 +753,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- | | -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes|Unique ID of the USB configuration. | | id | number | Yes | Unique ID of the USB configuration. |
| attributes | number | Yes|Configuration attributes. | | attributes | number | Yes | Configuration attributes. |
| maxPower | number | Yes|Maximum power consumption, in mA. | | maxPower | number | Yes | Maximum power consumption, in mA. |
| name | string | Yes|Configuration name, which can be left empty. | | name | string | Yes | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes|Support for remote wakeup.| | isRemoteWakeup | boolean | Yes | Support for remote wakeup.|
| isSelfPowered | boolean | Yes| Support for independent power supplies.| | isSelfPowered | boolean | Yes | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. | | interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. |
## USBDevice ## USBDevice
...@@ -769,19 +769,19 @@ Represents the USB device information. ...@@ -769,19 +769,19 @@ Represents the USB device information.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- | | ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes|Bus address. | | busNum | number | Yes | Bus address. |
| devAddress | number | Yes|Device address. | | devAddress | number | Yes | Device address. |
| serial | string | Yes|Sequence number. | | serial | string | Yes | Sequence number. |
| name | string | Yes|Device name. | | name | string | Yes | Device name. |
| manufacturerName | string | Yes| Device manufacturer. | | manufacturerName | string | Yes | Device manufacturer. |
| productName | string | Yes|Product name. | | productName | string | Yes | Product name. |
| version | string | Yes|Version number. | | version | string | Yes | Version number. |
| vendorId | number | Yes|Vendor ID. | | vendorId | number | Yes | Vendor ID. |
| productId | number | Yes|Product ID. | | productId | number | Yes | Product ID. |
| clazz | number | Yes|Device class. | | clazz | number | Yes | Device class. |
| subClass | number | Yes|Device subclass. | | subClass | number | Yes | Device subclass. |
| protocol | number | Yes|Device protocol code. | | protocol | number | Yes | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.| | configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.|
## USBDevicePipe ## USBDevicePipe
...@@ -802,12 +802,12 @@ Represents control transfer parameters. ...@@ -802,12 +802,12 @@ Represents control transfer parameters.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- | | ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes |Request type. | | request | number | Yes | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. | | target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. | | reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. |
| value | number | Yes |Request parameter value. | | value | number | Yes | Request parameter value. |
| index | number | Yes |Index of the request parameter value.| | index | number | Yes | Index of the request parameter value.|
| data | Uint8Array | Yes |Buffer for writing or reading data. | | data | Uint8Array | Yes | Buffer for writing or reading data. |
## USBPort ## USBPort
...@@ -819,9 +819,9 @@ Represents a USB port. ...@@ -819,9 +819,9 @@ Represents a USB port.
| Name | Type | Mandatory |Description | | Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ | | -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes |Unique identifier of a USB port. | | id | number | Yes | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.| | supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. | | status | [USBPortStatus](#usbportstatus) | Yes | USB port role. |
## USBPortStatus ## USBPortStatus
...@@ -833,9 +833,9 @@ Enumerates USB port roles. ...@@ -833,9 +833,9 @@ Enumerates USB port roles.
| Name | Type| Mandatory |Description | | Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- | | ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes|Current USB mode. | | currentMode | number | Yes | Current USB mode. |
| currentPowerRole | number | Yes |Current power role. | | currentPowerRole | number | Yes | Current power role. |
| currentDataRole | number | Yes |Current data role.| | currentDataRole | number | Yes | Current data role.|
## USBRequestTargetType ## USBRequestTargetType
...@@ -843,12 +843,12 @@ Enumerates request target types. ...@@ -843,12 +843,12 @@ Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager **System capability**: SystemCapability.USB.USBManager
| Name | Value | Description | | Name | Value | Description |
| ---------------------------- | ---- | ------ | | ---------------------------- | ----- | ----------- |
| USB_REQUEST_TARGET_DEVICE | 0 | Device| | USB_REQUEST_TARGET_DEVICE | 0 | Device |
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface| | USB_REQUEST_TARGET_INTERFACE | 1 | Interface |
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint| | USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint |
| USB_REQUEST_TARGET_OTHER | 3 | Other| | USB_REQUEST_TARGET_OTHER | 3 | Other |
## USBControlRequestType ## USBControlRequestType
......
# LCD # LCD
## Overview ## 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 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 **Figure 1** HDF-based display driver model
![image](figures/architecture-of-the-display-driver-model.png "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 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.
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.
- 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. - 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 ...@@ -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. The display driver model leverages the capabilities and APIs provided by the platform to simplify the display driver development and improve the efficiency.
### Basic Concepts
## Available APIs
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. 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 ...@@ -34,7 +39,7 @@ The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Displa
![](figures/mipi-dsi.png "MIPI DSI") ![](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 - TTL interface
...@@ -42,14 +47,31 @@ The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Displa ...@@ -42,14 +47,31 @@ The LCD interfaces include the Mobile Industry Processor Interface (MIPI) Displa
![](figures/ttl-interface.png "ttl-interface") ![](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. 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 ...@@ -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: 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 - 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. 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 - 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. 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()**. 4. (Optional) Implement other HDF APIs, such as **Release()**, as required.
5. Use the HDF to create other device nodes for implementing service logic or debugging as required. 5. (Optional) Create other device nodes for implementing service logic or debugging based on the HDF as required.
### Example
## Development Example
The following uses the Hi35xx series chips as an example to describe how to perform LCD driver adaptation.
Add the device configuration.
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 */ /* Configuration of the devices related to the display driver */
display :: host { display :: host {
hostName = "display_host"; hostName = "display_host";
/* Configuration of the HDF display driver */ /* Configuration of the HDF display driver */
device_hdf_disp :: device { device_hdf_disp :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 2; policy = 2;
priority = 200; priority = 200;
permission = 0660; permission = 0660;
moduleName = "HDF_DISP"; moduleName = "HDF_DISP";
serviceName = "hdf_disp"; serviceName = "hdf_disp";
} }
} }
/* Configuration of the driver device at the SoC adapter layer */ /* Configuration of the driver device at the SoC adapter layer */
device_hi35xx_disp :: device { device_hi35xx_disp :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 0; policy = 0;
priority = 199; priority = 199;
moduleName = "HI351XX_DISP"; moduleName = "HI351XX_DISP";
} }
} }
/* Configuration of the LCD driver */ /* Configuration of the LCD driver */
device_lcd :: device { device_lcd :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 0; policy = 0;
priority = 100; priority = 100;
preload = 0; preload = 0;
moduleName = "LCD_Sample"; moduleName = "LCD_Sample";
} }
device1 :: deviceNode { device1 :: deviceNode {
policy = 0; policy = 0;
priority = 100; priority = 100;
preload = 2; preload = 2;
moduleName = "LCD_SampleXX"; 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: 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) static int32_t MipiDsiInit(struct PanelInfo *info)
{ {
int32_t ret; int32_t ret;
struct DevHandle *mipiHandle = NULL; struct DevHandle *mipiHandle = NULL;
struct MipiCfg cfg; struct MipiCfg cfg;
mipiHandle = MipiDsiOpen(0); mipiHandle = MipiDsiOpen(0);
if (mipiHandle == NULL) { if (mipiHandle == NULL) {
HDF_LOGE("%s: MipiDsiOpen failure", __func__); HDF_LOGE("%s: MipiDsiOpen failure", __func__);
return HDF_FAILURE; return HDF_FAILURE;
} }
cfg.lane = info->mipi.lane; cfg.lane = info->mipi.lane;
cfg.mode = info->mipi.mode; cfg.mode = info->mipi.mode;
cfg.format = info->mipi.format; cfg.format = info->mipi.format;
cfg.burstMode = info->mipi.burstMode; cfg.burstMode = info->mipi.burstMode;
cfg.timing.xPixels = info->width; cfg.timing.xPixels = info->width;
cfg.timing.hsaPixels = info->hsw; cfg.timing.hsaPixels = info->hsw;
cfg.timing.hbpPixels = info->hbp; cfg.timing.hbpPixels = info->hbp;
cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw; cfg.timing.hlinePixels = info->width + info->hbp + info->hfp + info->hsw;
cfg.timing.vsaLines = info->vsw; cfg.timing.vsaLines = info->vsw;
cfg.timing.vbpLines = info->vbp; cfg.timing.vbpLines = info->vbp;
cfg.timing.vfpLines = info->vfp; cfg.timing.vfpLines = info->vfp;
cfg.timing.ylines = info->height; cfg.timing.ylines = info->height;
/* 0 : no care */ /* 0 : no care */
cfg.timing.edpiCmdSize = 0; cfg.timing.edpiCmdSize = 0;
cfg.pixelClk = CalcPixelClk(info); cfg.pixelClk = CalcPixelClk(info);
cfg.phyDataRate = CalcDataRate(info); cfg.phyDataRate = CalcDataRate(info);
/* Configure the MIPI device. */ /* Configure the MIPI device. */
ret = MipiDsiSetCfg(mipiHandle, &cfg); ret = MipiDsiSetCfg(mipiHandle, &cfg);
if (ret != HDF_SUCCESS) { if (ret != HDF_SUCCESS) {
HDF_LOGE("%s:MipiDsiSetCfg failure", __func__); HDF_LOGE("%s:MipiDsiSetCfg failure", __func__);
} }
MipiDsiClose(mipiHandle); MipiDsiClose(mipiHandle);
HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__, HDF_LOGI("%s:pixelClk = %d, phyDataRate = %d\n", __func__,
cfg.pixelClk, cfg.phyDataRate); cfg.pixelClk, cfg.phyDataRate);
return ret; return ret;
} }
``` ```
Develop an LCD driver. The sample code is as follows: 3. Add a device in **drivers/hdf_core/framework/model/display/driver/panel/mipi_icn9700.c**.
- Define driver-related interface information.
```
#define RESET_GPIO 5 ```c++
#define MIPI_DSI0 0 #define RESET_GPIO 5
#define BLK_PWM1 1 #define MIPI_DSI0 0
#define PWM_MAX_PERIOD 100000 #define BLK_PWM1 1
/* Set the backlight. */ #define PWM_MAX_PERIOD 100000
#define MIN_LEVEL 0 /* Set the backlight. */
#define MAX_LEVEL 255 #define MIN_LEVEL 0
#define DEFAULT_LEVEL 100 #define MAX_LEVEL 255
#define DEFAULT_LEVEL 100
#define WIDTH 480 #define WIDTH 480
#define HEIGHT 960 #define HEIGHT 960
#define HORIZONTAL_BACK_PORCH 20 #define HORIZONTAL_BACK_PORCH 20
#define HORIZONTAL_FRONT_PORCH 20 #define HORIZONTAL_FRONT_PORCH 20
#define HORIZONTAL_SYNC_WIDTH 10 #define HORIZONTAL_SYNC_WIDTH 10
#define VERTICAL_BACK_PORCH 14 #define VERTICAL_BACK_PORCH 14
#define VERTICAL_FRONT_PORCH 16 #define VERTICAL_FRONT_PORCH 16
#define VERTICAL_SYNC_WIDTH 2 #define VERTICAL_SYNC_WIDTH 2
#define FRAME_RATE 60 #define FRAME_RATE 60
```
/* PanelInfo structure */
struct PanelInfo { - Define the **PanelInfo** structure.
uint32_t width;
uint32_t height; ```c++
uint32_t hbp; struct PanelInfo {
uint32_t hfp; uint32_t width;
uint32_t hsw; uint32_t height;
uint32_t vbp; uint32_t hbp;
uint32_t vfp; uint32_t hfp;
uint32_t vsw; uint32_t hsw;
uint32_t frameRate; uint32_t vbp;
enum LcdIntfType intfType; uint32_t vfp;
enum IntfSync intfSync; uint32_t vsw;
struct MipiDsiDesc mipi; uint32_t frameRate;
struct BlkDesc blk; enum LcdIntfType intfType;
struct PwmCfg pwm; enum IntfSync intfSync;
}; struct MipiDsiDesc mipi;
struct BlkDesc blk;
/* Initialization sequence of the LCD panel */ struct PwmCfg pwm;
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 }; - Initialize the LCD.
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 }; ```c++
static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 }; static uint8_t g_payLoad0[] = { 0xF0, 0x5A, 0x5A };
static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 }; static uint8_t g_payLoad1[] = { 0xF1, 0xA5, 0xA5 };
static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 }; static uint8_t g_payLoad2[] = { 0xB3, 0x03, 0x03, 0x03, 0x07, 0x05, 0x0D, 0x0F, 0x11, 0x13, 0x09, 0x0B };
static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 }; static uint8_t g_payLoad3[] = { 0xB4, 0x03, 0x03, 0x03, 0x06, 0x04, 0x0C, 0x0E, 0x10, 0x12, 0x08, 0x0A };
static uint8_t g_payLoad10[] = { 0xb7, 0x41 }; static uint8_t g_payLoad4[] = { 0xB0, 0x54, 0x32, 0x23, 0x45, 0x44, 0x44, 0x44, 0x44, 0x60, 0x00, 0x60, 0x1C };
static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 }; static uint8_t g_payLoad5[] = { 0xB1, 0x32, 0x84, 0x02, 0x87, 0x12, 0x00, 0x50, 0x1C };
static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 }; static uint8_t g_payLoad6[] = { 0xB2, 0x73, 0x09, 0x08 };
static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 }; static uint8_t g_payLoad7[] = { 0xB6, 0x5C, 0x5C, 0x05 };
static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF }; static uint8_t g_payLoad8[] = { 0xB8, 0x23, 0x41, 0x32, 0x30, 0x03 };
static uint8_t g_payLoad15[] = { 0xD2, 0x63, 0x0B, 0x08, 0x88 }; static uint8_t g_payLoad9[] = { 0xBC, 0xD2, 0x0E, 0x63, 0x63, 0x5A, 0x32, 0x22, 0x14, 0x22, 0x03 };
static uint8_t g_payLoad16[] = { 0xC6, 0x08, 0x15, 0xFF, 0x10, 0x16, 0x80, 0x60 }; static uint8_t g_payLoad10[] = { 0xb7, 0x41 };
static uint8_t g_payLoad17[] = { 0xc7, 0x04 }; static uint8_t g_payLoad11[] = { 0xC1, 0x0c, 0x10, 0x04, 0x0c, 0x10, 0x04 };
static uint8_t g_payLoad18[] = { static uint8_t g_payLoad12[] = { 0xC2, 0x10, 0xE0 };
0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40, static uint8_t g_payLoad13[] = { 0xC3, 0x22, 0x11 };
0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, static uint8_t g_payLoad14[] = { 0xD0, 0x07, 0xFF };
0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06 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_payLoad19[] = { 0x11 }; static uint8_t g_payLoad17[] = { 0xc7, 0x04 };
static uint8_t g_payLoad20[] = { 0x29 }; static uint8_t g_payLoad18[] = {
0xC8, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52, 0x43, 0x4C, 0x40,
struct DsiCmdDesc g_OnCmd[] = { 0x3D, 0x30, 0x1E, 0x06, 0x7C, 0x50, 0x3B, 0x2C, 0x25, 0x16, 0x1C, 0x08, 0x27, 0x2B, 0x2F, 0x52,
{ 0x29, 0, sizeof(g_payLoad0), g_payLoad0 }, 0x43, 0x4C, 0x40, 0x3D, 0x30, 0x1E, 0x06
{ 0x29, 0, sizeof(g_payLoad1), g_payLoad1 }, };
{ 0x29, 0, sizeof(g_payLoad2), g_payLoad2 }, static uint8_t g_payLoad19[] = { 0x11 };
{ 0x29, 0, sizeof(g_payLoad3), g_payLoad3 }, static uint8_t g_payLoad20[] = { 0x29 };
{ 0x29, 0, sizeof(g_payLoad4), g_payLoad4 }, static DevHandle g_mipiHandle = NULL;
{ 0x29, 0, sizeof(g_payLoad5), g_payLoad5 }, static DevHandle g_pwmHandle = NULL;
{ 0x29, 0, sizeof(g_payLoad6), g_payLoad6 }, ```
{ 0x29, 0, sizeof(g_payLoad7), g_payLoad7 },
{ 0x29, 0, sizeof(g_payLoad8), g_payLoad8 }, - Set the status of the reset pin.
{ 0x29, 0, sizeof(g_payLoad9), g_payLoad9 },
{ 0x23, 0, sizeof(g_payLoad10), g_payLoad10 }, ```c++
{ 0x29, 0, sizeof(g_payLoad11), g_payLoad11 }, static int32_t LcdResetOn(void)
{ 0x29, 0, sizeof(g_payLoad12), g_payLoad12 }, {
{ 0x29, 0, sizeof(g_payLoad13), g_payLoad13 }, int32_t ret;
{ 0x29, 0, sizeof(g_payLoad14), g_payLoad14 }, ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT);
{ 0x29, 0, sizeof(g_payLoad15), g_payLoad15 }, if (ret != HDF_SUCCESS) {
{ 0x29, 0, sizeof(g_payLoad16), g_payLoad16 }, HDF_LOGE("GpioSetDir failure, ret:%d", ret);
{ 0x23, 0, sizeof(g_payLoad17), g_payLoad17 }, return HDF_FAILURE;
{ 0x29, 1, sizeof(g_payLoad18), g_payLoad18 }, }
{ 0x05, 120, sizeof(g_payLoad19), g_payLoad19 }, ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH);
{ 0x05, 120, sizeof(g_payLoad20), g_payLoad20 }, if (ret != HDF_SUCCESS) {
}; HDF_LOGE("GpioWrite failure, ret:%d", ret);
static DevHandle g_mipiHandle = NULL; return HDF_FAILURE;
static DevHandle g_pwmHandle = NULL; }
/* Set the delay to 20 ms. */
/* Set the status of the reset pin. */ OsalMSleep(20);
static int32_t LcdResetOn(void) return HDF_SUCCESS;
{ }
int32_t ret; ```
ret = GpioSetDir(RESET_GPIO, GPIO_DIR_OUT);
if (ret != HDF_SUCCESS) { - Initialize the entry function of the device driver.
HDF_LOGE("GpioSetDir failure, ret:%d", ret);
return HDF_FAILURE; ```c++
} int32_t SampleEntryInit(struct HdfDeviceObject *object)
ret = GpioWrite(RESET_GPIO, GPIO_VAL_HIGH); {
if (ret != HDF_SUCCESS) { HDF_LOGI("%s: enter", __func__);
HDF_LOGE("GpioWrite failure, ret:%d", ret); if (object == NULL) {
return HDF_FAILURE; HDF_LOGE("%s: param is null!", __func__);
} return HDF_FAILURE;
/* Set the delay to 20 ms. */ }
OsalMSleep(20); /* Register the device driver APIs with the platform driver. */
return HDF_SUCCESS; if (PanelDataRegister(&g_panelData) != HDF_SUCCESS) {
} HDF_LOGE("%s: PanelDataRegister error!", __func__);
return HDF_FAILURE;
static int32_t SampleInit(void) }
{ return HDF_SUCCESS;
/* Open the MIPI DSI device handle. */ }
g_mipiHandle = MipiDsiOpen(MIPI_DSI0);
if (g_mipiHandle == NULL) { struct HdfDriverEntry g_sampleDevEntry = {
HDF_LOGE("%s: MipiDsiOpen failure", __func__); .moduleVersion = 1,
return HDF_FAILURE; .moduleName = "LCD_SAMPLE",
} .Init = SampleEntryInit,
return HDF_SUCCESS; };
}
HDF_INIT(g_sampleDevEntry);
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,11 +4,11 @@ ...@@ -4,11 +4,11 @@
### Function ### 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 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 **Figure 1** Motion driver architecture
...@@ -23,8 +23,8 @@ The figure below illustrates how a motion driver works. ...@@ -23,8 +23,8 @@ The figure below illustrates how a motion driver works.
![](figures/motion_driver_work.png) ![](figures/motion_driver_work.png)
1. MSDP: The MSDP service obtains a Motion HDI service instance from the Motion Proxy and calls the Motion HDI API. 1. MSDP: The MSDP service obtains a Motion HDI service instance from the Motion Proxy and calls the Motion HDI API.
2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor. 2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor.
3. HDI Service: HDI Service consists of Motion Interface Driver, Motion Service, and Motion Impl. Motion Interface Driver provides the motion driver code. A **HdfDriverEntry** structure is defined to implement the **Init**, **Bind**, and **Release** functions. The **HDF_INIT** macro is used to load the driver in the functions. Motion Service provides the motion recognition service interface class. The specific implementation is described in Motion Impl. The code of HDI Service must be developed by the component vendor. 3. HDI Service: 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 ## Development Guidelines
...@@ -53,15 +53,15 @@ The development procedure is as follows: ...@@ -53,15 +53,15 @@ The development procedure is as follows:
The motion recognition directory structure is as follows: The motion recognition directory structure is as follows:
```undefined ```undefined
/drivers/peripheral/motion # Developed by the vendor. /drivers/peripheral/motion # Developed by the vendor.
├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer. ├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer.
├── test # Test code for the motion recognition module. ├── test # Test code for the motion recognition module.
│ └── unittest\hdi # HDI unit test code for the motion recognition module. │ └── unittest\hdi # HDI unit test code for the motion recognition module.
``` ```
The following describes how to develop a user-mode motion driver based on the HDF. For details, see [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp). The following describes how to develop a user-mode motion driver based on the HDF. For details, see [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp).
To develop the user-mode driver for motion recognition, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. The **Bind** function provides service capabilities. The **Init** function initializes the driver before the driver is loaded. The **Release** function releases resources when the **Init** function fails. 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++ ```c++
// Custom HdfMotionInterfaceHost object // Custom HdfMotionInterfaceHost object
...@@ -153,7 +153,6 @@ struct HdfDriverEntry g_motioninterfaceDriverEntry = { ...@@ -153,7 +153,6 @@ struct HdfDriverEntry g_motioninterfaceDriverEntry = {
HDF_INIT(g_userAuthInterfaceDriverEntry); HDF_INIT(g_userAuthInterfaceDriverEntry);
``` ```
### Verification ### Verification
The procedure is as follows: The procedure is as follows:
......
# Sensor # Sensor
## Overview ## 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 **Figure 1** Sensor driver model
![Sensor driver model](figures/sensor_driver_model.png) ![Sensor driver model](figures/sensor_driver_model.png)
### Basic Concepts ### 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 ### 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) ![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. 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). 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 corresponding sensor driver. 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. 3. The sensor host loads and initializes the sensor manager driver.
4. The sensor manager driver publishes the sensor hardware device interfaces (HDIs). 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 from the Sensor Host node of the device_info HCS. 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. 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. 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. 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. 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 ...@@ -54,34 +54,38 @@ The following uses the acceleration sensor driver on the Hi3516D V300 developmen
The sensor driver model offers the following APIs: The sensor driver model offers the following APIs:
- Sensor HDIs, for easier sensor service development - Sensor HDI APIs, for easier sensor service development
- Sensor driver model capability interfaces
- Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors - APIs for implementing sensor driver model capabilities
- Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors - APIs for loading, registering, and deregitering sensor drivers, and detecting sensors based on the HDF
- 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. - 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. 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 **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 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 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 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 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 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 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 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 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. 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 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.| | 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 ...@@ -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. 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 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.| | 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 ...@@ -121,14 +124,14 @@ The sensor driver model also provides certain driver development APIs that need
```c ```c
/* Register the entry structure object of the acceleration sensor. */ /* Register the entry structure object of the acceleration sensor. */
struct HdfDriverEntry g_sensorAccelDevEntry = { struct HdfDriverEntry g_sensorAccelDevEntry = {
.moduleVersion = 1, // Version of the acceleration sensor module. .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. .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. .Bind = BindAccelDriver, // Function for binding an acceleration sensor.
.Init = InitAccelDriver, // Function for initializing an acceleration sensor. .Init = InitAccelDriver, // Function for initializing an acceleration sensor.
.Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources. .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); HDF_INIT(g_sensorAccelDevEntry);
``` ```
...@@ -228,7 +231,7 @@ The sensor driver model also provides certain driver development APIs that need ...@@ -228,7 +231,7 @@ The sensor driver model also provides certain driver development APIs that need
return drvData->accelCfg; 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) int32_t AccelInitDriver(struct HdfDeviceObject *device)
{ {
... ...
...@@ -271,16 +274,16 @@ The sensor driver model also provides certain driver development APIs that need ...@@ -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). 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 information HCS configuration of the acceleration sensor. */
device_sensor_accel :: device { device_sensor_accel :: device {
device0 :: deviceNode { device0 :: deviceNode {
policy = 1; // Policy for publishing the driver service. policy = 1; // Policy for the driver to publish services.
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. 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; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite. 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 driver to create a device node. permission = 0664; // Permission for the device node created.
moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure. 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 provided by the driver. The name must be unique. 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. 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 ...@@ -466,7 +469,7 @@ The sensor driver model also provides certain driver development APIs that need
/* Release the resources allocated during driver initialization. */ /* Release the resources allocated during driver initialization. */
void Bmi160ReleaseDriver(struct HdfDeviceObject *device) void Bmi160ReleaseDriver(struct HdfDeviceObject *device)
{ {
...... ...
if (drvData->sensorCfg != NULL) { if (drvData->sensorCfg != NULL) {
AccelReleaseCfgData(drvData->sensorCfg); AccelReleaseCfgData(drvData->sensorCfg);
drvData->sensorCfg = NULL; drvData->sensorCfg = NULL;
...@@ -511,18 +514,12 @@ The sensor driver model also provides certain driver development APIs that need ...@@ -511,18 +514,12 @@ The sensor driver model also provides certain driver development APIs that need
} }
``` ```
>![](../public_sys-resources/icon-note.gif) **NOTE** ### Verification
>
>- 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.
### 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. ```c++
static int32_t g_sensorDataFlag = 0; // Whether to report sensor data.
```
static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data.
static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address. static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address.
/* Register the data reporting function. */ /* Register the data reporting function. */
...@@ -558,9 +555,9 @@ void HdfSensorTest::TearDownTestCase() ...@@ -558,9 +555,9 @@ void HdfSensorTest::TearDownTestCase()
/* Verify the sensor driver. */ /* Verify the sensor driver. */
HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0) HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0)
{ {
int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds. int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds.
int32_t pollTime = 5; // Data sampling duration, in seconds. int32_t pollTime = 5; // Data sampling time, in seconds.
int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1. int32_t accelSensorId = 1; // Acceleration sensor ID, which specifies the sensor type.
int32_t count = 0; int32_t count = 0;
int ret; int ret;
struct SensorInformation *sensorInfo = nullptr; struct SensorInformation *sensorInfo = nullptr;
......
# 使用显式Want启动Ability # 使用显式Want启动Ability
在应用使用场景中,当用户点击某个按钮时,应用经常需要拉起指定UIAbility组件来完成某些特定任务。下面介绍如何通过显式Want拉起应用内一个指定UIAbility组件。 在应用使用场景中,当用户在应用内点击某个按钮时,经常需要拉起指定UIAbility组件来完成某些特定任务。在启动UIAbility时,指定了abilityName和bundleName参数,可以使用显示Want方式启动UIAbility。显示Want的使用请参见[启动应用内的UIAbility](uiability-intra-device-interaction.md#启动应用内的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&gt;app.json5文件内获取;abilityName可在对应模块内的“yourModuleName &gt; src &gt; main &gt; 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按钮时,应看到页面的跳转。
<img src="figures/startAbilityWtExplicitWant.PNG" alt="startAbilityWtExplicitWant" style="zoom: 80%;" />
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
## 开发步骤 ## 开发步骤
1. 在自定义函数implicitStartAbility内使用**隐式Want**启动Ability。 1. 在自定义函数implicitStartAbility内使用**隐式Want**启动Ability。
```ts ```ts
async implicitStartAbility() { async implicitStartAbility() {
try { try {
...@@ -71,12 +71,12 @@ ...@@ -71,12 +71,12 @@
匹配过程如下: 匹配过程如下:
1. want内action不为空,且被skills内action包括,匹配成功。 1. want内action不为空,且被skills内action包括,匹配成功。
2. want内entities不为空,且被skills内entities包括,匹配成功。 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包含,匹配成功。 4. want内type不为空,且被skills内type包含,匹配成功。
2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。 2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" /> <img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
# 常见action与entities # 常见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表示该应用支持声明操作。 **[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 @@ ...@@ -15,7 +14,6 @@
- ACTION_VIEW_MULTIPLE_DATA:发送多个数据记录的操作。 - ACTION_VIEW_MULTIPLE_DATA:发送多个数据记录的操作。
**[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。 **[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。
......
...@@ -64,7 +64,7 @@ ...@@ -64,7 +64,7 @@
- "ability.picker.fileSizes":应用选择器根据该字段展示文件大小。以字节为单位。 - "ability.picker.fileSizes":应用选择器根据该字段展示文件大小。以字节为单位。
- "ability.picker.fileNames"与"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]”时,应用选择器将以下形式展示。
<img src="figures/stage-want2.png" alt="stage-want2" style="zoom:50%;" /> <img src="figures/stage-want2.png" alt="stage-want2" style="zoom:50%;" />
示例代码中“ability.want.params.INTENT”字段是一个嵌套Want,内部所含action、type等字段将由应用选择器进行隐式匹配,具体隐式匹配规则可参考[隐式Want匹配原理详解](explicit-implicit-want-mappings.md#隐式want匹配原理详解)。当用户选择具体应用后,“ability.want.params.INTENT”字段的嵌套Want将传递至所选应用。 示例代码中“ability.want.params.INTENT”字段是一个嵌套Want,内部所含action、type等字段将由应用选择器进行隐式匹配,具体隐式匹配规则可参考[隐式Want匹配原理详解](explicit-implicit-want-mappings.md#隐式want匹配原理详解)。当用户选择具体应用后,“ability.want.params.INTENT”字段的嵌套Want将传递至所选应用。
......
...@@ -49,7 +49,7 @@ ...@@ -49,7 +49,7 @@
### want参数的action匹配规则 ### 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匹配失败。 - 调用方传入的want参数的action不为空,待匹配Ability的skills配置中的actions为空,则action匹配失败。
...@@ -64,7 +64,7 @@ ...@@ -64,7 +64,7 @@
### want参数的entities匹配规则 ### 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匹配成功。 - 调用方传入的want参数的entities为空,待匹配Ability的skills配置中的entities不为空,则entities匹配成功。
...@@ -84,7 +84,7 @@ ...@@ -84,7 +84,7 @@
调用方传入的want参数中设置uri和type参数发起组件启动请求,系统会遍历当前系统已安装的组件列表,并逐个匹配待匹配Ability的skills配置中的uris数组,如果待匹配Ability的skills配置中的uris数组中只要有一个可以匹配调用方传入的want参数中设置的uri和type即为匹配成功。 调用方传入的want参数中设置uri和type参数发起组件启动请求,系统会遍历当前系统已安装的组件列表,并逐个匹配待匹配Ability的skills配置中的uris数组,如果待匹配Ability的skills配置中的uris数组中只要有一个可以匹配调用方传入的want参数中设置的uri和type即为匹配成功。
**图3** want参数中uri和type皆不为空时的匹配规则 **图3** want参数中uri和type皆不为空时的匹配规则
<img src="figures/want-uri-type1.png" alt="want-uri-type1" style="zoom: 80%;" /> <img src="figures/want-uri-type1.png" alt="want-uri-type1" style="zoom: 80%;" />
实际应用中,uri和type共存在四种情况,下面将讲解四种情况的具体匹配规则: 实际应用中,uri和type共存在四种情况,下面将讲解四种情况的具体匹配规则:
...@@ -110,7 +110,7 @@ ...@@ -110,7 +110,7 @@
下图为了简化描述,称want中传入的uri为w_uri,称want中传入的type为w_type, 待匹配Ability的skills配置中uris为s_uris,其中每个元素为s_uri;按自上而下顺序匹配。 下图为了简化描述,称want中传入的uri为w_uri,称want中传入的type为w_type, 待匹配Ability的skills配置中uris为s_uris,其中每个元素为s_uri;按自上而下顺序匹配。
**图4** want参数中uri和type的具体匹配规则 **图4** want参数中uri和type的具体匹配规则
<img src="figures/want-uri-type2.png" alt="want-uri-type2" style="zoom:80%;" /> <img src="figures/want-uri-type2.png" alt="want-uri-type2" style="zoom:80%;" />
...@@ -133,24 +133,24 @@ ...@@ -133,24 +133,24 @@
> **说明:** > **说明:**
> 待匹配Ability的skills配置的uris中scheme、host、port、path、pathStartWith和pathRegex属性拼接,如果依次声明了path、pathStartWith和pathRegex属性时,uris将分别拼接为如下三种表达式: > 待匹配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匹配规则
> **说明:** > **说明:**
> 此小节所述的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,具体的匹配规则如下: 这里为了简化描述,称want中传入的uri为w_type,待匹配Ability的skills数组中uris的type数据为s_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/`时匹配成功,否则匹配失败。
...@@ -15,15 +15,14 @@ UIAbility的启动模式是指UIAbility实例在启动时的不同呈现状态 ...@@ -15,15 +15,14 @@ UIAbility的启动模式是指UIAbility实例在启动时的不同呈现状态
singleton启动模式为单实例模式,也是默认情况下的启动模式。 singleton启动模式为单实例模式,也是默认情况下的启动模式。
每次调用startAbility()方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。 每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。
**图1** 单实例模式演示效果 **图1** 单实例模式演示效果
<img src="figures/uiability-launch-type1.png" alt="uiability-launch-type1" style="zoom:50%;" /> <img src="figures/uiability-launch-type1.png" alt="uiability-launch-type1" width="40%;" />
> **说明:** > **说明**:应用的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)生命周期回调。
> 应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用startAbility()方法启动该UIAbility实例,此时只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其onCreate()和onWindowStageCreate()生命周期回调。
如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的"launchType"字段配置为"singleton"即可。 如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`singleton`即可。
```json ```json
...@@ -43,12 +42,12 @@ singleton启动模式为单实例模式,也是默认情况下的启动模式 ...@@ -43,12 +42,12 @@ singleton启动模式为单实例模式,也是默认情况下的启动模式
## standard启动模式 ## standard启动模式
standard启动模式为标准实例模式,每次调用startAbility()方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。 standard启动模式为标准实例模式,每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。
**图2** 标准实例模式演示效果 **图2** 标准实例模式演示效果
<img src="figures/standard-mode.png" alt="standard-mode" style="zoom:50%;" /> <img src="figures/standard-mode.png" alt="standard-mode" width="40%;" />
standard启动模式的开发使用,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的"launchType"字段配置为"standard"即可。 standard启动模式的开发使用,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`standard`即可。
```json ```json
...@@ -70,19 +69,12 @@ standard启动模式的开发使用,在[module.json5配置文件](../quick-sta ...@@ -70,19 +69,12 @@ standard启动模式的开发使用,在[module.json5配置文件](../quick-sta
specified启动模式为指定实例模式,针对一些特殊场景使用(例如文档应用中每次新建文档希望都能新建一个文档实例,重复打开一个已保存的文档希望打开的都是同一个文档实例)。 specified启动模式为指定实例模式,针对一些特殊场景使用(例如文档应用中每次新建文档希望都能新建一个文档实例,重复打开一个已保存的文档希望打开的都是同一个文档实例)。
在UIAbility实例创建之前,允许开发者为该实例创建一个唯一的字符串Key,创建的UIAbility实例绑定Key之后,后续每次调用startAbility()方法时,都会询问应用使用哪个Key对应的UIAbility实例来响应startAbility()请求。运行时由UIAbility内部业务决定是否创建多实例,如果匹配有该UIAbility实例的Key,则直接拉起与之绑定的UIAbility实例,否则创建一个新的UIAbility实例。 **图3** 指定实例模式演示效果
**图3** 指定实例模式演示效果
<img src="figures/uiability-launch-type2.png" alt="uiability-launch-type2" style="zoom:50%;" /> <img src="figures/uiability-launch-type2.png" alt="uiability-launch-type2" style="zoom:50%;" />
> **说明:** 例如有两个UIAbility:EntryAbility和SpecifiedAbility,SpecifiedAbility配置为specified启动模式,需要从EntryAbility的页面中启动SpecifiedAbility。
>
> 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。
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 ```json
{ {
...@@ -98,7 +90,8 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( ...@@ -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 ```ts
// 在启动指定实例模式的UIAbility时,给每一个UIAbility实例配置一个独立的Key标识 // 在启动指定实例模式的UIAbility时,给每一个UIAbility实例配置一个独立的Key标识
...@@ -110,7 +103,7 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( ...@@ -110,7 +103,7 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
let want = { let want = {
deviceId: '', // deviceId为空表示本设备 deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility', abilityName: 'SpecifiedAbility',
moduleName: 'module1', // moduleName非必选 moduleName: 'module1', // moduleName非必选
parameters: { // 自定义信息 parameters: { // 自定义信息
instanceKey: getInstance(), instanceKey: getInstance(),
...@@ -123,8 +116,9 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( ...@@ -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 ```ts
import AbilityStage from '@ohos.app.ability.AbilityStage'; import AbilityStage from '@ohos.app.ability.AbilityStage';
...@@ -132,19 +126,24 @@ specified启动模式为指定实例模式,针对一些特殊场景使用( ...@@ -132,19 +126,24 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onAcceptWant(want): string { onAcceptWant(want): string {
// 在被调用方的AbilityStage中,针对启动模式为specified的UIAbility返回一个UIAbility实例对应的一个Key值 // 在被调用方的AbilityStage中,针对启动模式为specified的UIAbility返回一个UIAbility实例对应的一个Key值
// 当前示例指的是module1 Module的FuncAbility // 当前示例指的是module1 Module的SpecifiedAbility
if (want.abilityName === 'FuncAbility') { if (want.abilityName === 'SpecifiedAbility') {
// 返回的字符串Key标识为自定义拼接的字符串内容 // 返回的字符串Key标识为自定义拼接的字符串内容
return `FuncAbilityInstance_${want.parameters.instanceKey}`; return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`;
} }
return ''; 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时,打开的仍然是之前原来已保存的文档界面。 例如在文档应用中,可以对不同的文档实例内容绑定不同的Key值。当每次新建文档的时候,可以传入不同的新Key值(如可以将文件的路径作为一个Key标识),此时AbilityStage中启动UIAbility时都会创建一个新的UIAbility实例;当新建的文档保存之后,回到桌面,或者新打开一个已保存的文档,回到桌面,此时再次打开该已保存的文档,此时AbilityStage中再次启动该UIAbility时,打开的仍然是之前原来已保存的文档界面。
以如下步骤所示进行举例说明。 以如下步骤所示进行举例说明。
1. 打开文件A,对应启动一个新的UIAbility实例,例如启动“UIAbility实例1”。 1. 打开文件A,对应启动一个新的UIAbility实例,例如启动“UIAbility实例1”。
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
## Want的类型 ## Want的类型
- **显式Want**:在启动Ability时指定了abilityName和bundleName的Want称为显式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 ```ts
let wantInfo = { let wantInfo = {
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
} }
``` ```
- **隐式Want**:在启动UIAbility时未指定abilityName的Want称为隐式Want。 - **隐式Want**:在启动Ability时未指定abilityName的Want称为隐式Want。
当请求处理的对象不明确时,希望在当前应用中使用其他应用提供的某个能力(通过[skills标签](../quick-start/module-configuration-file.md#skills标签)定义),而不关心提供该能力的具体应用,可以使用隐式Want。例如使用隐式Want描述需要打开一个链接的请求,而不关心通过具体哪个应用打开,系统将匹配声明支持该请求的所有应用。 当请求处理的对象不明确时,希望在当前应用中使用其他应用提供的某个能力(通过[skills标签](../quick-start/module-configuration-file.md#skills标签)定义),而不关心提供该能力的具体应用,可以使用隐式Want。例如使用隐式Want描述需要打开一个链接的请求,而不关心通过具体哪个应用打开,系统将匹配声明支持该请求的所有应用。
...@@ -47,18 +47,3 @@ ...@@ -47,18 +47,3 @@
> - 调用方传入的want参数中不带有abilityName和bundleName,则不允许通过隐式Want启动所有应用的ServiceExtensionAbility。 > - 调用方传入的want参数中不带有abilityName和bundleName,则不允许通过隐式Want启动所有应用的ServiceExtensionAbility。
> >
> - 调用方传入的want参数中带有bundleName,则允许使用startServiceExtensionAbility()方法隐式Want启动ServiceExtensionAbility,默认返回优先级最高的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,&nbsp;schemeSpecificPart,&nbsp;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&lt;string&gt; | 否 | 表示目标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:&nbsp;string]:&nbsp;any} | 否 | 此参数用于传递自定义数据,通过用户自定义的键值对进行数据填充,具体支持的数据类型如[Want&nbsp;API](../reference/apis/js-apis-app-ability-want.md)所示。 |
...@@ -7,7 +7,7 @@ ...@@ -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 @@ ...@@ -17,8 +17,8 @@
| 接口名 | 描述 | | 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise&lt;RdbStoreV9&gt; | 获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。<br/>-context:应用程序或功能的上下文。<br/>-config:与此RDB存储相关的数据库配置。<br/>-version:数据库版本。目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 | | getRdbStore(context: Context, config: StoreConfig): Promise&lt;RdbStore&gt; | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。<br/>-context:应用上下文。<br/>-config:与此RDB存储相关的数据库配置。 |
| deleteRdbStoreV9(context: Context, name: string): Promise&lt;void&gt; | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。<br/>-context:应用程序或功能的上下文。<br/>-name:数据库名称。 | | deleteRdbStore(context: Context, name: string): Promise&lt;void&gt; | 使用指定的数据库文件配置删除数据库,使用Promise异步回调。<br/>-context:应用上下文。<br/>-name:数据库名称。 |
### 数据库的增删改查 ### 数据库的增删改查
...@@ -33,29 +33,29 @@ ...@@ -33,29 +33,29 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | 向目标表中插入一行数据,使用Promise异步回调。<br>如果操作成功,返回行ID;否则返回-1。<br/>-table:指定的目标表名。<br/>-values:表示要插入到表中的数据行。 | | RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | 向目标表中插入一行数据,使用Promise异步回调。<br>如果操作成功,返回行ID;否则返回-1。<br/>-table:指定的目标表名。<br/>-values:表示要插入到表中的数据行。 |
- **更新** - **更新**
调用更新接口,传入要更新的数据,并通过RdbPredicatesV9指定更新条件。该接口的返回值表示更新操作影响的行数。如果更新失败,则返回0。 调用更新接口,传入要更新的数据,并通过RdbPredicates指定更新条件。该接口的返回值表示更新操作影响的行数。如果更新失败,则返回0。
**表3** 数据库更新API **表3** 数据库更新API
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise&lt;number&gt; | 根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-values:以ValuesBucket存储的要更新的数据。<br/>-predicates:表示RdbPredicatesV9的实例对象指定的更新条件。 | | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。<br>返回受影响的行数。<br/>-values:以ValuesBucket存储的要更新的数据。<br/>-predicates:表示RdbPredicates的实例对象指定的更新条件。 |
- **删除** - **删除**
调用删除接口,通过RdbPredicatesV9指定删除条件。该接口的返回值表示删除的数据行数,可根据此值判断是否删除成功。如果删除失败,则返回0。 调用删除接口,通过RdbPredicates指定删除条件。该接口的返回值表示删除的数据行数,可根据此值判断是否删除成功。如果删除失败,则返回0。
**表4** 数据库删除API **表4** 数据库删除API
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ | | ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
| RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise&lt;number&gt; | 根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。<br>返回受影响的行数。 <br/>-predicates:RdbPredicatesV9的实例对象指定的删除条件。 | | RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | 根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。<br>返回受影响的行数。 <br/>-predicates:RdbPredicates的实例对象指定的删除条件。 |
- **查询** - **查询**
...@@ -66,35 +66,34 @@ ...@@ -66,35 +66,34 @@
**表5** 数据库查询API **表5** 数据库查询API
| 类名 | 接口名 | 描述 |
| 类名 | 接口名 | 描述 | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | RdbStore | query(predicates: RdbPredicates, columns?: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | 根据指定条件查询数据库中的数据,使用Promise异步回调。<br/>-predicates:表示RdbPredicates的实例对象指定的查询条件。<br/>-columns:表示要查询的列。如果值为空,则查询应用于所有列。 |
| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array&lt;string&gt;): Promise&lt;ResultSetV9&gt; | 根据指定条件查询数据库中的数据,使用Promise异步回调。<br/>-predicates:表示RdbPredicatesV9的实例对象指定的查询条件。<br/>-columns:表示要查询的列。如果值为空,则查询应用于所有列。 | | RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;): Promise&lt;ResultSet&gt; | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。<br/>-sql:指定要查询的SQL语句。<br/>-bindArgs:SQL语句中参数的值。 |
| RdbStoreV9 | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;): Promise&lt;ResultSetV9&gt; | 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。<br/>-sql:指定要查询的SQL语句。<br/>-bindArgs:SQL语句中参数的值。 | | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | 根据指定条件查询指定远程设备数据库中的数据。使用Promise异步回调。<br/>-device:指定远程查询的设备networkId。<br/>-table:指定远程查询的表名。<br/>-predicates:表示RdbPredicates的实例对象,指定查询的条件。<br/>-columns:表示要查询的列。如果值为空,则查询应用于所有列。 |
| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array&lt;string&gt;): Promise&lt;ResultSetV9&gt; | 根据指定条件查询指定远程设备数据库中的数据。使用Promise异步回调。<br/>-device:指定远程查询的设备networkId。<br/>-table:指定远程查询的表名。<br/>-predicates:表示RdbPredicatesV9的实例对象,指定查询的条件。<br/>-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 **表6** 数据库谓词API
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicatesV9:返回与指定字段匹配的谓词。 | | RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicatesV9:返回与指定字段匹配的谓词。 | | RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回与指定字段匹配的谓词。 |
| RdbPredicatesV9 | or(): RdbPredicatesV9 | 将或条件添加到谓词中。<br/>-RdbPredicatesV9:返回带有或条件的谓词。 | | RdbPredicates | or(): RdbPredicates | 将或条件添加到谓词中。<br/>-RdbPredicates:返回带有或条件的谓词。 |
| RdbPredicatesV9 | and(): RdbPredicatesV9 | 向谓词添加和条件。<br/>-RdbPredicatesV9:返回带有和条件的谓词。 | | RdbPredicates | and(): RdbPredicates | 向谓词添加和条件。<br/>-RdbPredicates:返回带有和条件的谓词。 |
| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | 配置谓词以匹配数据字段为String且value包含指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicatesV9:返回带有包含条件的谓词。 | | RdbPredicates | contains(field: string, value: string): RdbPredicates | 配置谓词以匹配数据字段为String且value包含指定值的字段。<br/>-field:数据库表中的列名。<br/>-value:指示要与谓词匹配的值。<br/>-RdbPredicates:返回带有包含条件的谓词。 |
### 查询结果集的使用 ### 查询结果集的使用
关系型数据库提供了查询返回的结果集ResultSetV9,其指向查询结果中的一行数据,供用户对查询结果进行遍历和访问。 关系型数据库提供了查询返回的结果集ResultSet,其指向查询结果中的一行数据,供用户对查询结果进行遍历和访问。
更多结果集的接口使用,请见[结果集](../reference/apis/js-apis-data-resultset.md) 更多结果集的接口使用,请见[结果集](../reference/apis/js-apis-data-relationalStore.md#resultset)
> **须知:** > **须知:**
> **结果集使用完后,请一定要调用close方法显式关闭。** > **结果集使用完后,请一定要调用close方法显式关闭。**
...@@ -103,12 +102,12 @@ ...@@ -103,12 +102,12 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ----------- | ---------------------------------------- | ------------------------------------------ | | ----------- | ---------------------------------------- | ------------------------------------------ |
| ResultSetV9 | goToFirstRow(): boolean | 将结果集移动到第一行。 | | ResultSet | goToFirstRow(): boolean | 将结果集移动到第一行。 |
| ResultSetV9 | getString(columnIndex: number): string | 获取当前行指定列的值,以String类型返回。 | | ResultSet | getString(columnIndex: number): string | 获取当前行指定列的值,以String类型返回。 |
| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 | | ResultSet | getBlob(columnIndex: number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 |
| ResultSetV9 | getDouble(columnIndex: number): number | 获取当前行指定列的值,以double型返回。 | | ResultSet | getDouble(columnIndex: number): number | 获取当前行指定列的值,以double型返回。 |
| ResultSetV9 | getLong(columnIndex: number): number | 获取当前行指定列的值,以Long形式返回。 | | ResultSet | getLong(columnIndex: number): number | 获取当前行指定列的值,以Long形式返回。 |
| ResultSetV9 | close(): void | 关闭结果集。 | | ResultSet | close(): void | 关闭结果集。 |
...@@ -116,7 +115,7 @@ ...@@ -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)。 > - 使用分布式列表前,需要先建立设备间组网,具体接口及使用可见[设备管理](../reference/apis/js-apis-device-manager.md)。
**设置分布式列表** **设置分布式列表**
...@@ -125,7 +124,7 @@ ...@@ -125,7 +124,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | setDistributedTables(tables: Array\<string>): Promise\<void> | 设置分布式列表,使用Promise异步回调。<br/>-tables:要设置的分布式列表表名。 | | RdbStore | setDistributedTables(tables: Array\<string>): Promise\<void> | 设置分布式列表,使用Promise异步回调。<br/>-tables:要设置的分布式列表表名。 |
**根据本地表名获取指定远程设备的分布式表名** **根据本地表名获取指定远程设备的分布式表名**
...@@ -135,7 +134,7 @@ ...@@ -135,7 +134,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | obtainDistributedTableName(device: string, table: string): Promise\<string> | 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。<br/>-device:远程设备。<br/>-table:本地表名。 | | RdbStore | obtainDistributedTableName(device: string, table: string): Promise\<string> | 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。<br/>-device:远程设备。<br/>-table:本地表名。 |
**在设备之间同步数据** **在设备之间同步数据**
...@@ -143,7 +142,7 @@ ...@@ -143,7 +142,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\<Array\<[string, number]>> | 在设备之间同步数据,使用Promise异步回调。<br/>-mode:指同步模式。SYNC_MODE_PUSH 表示数据从本地设备推送到远程设备;SYNC_MODE_PULL 表示数据从远程设备拉至本地设备。<br/>-predicates:约束同步数据和设备。<br>-string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 | | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | 在设备之间同步数据,使用Promise异步回调。<br/>-mode:指同步模式。SYNC_MODE_PUSH 表示数据从本地设备推送到远程设备;SYNC_MODE_PULL 表示数据从远程设备拉至本地设备。<br/>-predicates:约束同步数据和设备。<br>-string:设备ID;number:每个设备同步状态,0表示成功,其他值表示失败。 |
**注册数据库的观察者** **注册数据库的观察者**
...@@ -151,7 +150,7 @@ ...@@ -151,7 +150,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | on(event: 'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void | 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。<br/>-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。<br/>-observer:指分布式数据库中数据更改事件的观察者。 | | RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void | 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。<br/>-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。<br/>-observer:指分布式数据库中数据更改事件的观察者。 |
**从数据库中删除指定类型的指定观察者** **从数据库中删除指定类型的指定观察者**
...@@ -159,7 +158,7 @@ ...@@ -159,7 +158,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void; | 从数据库中删除指定类型的指定观察者,使用callback异步回调。<br/>-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。<br/>-observer:指已注册的数据更改观察者。 | | RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void; | 从数据库中删除指定类型的指定观察者,使用callback异步回调。<br/>-type:订阅类型;SUBSCRIBE_TYPE_REMOTE 订阅远程数据更改。<br/>-observer:指已注册的数据更改观察者。 |
### 数据库的备份和恢复 ### 数据库的备份和恢复
...@@ -169,7 +168,7 @@ ...@@ -169,7 +168,7 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | --------------------------------------------- | ------------------------------------------------------------ | | ---------- | --------------------------------------------- | ------------------------------------------------------------ |
| RdbStoreV9 | backup(destName: string): Promise&lt;void&gt; | 以指定名称备份数据库,使用Promise异步回调。<br/>-destName:指定数据库的备份文件名。 | | RdbStore | backup(destName: string): Promise&lt;void&gt; | 以指定名称备份数据库,使用Promise异步回调。<br/>-destName:指定数据库的备份文件名。 |
**恢复** **恢复**
...@@ -177,17 +176,17 @@ ...@@ -177,17 +176,17 @@
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| ---------- | --------------------------------------------- | ------------------------------------------------------------ | | ---------- | --------------------------------------------- | ------------------------------------------------------------ |
| RdbStoreV9 | restore(srcName: string): Promise&lt;void&gt; | 从指定的数据库备份文件恢复数据库,使用Promise异步回调。<br/>-srcName:指定数据库的备份文件名。 | | RdbStore | restore(srcName: string): Promise&lt;void&gt; | 从指定的数据库备份文件恢复数据库,使用Promise异步回调。<br/>-srcName:指定数据库的备份文件名。 |
**事务** ### 事务
**表15** 事务 **表15** 事务
| 类名 | 接口名 | 描述 | | 类名 | 接口名 | 描述 |
| -------- | ----------------------- | --------------------------------- | | -------- | ----------------------- | --------------------------------- |
| RdbStoreV9 | beginTransaction(): void | 在开始执行SQL语句之前,开始事务。 | | RdbStore | beginTransaction(): void | 在开始执行SQL语句之前,开始事务。 |
| RdbStoreV9 | commit(): void | 提交已执行的SQL语句。 | | RdbStore | commit(): void | 提交已执行的SQL语句。 |
| RdbStoreV9 | rollBack(): void | 回滚已经执行的SQL语句。 | | RdbStore | rollBack(): void | 回滚已经执行的SQL语句。 |
## 开发步骤 ## 开发步骤
...@@ -202,23 +201,23 @@ ...@@ -202,23 +201,23 @@
FA模型示例: FA模型示例:
```js ```js
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.relationalStore'
// 获取context // 获取context
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext() 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 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} securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStoreV9.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
``` ```
Stage模型示例: Stage模型示例:
```ts ```ts
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.relationalStore'
// 获取context // 获取context
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
let context = null let context = null
...@@ -230,10 +229,10 @@ ...@@ -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 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} securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStoreV9.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
``` ```
...@@ -247,9 +246,24 @@ ...@@ -247,9 +246,24 @@
示例代码如下: 示例代码如下:
```js ```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 } 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. 查询数据。 3. 查询数据。
...@@ -263,17 +277,17 @@ ...@@ -263,17 +277,17 @@
示例代码如下: 示例代码如下:
```js ```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("test"); let predicates = new data_rdb.RdbPredicates("test");
predicatesV9.equalTo("name", "Tom") predicates.equalTo("name", "Tom")
let promisequery = rdbStoreV9.query(predicatesV9) let promisequery = rdbStore.query(predicates)
promisequery.then((resultSetV9) => { promisequery.then((resultSet) => {
resultSetV9.goToFirstRow() resultSet.goToFirstRow()
const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id")) const id = resultSet.getLong(resultSet.getColumnIndex("id"))
const name = resultSetV9.getString(resultSetV9.getColumnIndex("name")) const name = resultSet.getString(resultSet.getColumnIndex("name"))
const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age")) const age = resultSet.getLong(resultSet.getColumnIndex("age"))
const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary")) const salary = resultSet.getDouble(resultSet.getColumnIndex("salary"))
const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
resultSetV9.close() resultSet.close()
}) })
``` ```
...@@ -301,7 +315,7 @@ ...@@ -301,7 +315,7 @@
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`result.requestCode=${result.requestCode}`)
}) })
let promise = rdbStoreV9.setDistributedTables(["test"]) let promise = rdbStore.setDistributedTables(["test"])
promise.then(() => { promise.then(() => {
console.info("setDistributedTables success.") console.info("setDistributedTables success.")
}).catch((err) => { }).catch((err) => {
...@@ -320,9 +334,9 @@ ...@@ -320,9 +334,9 @@
示例代码如下: 示例代码如下:
```js ```js
let predicateV9 = new data_rdb.RdbPredicatesV9('test') let predicate = new data_rdb.RdbPredicates('test')
predicateV9.inDevices(['12345678abcde']) predicate.inDevices(['12345678abcde'])
let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9) let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate)
promise.then((result) => { promise.then((result) => {
console.log('sync done.') console.log('sync done.')
for (let i = 0; i < result.length; i++) { for (let i = 0; i < result.length; i++) {
...@@ -349,7 +363,7 @@ ...@@ -349,7 +363,7 @@
} }
try { try {
rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver)
} catch (err) { } catch (err) {
console.log('register observer failed') console.log('register observer failed')
} }
...@@ -364,8 +378,8 @@ ...@@ -364,8 +378,8 @@
示例代码如下: 示例代码如下:
```js ```js
let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test"); let tableName = rdbStore.obtainDistributedTableName(deviceId, "test");
let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName) let resultSet = rdbStore.querySql("SELECT * FROM " + tableName)
``` ```
8. 远程查询。 8. 远程查询。
...@@ -378,17 +392,17 @@ ...@@ -378,17 +392,17 @@
示例代码如下: 示例代码如下:
```js ```js
let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee') let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicatesV9.greaterThan("id", 0) predicates.greaterThan("id", 0)
let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
promiseQuery.then((resultSetV9) => { promiseQuery.then((resultSet) => {
while (resultSetV9.goToNextRow()) { while (resultSet.goToNextRow()) {
let idx = resultSetV9.getLong(0); let idx = resultSet.getLong(0);
let name = resultSetV9.getString(1); let name = resultSet.getString(1);
let age = resultSetV9.getLong(2); let age = resultSet.getLong(2);
console.info(idx + " " + name + " " + age); console.info(idx + " " + name + " " + age);
} }
resultSetV9.close(); resultSet.close();
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.info("failed to remoteQuery, err: " + err)
}) })
...@@ -401,7 +415,7 @@ ...@@ -401,7 +415,7 @@
示例代码如下: 示例代码如下:
```js ```js
let promiseBackup = rdbStoreV9.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info('Backup success.')
}).catch((err) => { }).catch((err) => {
...@@ -413,7 +427,7 @@ ...@@ -413,7 +427,7 @@
示例代码如下: 示例代码如下:
```js ```js
let promiseRestore = rdbStoreV9.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info('Restore success.')
}).catch((err) => { }).catch((err) => {
......
...@@ -191,7 +191,7 @@ currentSession.on('playNext', () => { ...@@ -191,7 +191,7 @@ currentSession.on('playNext', () => {
}); });
console.log("调用AudioPlayer.play方法"); 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(() => { currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => {
console.info('setAVPlaybackState successfully'); console.info('setAVPlaybackState successfully');
}).catch((err) => { }).catch((err) => {
...@@ -286,7 +286,7 @@ currentSession.off('outputDeviceChange'); ...@@ -286,7 +286,7 @@ currentSession.off('outputDeviceChange');
// 去激活session并销毁对象 // 去激活session并销毁对象
currentSession.deactivate().then(() => { currentSession.deactivate().then(() => {
currentSession.destory(); currentSession.destroy();
}); });
``` ```
......
...@@ -91,7 +91,9 @@ struct MyComponent { ...@@ -91,7 +91,9 @@ struct MyComponent {
- 支持多个实例:一个组件中可以定义多个标有@Prop的属性; - 支持多个实例:一个组件中可以定义多个标有@Prop的属性;
- 创建自定义组件时将值传递给@Prop变量进行初始化:在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。 - 创建自定义组件时将值传递给@Prop变量进行初始化:在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。
> **说明:** @Prop修饰的变量不能在组件内部进行初始化。 > **说明:**
>
> @Prop修饰的变量不能在组件内部进行初始化。
**示例:** **示例:**
...@@ -158,7 +160,9 @@ struct CountDownComponent { ...@@ -158,7 +160,9 @@ struct CountDownComponent {
- 双向通信:子组件对@Link变量的更改将同步修改父组件中的@State变量; - 双向通信:子组件对@Link变量的更改将同步修改父组件中的@State变量;
- 创建自定义组件时需要将变量的引用传递给@Link变量,在创建组件的新实例时,必须使用命名参数初始化所有@Link变量。@Link变量可以使用@State变量或@Link变量的引用进行初始化,@State变量可以通过`'$'`操作符创建引用。 - 创建自定义组件时需要将变量的引用传递给@Link变量,在创建组件的新实例时,必须使用命名参数初始化所有@Link变量。@Link变量可以使用@State变量或@Link变量的引用进行初始化,@State变量可以通过`'$'`操作符创建引用。
> **说明:** @Link修饰的变量不能在组件内部进行初始化。 > **说明:**
>
> @Link修饰的变量不能在组件内部进行初始化。
**简单类型示例:** **简单类型示例:**
...@@ -395,7 +399,9 @@ struct ViewB { ...@@ -395,7 +399,9 @@ struct ViewB {
@Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。@Consume在感知到@Provide数据的更新后,会触发当前自定义组件的重新渲染。 @Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。@Consume在感知到@Provide数据的更新后,会触发当前自定义组件的重新渲染。
> **说明:** 使用@Provide和@Consume时应避免循环引用导致死循环。 > **说明:**
>
> 使用@Provide和@Consume时应避免循环引用导致死循环。
### @Provide ### @Provide
......
# 应用配置文件概述(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组件的描述信息。
- 应用运行过程中所需的权限信息。
# @ohos.app.ability.Want (Want) # @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'; ...@@ -19,25 +19,25 @@ import Want from '@ohos.app.ability.Want';
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 | | deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 |
| bundleName | string | 否 | 表示Bundle名称。 | | bundleName | string | 否 | 表示待启动Ability所在的应用Bundle名称。 |
| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 | | moduleName | string | 否 | 表示待启动的Ability所属的模块名称。 |
| uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 | | abilityName | string | 否 | 表示待启动Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 | | [action](js-apis-app-ability-wantConstant.md#wantConstant.Action) | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。隐式Want定义及匹配规则请参见[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-app-ability-wantConstant.md#wantConstant.Flags)。 | | [entities](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 |
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) | | uri | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在Want中指定了uri,则Want将匹配指定的Uri信息,包括`scheme``schemeSpecificPart``authority``path`信息。 |
| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 | | type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义请参见https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | | parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<br />- ohos.aafwk.callerPid:表示拉起方的pid。<br />- ohos.aafwk.param.callerToken:表示拉起方的token。<br />- ohos.aafwk.param.callerUid:表示[BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1)中的uid,应用包里应用程序的uid。 |
| moduleName | string | 否 | 表示待启动的Ability所属的模块(module)。 | | [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | 否 | 表示处理Want的方式。默认传数字。<br />例如通过wantConstant.Flags.FLAG_ABILITY_CONTINUATION表示是否以设备间迁移方式启动Ability。 |
**示例:** **示例:**
- 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象) - 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。
```ts ```ts
let want = { let want = {
"deviceId": "", // deviceId为空表示本设备 "deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test", "bundleName": "com.example.myapplication",
"abilityName": "MainAbility", "abilityName": "FuncAbility",
"moduleName": "entry" // moduleName非必选 "moduleName": "entry" // moduleName非必选
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
...@@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want'; ...@@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want';
}) })
``` ```
- 通过自定字段传递数据, 以下为当前支持类型。(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象) - 通过自定字段传递数据, 以下为当前支持类型(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。
* 字符串(String) * 字符串(String)
```ts ```ts
let want = { let want = {
bundleName: "com.example.demo", bundleName: "com.example.myapplication",
abilityName: "com.example.demo.MainAbility", abilityName: "FuncAbility",
parameters: { parameters: {
keyForString: "str", keyForString: "str",
}, },
...@@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want'; ...@@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want';
* 数字(Number) * 数字(Number)
```ts ```ts
let want = { let want = {
bundleName: "com.example.demo", bundleName: "com.example.myapplication",
abilityName: "com.example.demo.MainAbility", abilityName: "FuncAbility",
parameters: { parameters: {
keyForInt: 100, keyForInt: 100,
keyForDouble: 99.99, keyForDouble: 99.99,
...@@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want'; ...@@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want';
* 布尔(Boolean) * 布尔(Boolean)
```ts ```ts
let want = { let want = {
bundleName: "com.example.demo", bundleName: "com.example.myapplication",
abilityName: "com.example.demo.MainAbility", abilityName: "FuncAbility",
parameters: { parameters: {
keyForBool: true, keyForBool: true,
}, },
...@@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want'; ...@@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want';
* 对象(Object) * 对象(Object)
```ts ```ts
let want = { let want = {
bundleName: "com.example.demo", bundleName: "com.example.myapplication",
abilityName: "com.example.demo.MainAbility", abilityName: "FuncAbility",
parameters: { parameters: {
keyForObject: { keyForObject: {
keyForObjectString: "str", keyForObjectString: "str",
...@@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want'; ...@@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want';
* 数组(Array) * 数组(Array)
```ts ```ts
let want = { let want = {
bundleName: "com.example.demo", bundleName: "com.example.myapplication",
abilityName: "com.example.demo.MainAbility", abilityName: "FuncAbility",
parameters: { parameters: {
keyForArrayString: ["str1", "str2", "str3"], keyForArrayString: ["str1", "str2", "str3"],
keyForArrayInt: [100, 200, 300, 400], keyForArrayInt: [100, 200, 300, 400],
...@@ -109,30 +109,29 @@ import Want from '@ohos.app.ability.Want'; ...@@ -109,30 +109,29 @@ import Want from '@ohos.app.ability.Want';
``` ```
* 文件描述符(FD) * 文件描述符(FD)
```ts ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let fd; let fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) { } catch(e) {
console.log("openSync fail:" + JSON.stringify(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为空表示本设备 this.context.startAbility(want, (error) => {
"bundleName": "com.extreme.test", // 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability
"abilityName": "MainAbility", console.log("error.code = " + error.code)
"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)
})
``` ```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want - 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want
<!--no_check--> <!--no_check-->
...@@ -48,20 +48,17 @@ createFormBindingData(obj?: Object | string): FormBindingData ...@@ -48,20 +48,17 @@ createFormBindingData(obj?: Object | string): FormBindingData
**示例:** **示例:**
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility'; import fs from '@ohos.file.fs';
import fileio from '@ohos.fileio'; import formBindingData from '@ohos.app.form.formBindingData';
let context=featureAbility.getContext();
context.getOrCreateLocalDir((err,data)=>{ try {
let path=data+"/xxx.jpg"; let fd = fs.openSync('/path/to/form.png')
let fd = fileio.openSync(path);
let obj = { let obj = {
"temperature": "21°", "temperature": "21°",
"formImages": {"image": fd} "formImages": { "image": fd }
}; };
try { formBindingData.createFormBindingData(obj);
formBindingData.createFormBindingData(obj); } catch (error) {
} catch (error) { console.log(`catch error, code: ${error.code}, message: ${error.message})`);
console.log(`catch err->${JSON.stringify(err)}`); }
}
})
``` ```
\ No newline at end of file
...@@ -33,7 +33,7 @@ onAddForm(want: Want): formBindingData.FormBindingData ...@@ -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 ...@@ -45,17 +45,19 @@ onAddForm(want: Want): formBindingData.FormBindingData
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) { onAddForm(want) {
console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); console.log('FormExtensionAbility onAddForm, want:' + want.abilityName);
let dataObj1 = { let dataObj1 = {
temperature:"11c", temperature: "11c",
"time":"11:00" "time": "11:00"
}; };
let obj1 = formBindingData.createFormBindingData(dataObj1); let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1; return obj1;
} }
} };
``` ```
## onCastToNormalForm ## onCastToNormalForm
...@@ -75,11 +77,13 @@ onCastToNormalForm(formId: string): void ...@@ -75,11 +77,13 @@ onCastToNormalForm(formId: string): void
**示例:** **示例:**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId) { onCastToNormalForm(formId) {
console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId);
} }
} };
``` ```
## onUpdateForm ## onUpdateForm
...@@ -99,17 +103,24 @@ onUpdateForm(formId: string): void ...@@ -99,17 +103,24 @@ onUpdateForm(formId: string): void
**示例:** **示例:**
```ts ```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 { export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId) { onUpdateForm(formId) {
console.log('FormExtensionAbility onUpdateForm, formId:' + formId); console.log('FormExtensionAbility onUpdateForm, formId:' + formId);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); let obj2 = formBindingData.createFormBindingData({
this.context.updateForm(formId, obj2).then((data)=>{ temperature: "22c",
time: "22:00"
});
formProvider.updateForm(formId, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data:' + data); console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => { }).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);}); console.error('Operation updateForm failed. Cause: ' + error);
} });
} }
};
``` ```
## onChangeFormVisibility ## onChangeFormVisibility
...@@ -129,21 +140,28 @@ onChangeFormVisibility(newStatus: { [key: string]: number }): void ...@@ -129,21 +140,28 @@ onChangeFormVisibility(newStatus: { [key: string]: number }): void
**示例:** **示例:**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData' import formBindingData from '@ohos.app.form.formBindingData'
import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus) { onChangeFormVisibility(newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); let obj2 = formBindingData.createFormBindingData({
temperature: "22c",
for (let key in newStatus) { time: "22:00"
console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); });
this.context.updateForm(key, obj2).then((data)=>{
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); console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => { }).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);}); console.error('Operation updateForm failed. Cause: ' + error);
});
} }
} }
} };
``` ```
## onFormEvent ## onFormEvent
...@@ -164,11 +182,13 @@ onFormEvent(formId: string, message: string): void ...@@ -164,11 +182,13 @@ onFormEvent(formId: string, message: string): void
**示例:** **示例:**
```ts ```ts
export default class MyFormExtension extends FormExtensionAbility { import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) { onFormEvent(formId, message) {
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
} }
} };
``` ```
## onRemoveForm ## onRemoveForm
...@@ -188,11 +208,13 @@ onRemoveForm(formId: string): void ...@@ -188,11 +208,13 @@ onRemoveForm(formId: string): void
**示例:** **示例:**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId) { onRemoveForm(formId) {
console.log('FormExtensionAbility onRemoveForm, formId:' + formId); console.log('FormExtensionAbility onRemoveForm, formId:' + formId);
} }
} };
``` ```
## onConfigurationUpdate ## onConfigurationUpdate
...@@ -212,11 +234,13 @@ onConfigurationUpdate(newConfig: Configuration): void; ...@@ -212,11 +234,13 @@ onConfigurationUpdate(newConfig: Configuration): void;
**示例:** **示例:**
```ts ```ts
class MyFormExtensionAbility extends FormExtensionAbility { import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(config) { onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
} }
} };
``` ```
## onAcquireFormState ## onAcquireFormState
...@@ -236,13 +260,15 @@ onAcquireFormState?(want: Want): formInfo.FormState; ...@@ -236,13 +260,15 @@ onAcquireFormState?(want: Want): formInfo.FormState;
**示例:** **示例:**
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formInfo from '@ohos.app.form.formInfo'; import formInfo from '@ohos.app.form.formInfo';
class MyFormExtensionAbility extends FormExtensionAbility {
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState(want) { onAcquireFormState(want) {
console.log('FormExtensionAbility onAcquireFormState, want:' + want); console.log('FormExtensionAbility onAcquireFormState, want:' + want);
return formInfo.FormState.UNKNOWN; return formInfo.FormState.UNKNOWN;
} }
} };
``` ```
## onShareForm ## onShareForm
...@@ -270,14 +296,16 @@ onShareForm?(formId: string): { [key: string]: any } ...@@ -270,14 +296,16 @@ onShareForm?(formId: string): { [key: string]: any }
**示例:** **示例:**
```ts ```ts
class MyFormExtensionAbility extends FormExtensionAbility { import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm(formId) { onShareForm(formId) {
console.log('FormExtensionAbility onShareForm, formId:' + formId); console.log('FormExtensionAbility onShareForm, formId:' + formId);
let wantParams = { let wantParams = {
"temperature":"20", "temperature": "20",
"time":"2022-8-8 09:59", "time": "2022-8-8 09:59",
}; };
return wantParams; return wantParams;
} }
} };
``` ```
\ No newline at end of file
# @ohos.app.form.formHost (FormHost) # @ohos.app.form.formHost (formHost)
FormHost模块提供了卡片使用方相关接口的能力,包括对使用方同一用户下安装的卡片进行删除、释放、请求更新、获取卡片信息、状态等操作。 formHost模块提供了卡片使用方相关接口的能力,包括对使用方同一用户下安装的卡片进行删除、释放、请求更新、获取卡片信息、状态等操作。
> **说明:** > **说明:**
> >
...@@ -34,25 +34,24 @@ deleteForm(formId: string, callback: AsyncCallback&lt;void&gt;): void ...@@ -34,25 +34,24 @@ deleteForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.deleteForm(formId, (error, data) => { formHost.deleteForm(formId, (error) => {
if (error) { if (error) {
console.log('formHost deleteForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
## deleteForm ## deleteForm
...@@ -82,21 +81,21 @@ deleteForm(formId: string): Promise&lt;void&gt; ...@@ -82,21 +81,21 @@ deleteForm(formId: string): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**参数:** **参数:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.deleteForm(formId).then(() => { formHost.deleteForm(formId).then(() => {
console.log('formHost deleteForm success'); console.log('formHost deleteForm success');
}).catch((error) => { }).catch((error) => {
console.log('formHost deleteForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;void&gt;): void ...@@ -121,21 +120,21 @@ releaseForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.releaseForm(formId, (error, data) => { formHost.releaseForm(formId, (error) => {
if (error) { if (error) {
console.log('formHost releaseForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt; ...@@ -161,21 +160,21 @@ releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback&lt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.releaseForm(formId, true, (error, data) => { formHost.releaseForm(formId, true, (error) => {
if (error) { if (error) {
console.log('formHost releaseForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;void&gt; ...@@ -206,21 +205,21 @@ releaseForm(formId: string, isReleaseCache?: boolean): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.releaseForm(formId, true).then(() => { formHost.releaseForm(formId, true).then(() => {
console.log('formHost releaseForm success'); console.log('formHost releaseForm success');
}).catch((error) => { }).catch((error) => {
console.log('formHost releaseForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;void&gt;): void ...@@ -245,21 +244,21 @@ requestForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.requestForm(formId, (error, data) => { formHost.requestForm(formId, (error) => {
if (error) { if (error) {
console.log('formHost requestForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;void&gt; ...@@ -289,21 +288,21 @@ requestForm(formId: string): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.requestForm(formId).then(() => { formHost.requestForm(formId).then(() => {
console.log('formHost requestForm success'); console.log('formHost requestForm success');
}).catch((error) => { }).catch((error) => {
console.log('formHost requestForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;void&gt;): void ...@@ -323,27 +322,27 @@ castToNormalForm(formId: string, callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formId | string | 是 | 卡片标识。 | | formId | string | 是 | 卡片标识。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当将指定的临时卡片转换为普通卡片成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当将指定的临时卡片转换为普通卡片成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.castToNormalForm(formId, (error, data) => { formHost.castToNormalForm(formId, (error) => {
if (error) { if (error) {
console.log('formHost castTempForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;void&gt; ...@@ -373,21 +372,21 @@ castToNormalForm(formId: string): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288"; let formId = "12400633174999288";
formHost.castToNormalForm(formId).then(() => { formHost.castToNormalForm(formId).then(() => {
console.log('formHost castTempForm success'); console.log('formHost castTempForm success');
}).catch((error) => { }).catch((error) => {
console.log('formHost castTempForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, callback: AsyncCallback&lt;void ...@@ -406,27 +405,27 @@ notifyVisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可见成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可见成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId, (error, data) => { formHost.notifyVisibleForms(formId, (error) => {
if (error) { if (error) {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;): Promise&lt;void&gt; ...@@ -456,21 +455,21 @@ notifyVisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.notifyVisibleForms(formId).then(() => { formHost.notifyVisibleForms(formId).then(() => {
console.log('formHost notifyVisibleForms success'); console.log('formHost notifyVisibleForms success');
}).catch((error) => { }).catch((error) => {
console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, callback: AsyncCallback&lt;vo ...@@ -489,27 +488,27 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;vo
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。| | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。|
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可见成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可见成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId, (error, data) => { formHost.notifyInvisibleForms(formId, (error) => {
if (error) { if (error) {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;): Promise&lt;void&gt; ...@@ -539,21 +538,21 @@ notifyInvisibleForms(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.notifyInvisibleForms(formId).then(() => { formHost.notifyInvisibleForms(formId).then(() => {
console.log('formHost notifyInvisibleForms success'); console.log('formHost notifyInvisibleForms success');
}).catch((error) => { }).catch((error) => {
console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, callback: AsyncCallback&lt;void& ...@@ -572,27 +571,27 @@ enableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void&
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可以更新成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片可以更新成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId, (error, data) => { formHost.enableFormsUpdate(formId, (error) => {
if (error) { if (error) {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;): Promise&lt;void&gt; ...@@ -622,21 +621,21 @@ enableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.enableFormsUpdate(formId).then(() => { formHost.enableFormsUpdate(formId).then(() => {
console.log('formHost enableFormsUpdate success'); console.log('formHost enableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, callback: AsyncCallback&lt;void ...@@ -655,27 +654,27 @@ disableFormsUpdate(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可以更新成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当向卡片框架发送通知以使指定的卡片不可以更新成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId, (error, data) => { formHost.disableFormsUpdate(formId, (error) => {
if (error) { if (error) {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;): Promise&lt;void&gt; ...@@ -705,21 +704,21 @@ disableFormsUpdate(formIds: Array&lt;string&gt;): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
try { try {
var formId = ["12400633174999288"]; let formId = ["12400633174999288"];
formHost.disableFormsUpdate(formId).then(() => { formHost.disableFormsUpdate(formId).then(() => {
console.log('formHost disableFormsUpdate success'); console.log('formHost disableFormsUpdate success');
}).catch((error) => { }).catch((error) => {
console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;void&gt;): void ...@@ -735,20 +734,19 @@ isSystemReady(callback: AsyncCallback&lt;void&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当检查系统是否准备好成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当检查系统是否准备好成功,error为undefined,否则为错误对象。 |
**示例:** **示例:**
```ts ```ts
try { try {
var formId = "12400633174999288";
formHost.isSystemReady((error, data) => { formHost.isSystemReady((error, data) => {
if (error) { if (error) {
console.log('formHost isSystemReady, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;void&gt; ...@@ -770,14 +768,13 @@ isSystemReady(): Promise&lt;void&gt;
```ts ```ts
try { try {
var formId = "12400633174999288";
formHost.isSystemReady().then(() => { formHost.isSystemReady().then(() => {
console.log('formHost isSystemReady success'); console.log('formHost isSystemReady success');
}).catch((error) => { }).catch((error) => {
console.log('formHost isSystemReady, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;Array&lt;formInfo.FormInfo&gt;&gt;): ...@@ -795,7 +792,7 @@ getAllFormsInfo(callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;):
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上所有应用提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | | callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上所有应用提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 |
**示例:** **示例:**
...@@ -803,13 +800,13 @@ getAllFormsInfo(callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): ...@@ -803,13 +800,13 @@ getAllFormsInfo(callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;):
try { try {
formHost.getAllFormsInfo((error, data) => { formHost.getAllFormsInfo((error, data) => {
if (error) { if (error) {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } 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&lt;Array&lt;formInfo.FormInfo&gt;&gt; ...@@ -825,9 +822,9 @@ getAllFormsInfo(): Promise&lt;Array&lt;formInfo.FormInfo&gt;&gt;
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| :------------ | :---------------------------------- | | :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象,返回查询到的卡片信息。 | | Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象,返回查询到的卡片信息。 |
**示例:** **示例:**
...@@ -836,10 +833,10 @@ try { ...@@ -836,10 +833,10 @@ try {
formHost.getAllFormsInfo().then((data) => { formHost.getAllFormsInfo().then((data) => {
console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); console.log('formHost getAllFormsInfo data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;Array&lt;formInfo.Fo ...@@ -858,14 +855,14 @@ getFormsInfo(bundleName: string, callback: AsyncCallback&lt;Array&lt;formInfo.Fo
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| bundleName | string | 是 | 要查询的应用Bundle名称。 | | bundleName | string | 是 | 要查询的应用Bundle名称。 |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | | callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
...@@ -873,13 +870,13 @@ getFormsInfo(bundleName: string, callback: AsyncCallback&lt;Array&lt;formInfo.Fo ...@@ -873,13 +870,13 @@ getFormsInfo(bundleName: string, callback: AsyncCallback&lt;Array&lt;formInfo.Fo
try { try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => {
if (error) { if (error) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } 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&lt; ...@@ -899,14 +896,14 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback&lt;
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| bundleName | string | 是 | 要查询的应用Bundle名称。 | | bundleName | string | 是 | 要查询的应用Bundle名称。 |
| moduleName | string | 是 | 要查询的模块名称。 | | moduleName | string | 是 | 要查询的模块名称。 |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,err为undefined,data为查询到的卡片信息;否则为错误对象。 | | callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。当获取设备上指定应用程序提供的卡片信息成功,error为undefined,data为查询到的卡片信息;否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
...@@ -914,13 +911,13 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback&lt; ...@@ -914,13 +911,13 @@ getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback&lt;
try { try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => {
if (error) { if (error) {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } 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&lt;Array&lt;formI ...@@ -943,16 +940,16 @@ getFormsInfo(bundleName: string, moduleName?: string): Promise&lt;Array&lt;formI
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| :------------ | :---------------------------------- | | :----------------------------------------------------------- | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象,返回查询到的卡片信息。 | | Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象,返回查询到的卡片信息。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
...@@ -961,10 +958,10 @@ try { ...@@ -961,10 +958,10 @@ try {
formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => {
console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); console.log('formHost getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, callback: AsyncCallback&lt;numb ...@@ -983,22 +980,22 @@ deleteInvalidForms(formIds: Array&lt;string&gt;, callback: AsyncCallback&lt;numb
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 有效卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 有效卡片标识列表。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 回调函数。当根据列表删除应用程序的无效卡片成功,err为undefined,data为删除的卡片个数;否则为错误对象。 | | callback | AsyncCallback&lt;number&gt; | 是 | 回调函数。当根据列表删除应用程序的无效卡片成功,error为undefined,data为删除的卡片个数;否则为错误对象。 |
**示例:** **示例:**
```ts ```ts
try { try {
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds, (error, data) => { formHost.deleteInvalidForms(formIds, (error, data) => {
if (error) { if (error) {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } 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&lt;string&gt;): Promise&lt;number&gt; ...@@ -1028,14 +1025,14 @@ deleteInvalidForms(formIds: Array&lt;string&gt;): Promise&lt;number&gt;
```ts ```ts
try { try {
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
formHost.deleteInvalidForms(formIds).then((data) => { formHost.deleteInvalidForms(formIds).then((data) => {
console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;formInfo.FormStateInfo&g ...@@ -1053,15 +1050,15 @@ acquireFormState(want: Want, callback: AsyncCallback&lt;formInfo.FormStateInfo&g
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。 | | want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。需要包含bundle名、ability名、module名、卡片名、卡片规格等。 |
| callback | AsyncCallback&lt;[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | 是 | 回调函数。当获取卡片状态成功,err为undefined,data为获取到的卡片状态;否则为错误对象。 | | callback | AsyncCallback&lt;[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | 是 | 回调函数。当获取卡片状态成功,error为undefined,data为获取到的卡片状态;否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
...@@ -1079,13 +1076,13 @@ var want = { ...@@ -1079,13 +1076,13 @@ var want = {
try { try {
formHost.acquireFormState(want, (error, data) => { formHost.acquireFormState(want, (error, data) => {
if (error) { if (error) {
console.log('formHost acquireFormState, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
} }
}); });
} catch(error) { } 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&lt;formInfo.FormStateInfo&gt; ...@@ -1103,20 +1100,20 @@ acquireFormState(want: Want): Promise&lt;formInfo.FormStateInfo&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。 | | want | [Want](js-apis-application-want.md) | 是 | 查询卡片状态时携带的want信息。需要包含bundle名、ability名、module名、卡片名、卡片规格等。 |
**返回值:** **返回值:**
| 类型 | 说明 | | 类型 | 说明 |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;[FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise对象,返回卡片状态。 | | Promise&lt;[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)&gt; | Promise对象,返回卡片状态。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
...@@ -1135,10 +1132,10 @@ try { ...@@ -1135,10 +1132,10 @@ try {
formHost.acquireFormState(want).then((data) => { formHost.acquireFormState(want).then((data) => {
console.log('formHost acquireFormState, data:' + JSON.stringify(data)); console.log('formHost acquireFormState, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formHost acquireFormState, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, isVisible: boolean, callback: A ...@@ -1206,27 +1203,27 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean, callback: A
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 |
| isVisible | boolean | 是 | 是否可见。 | | isVisible | boolean | 是 | 是否可见。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当通知卡片是否可见成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当通知卡片是否可见成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsVisible(formIds, true, (error, data) => { formHost.notifyFormsVisible(formIds, true, (error) => {
if (error) { if (error) {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;, isVisible: boolean): Promise&lt ...@@ -1257,21 +1254,21 @@ notifyFormsVisible(formIds: Array&lt;string&gt;, isVisible: boolean): Promise&lt
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsVisible(formIds, true).then(() => { formHost.notifyFormsVisible(formIds, true).then(() => {
console.log('formHost notifyFormsVisible success'); console.log('formHost notifyFormsVisible success');
}).catch((error) => { }).catch((error) => {
console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } 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&lt;string&gt;, isEnableUpdate: boolean, c ...@@ -1291,27 +1288,27 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean, c
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 | | formIds | Array&lt;string&gt; | 是 | 卡片标识列表。 |
| isEnableUpdate | boolean | 是 | 是否使能更新。 | | isEnableUpdate | boolean | 是 | 是否使能更新。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当通知卡片是否启用更新状态成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当通知卡片是否启用更新状态成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { formHost.notifyFormsEnableUpdate(formIds, true, (error) => {
if (error) { if (error) {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;string&gt;, isEnableUpdate: boolean): ...@@ -1342,21 +1339,21 @@ notifyFormsEnableUpdate(formIds: Array&lt;string&gt;, isEnableUpdate: boolean):
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formIds = new Array("12400633174999288", "12400633174999289"); let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsEnableUpdate(formIds, true).then(() => { formHost.notifyFormsEnableUpdate(formIds, true).then(() => {
console.log('formHost notifyFormsEnableUpdate success'); console.log('formHost notifyFormsEnableUpdate success');
}).catch((error) => { }).catch((error) => {
console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } catch(error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
## shareForm ## shareForm
...@@ -1375,29 +1372,28 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;) ...@@ -1375,29 +1372,28 @@ shareForm(formId: string, deviceId: string, callback: AsyncCallback&lt;void&gt;)
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formId | string | 是 | 卡片标识。 | | formId | string | 是 | 卡片标识。 |
| deviceId | string | 是 | 远程设备标识。 | | deviceId | string | 是 | 远程设备标识。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当指定formId和远程设备Id进行卡片分享成功,err为undefined,否则为错误对象。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。当指定formId和远程设备Id进行卡片分享成功,error为undefined,否则为错误对象。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formId = "12400633174999288"; let formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try { try {
formHost.shareForm(formId, deviceId, (error, data) => { formHost.shareForm(formId, deviceId, (error) => {
if (error) { if (error) {
console.log('formHost shareForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
} }
}); });
} catch(error) { } 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&lt;void&gt; ...@@ -1428,22 +1424,22 @@ shareForm(formId: string, deviceId: string): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**参数:** **示例:**
```ts ```ts
var formId = "12400633174999288"; let formId = "12400633174999288";
var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2";
try { try {
formHost.shareForm(formId, deviceId).then(() => { formHost.shareForm(formId, deviceId).then(() => {
console.log('formHost shareForm success'); console.log('formHost shareForm success');
}).catch((error) => { }).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } catch(error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
...@@ -1451,6 +1447,8 @@ try { ...@@ -1451,6 +1447,8 @@ try {
notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callback: AsyncCallback\<void>): void notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callback: AsyncCallback\<void>): void
通知指定卡片隐私保护状态改变。使用callback异步回调。
**需要权限**:ohos.permission.REQUIRE_FORM **需要权限**:ohos.permission.REQUIRE_FORM
**系统能力**:SystemCapability.Ability.Form **系统能力**:SystemCapability.Ability.Form
...@@ -1459,18 +1457,72 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb ...@@ -1459,18 +1457,72 @@ notifyFormsPrivacyProtected(formIds: Array\<string>, isProtected: boolean, callb
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| formId | string | 是 | 卡片标识。 | | formIds | Array\<string\> | 是 | 需要修改隐私保护的卡片标识列表。 |
| deviceId | string | 是 | 远程设备标识。 | | isProtected | boolean | 是 | 是否进行隐私保护。 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当指定卡片设置隐私保护属性成功,error为undefined,否则为错误对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------------------------------------------------------------ | ------------------ |
| 401 | 调用接口入参错误。 |
| 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | |
**示例:**
```ts ```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\<string\>, isProtected: boolean): Promise\<void\>;
通知指定卡片隐私保护状态改变。使用Promise异步回调。
**需要权限**:ohos.permission.REQUIRE_FORM
**系统能力**:SystemCapability.Ability.Form
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------- | ---- | -------------------------------- |
| formIds | Array\<string\> | 是 | 需要修改隐私保护的卡片标识列表。 |
| isProtected | boolean | 是 | 是否进行隐私保护。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**错误码:**
| 错误码ID | 错误信息 |
| ------------------------------------------------------------ | ------------------ |
| 401 | 调用接口入参错误。 |
| 以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。 | |
```ts
let formIds = new Array("12400633174999288", "12400633174999289");
try { try {
formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { formHost.notifyFormsPrivacyProtected(formIds, true).then(() => {
console.log('formHost shareForm success'); console.log('formHost notifyFormsPrivacyProtected success');
}).catch((error) => { }).catch((error) => {
console.log('formHost shareForm, error:' + JSON.stringify(error)); console.log(`error, code: ${error.code}, message: ${error.message})`);
}); });
} catch(error) { } catch(error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
# @ohos.app.form.formInfo (FormInfo) # @ohos.app.form.formInfo (formInfo)
FormInfo模块提供对卡片的相关卡片信息和状态进行设置和查询的能力 formInfo模块提供了卡片信息和状态等相关类型和枚举
> **说明:** > **说明:**
> >
...@@ -30,11 +30,11 @@ import formInfo from '@ohos.app.form.formInfo'; ...@@ -30,11 +30,11 @@ import formInfo from '@ohos.app.form.formInfo';
| colorMode | [ColorMode](#colormode) | 是 | 否 | 卡片颜色模式。 | | colorMode | [ColorMode](#colormode) | 是 | 否 | 卡片颜色模式。 |
| isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 | | isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 |
| updateEnabled | boolean | 是 | 否 | 卡片是否使能更新。 | | updateEnabled | boolean | 是 | 否 | 卡片是否使能更新。 |
| formVisibleNotify | string | 是 | 否 | 卡片是否使能可见通知。 | | formVisibleNotify | boolean | 是 | 否 | 卡片是否使能可见通知。 |
| relatedBundleName | string | 是 | 否 | 卡片所属的相关联Bundle名称。 | | relatedBundleName | string | 是 | 否 | 卡片所属的相关联Bundle名称。 |
| scheduledUpdateTime | string | 是 | 否 | 卡片更新时间。 | | scheduledUpdateTime | string | 是 | 否 | 卡片更新时间。 |
| formConfigAbility | string | 是 | 否 | 卡片配置ability。指定长按卡片弹出的选择框内,编辑选项所对应的ability。 | | formConfigAbility | string | 是 | 否 | 卡片配置ability。指定长按卡片弹出的选择框内,编辑选项所对应的ability。 |
| updateDuration | string | 是 | 否 | 卡片更新周期。 | | updateDuration | number | 是 | 否 | 卡片更新周期。 |
| defaultDimension | number | 是 | 否 | 表示卡片规格 | | defaultDimension | number | 是 | 否 | 表示卡片规格 |
| supportDimensions | Array&lt;number&gt; | 是 | 否 | 卡片支持的规格。具体可选规格参考[FormDimension](#formdimension) | | supportDimensions | Array&lt;number&gt; | 是 | 否 | 卡片支持的规格。具体可选规格参考[FormDimension](#formdimension) |
| customizeData | {[key: string]: [value: string]} | 是 | 否 | 卡片用户数据。 | | customizeData | {[key: string]: [value: string]} | 是 | 否 | 卡片用户数据。 |
...@@ -100,8 +100,8 @@ import formInfo from '@ohos.app.form.formInfo'; ...@@ -100,8 +100,8 @@ import formInfo from '@ohos.app.form.formInfo';
| WIDTH_KEY | "ohos.extra.param.key.form_width" | 卡片宽度。 | | WIDTH_KEY | "ohos.extra.param.key.form_width" | 卡片宽度。 |
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | 卡片高度。 | | HEIGHT_KEY | "ohos.extra.param.key.form_height" | 卡片高度。 |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | 临时卡片。 | | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | 临时卡片。 |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称 | | ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称 |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。<br/>**系统接口**: 此接口为系统接口。 | | DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。 |
| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | 指示指定要获取的捆绑Bundle名称的键。 | | BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | 指示指定要获取的捆绑Bundle名称的键。 |
## FormDimension ## FormDimension
...@@ -127,7 +127,7 @@ import formInfo from '@ohos.app.form.formInfo'; ...@@ -127,7 +127,7 @@ import formInfo from '@ohos.app.form.formInfo';
| 名称 | 说明 | | 名称 | 说明 |
| ----------- | ------------ | | ----------- | ------------ |
| moduleName | 仅保留moduleName与提供值相符的卡片信息。 | | moduleName | 选填。仅保留moduleName与提供值相符的卡片信息。未填写时则不通过moduleName进行过滤。 |
## VisibilityType ## VisibilityType
......
# @ohos.app.form.formProvider (FormProvider) # @ohos.app.form.formProvider (formProvider)
FormProvider模块提供了卡片提供方相关接口的能力,开发者在开发卡片时,可通过该模块提供接口实现更新卡片,设置卡片更新时间,获取卡片信息,请求发布卡片等。 FormProvider模块提供了卡片提供方相关接口的能力,开发者在开发卡片时,可通过该模块提供接口实现更新卡片、设置卡片更新时间、获取卡片信息、请求发布卡片等。
> **说明:** > **说明:**
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
...@@ -31,23 +31,25 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l ...@@ -31,23 +31,25 @@ setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback&l
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formId = "12400633174999288"; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try { try {
formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { formProvider.setFormNextRefreshTime(formId, 5, (error, data) => {
if (error) { if (error) {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log(`formProvider setFormNextRefreshTime success`); console.log(`formProvider setFormNextRefreshTime success`);
} }
}); });
} catch (error) { } 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&lt;void&gt; ...@@ -76,21 +78,23 @@ setFormNextRefreshTime(formId: string, minute: number): Promise&lt;void&gt;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var formId = "12400633174999288"; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try { try {
formProvider.setFormNextRefreshTime(formId, 5).then(() => { formProvider.setFormNextRefreshTime(formId, 5).then(() => {
console.log('formProvider setFormNextRefreshTime success'); console.log(`formProvider setFormNextRefreshTime success`);
}).catch((error) => { }).catch((error) => {
console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } 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 ...@@ -114,25 +118,27 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData,call
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288"; import formProvider from '@ohos.app.form.formProvider';
let formId = "12400633174999288";
try { try {
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
formProvider.updateForm(formId, obj, (error, data) => { formProvider.updateForm(formId, obj, (error, data) => {
if (error) { if (error) {
console.log('formProvider updateForm, error:' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log(`formProvider updateForm success`); console.log(`formProvider updateForm success`);
} }
}); });
} catch (error) { } 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 ...@@ -161,23 +167,25 @@ updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Pr
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var formId = "12400633174999288"; import formProvider from '@ohos.app.form.formProvider';
let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
let formId = "12400633174999288";
let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" });
try { try {
formProvider.updateForm(formId, obj).then(() => { formProvider.updateForm(formId, obj).then(() => {
console.log('formProvider updateForm success'); console.log(`formProvider updateForm success`);
}).catch((error) => { }).catch((error) => {
console.log('formProvider updateForm, error:' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } 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&lt;Array&lt;formInfo.FormInfo&gt;&gt;): voi ...@@ -193,29 +201,31 @@ getFormsInfo(callback: AsyncCallback&lt;Array&lt;formInfo.FormInfo&gt;&gt;): voi
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。返回查询到的卡片信息。 | | callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。返回查询到的卡片信息。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.getFormsInfo((error, data) => { formProvider.getFormsInfo((error, data) => {
if (error) { if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
## getFormsInfo ## getFormsInfo
...@@ -231,33 +241,35 @@ getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback&lt;Array&l ...@@ -231,33 +241,35 @@ getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback&lt;Array&l
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | 是 | 卡片信息过滤器。 | | filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | 是 | 卡片信息过滤器。 |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。返回查询到符合条件的卡片信息。 | | callback | AsyncCallback&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | 是 | 回调函数。返回查询到符合条件的卡片信息。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formInfo from '@ohos.application.formInfo'; import formInfo from '@ohos.app.form.formInfo';
const filter : formInfo.FormInfoFilter = { import formProvider from '@ohos.app.form.formProvider';
// get info of forms belong to module entry.
moduleName : "entry" const filter: formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName: "entry"
}; };
try { try {
formProvider.getFormsInfo(filter, (error, data) => { formProvider.getFormsInfo(filter, (error, data) => {
if (error) { if (error) {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data));
} }
}); });
} catch(error) { } catch (error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
...@@ -279,31 +291,33 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise&lt;Array&lt;formInfo.For ...@@ -279,31 +291,33 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise&lt;Array&lt;formInfo.For
| 类型 | 说明 | | 类型 | 说明 |
| :------------ | :---------------------------------- | | :------------ | :---------------------------------- |
| Promise&lt;Array&lt;[FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象。返回查询到符合条件的卡片信息。 | | Promise&lt;Array&lt;[formInfo.FormInfo](js-apis-app-form-formInfo.md)&gt;&gt; | Promise对象。返回查询到符合条件的卡片信息。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formInfo from '@ohos.application.formInfo'; import formInfo from '@ohos.app.form.formInfo';
const filter : formInfo.FormInfoFilter = { import formProvider from '@ohos.app.form.formProvider';
// get info of forms belong to module entry.
moduleName : "entry" const filter: formInfo.FormInfoFilter = {
// get info of forms belong to module entry.
moduleName: "entry"
}; };
try { try {
formProvider.getFormsInfo(filter).then((data) => { formProvider.getFormsInfo(filter).then((data) => {
console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); console.log('formProvider getFormsInfo, data:' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } 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, ...@@ -322,21 +336,23 @@ requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData,
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- |
| want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。<br>abilityName: 目标卡片ability<br>parameters:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" | | want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。<br>abilityName: 目标卡片ability<br>parameters:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"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&lt;string&gt; | 是 | 回调函数。返回卡片标识。 | | callback | AsyncCallback&lt;string&gt; | 是 | 回调函数。返回卡片标识。 |
**错误码:** **错误码:**
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
import formBindingData from '@ohos.application.formBindingData'; import formBindingData from '@ohos.application.formBindingData';
var want = { import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility", abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_dimension": 2,
...@@ -345,16 +361,16 @@ var want = { ...@@ -345,16 +361,16 @@ var want = {
} }
}; };
try { 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) => { formProvider.requestPublishForm(want, obj, (error, data) => {
if (error) { if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
} catch (error) { } 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&lt;string&gt;): void ...@@ -379,13 +395,15 @@ requestPublishForm(want: Want, callback: AsyncCallback&lt;string&gt;): void
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var want = { import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility", abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_dimension": 2,
...@@ -396,15 +414,14 @@ var want = { ...@@ -396,15 +414,14 @@ var want = {
try { try {
formProvider.requestPublishForm(want, (error, data) => { formProvider.requestPublishForm(want, (error, data) => {
if (error) { if (error) {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data));
} }
}); });
} catch (error) { } catch (error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
``` ```
## requestPublishForm ## requestPublishForm
...@@ -422,7 +439,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData ...@@ -422,7 +439,7 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。<br>abilityName: 目标卡片ability<br>parameters:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"ohos.extra.param.key.module_name" | | want | [Want](js-apis-application-want.md) | 是 | 发布请求。需包含以下字段。<br>abilityName: 目标卡片ability<br>parameters:<br>"ohos.extra.param.key.form_dimension"<br>"ohos.extra.param.key.form_name"<br>"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 ...@@ -434,13 +451,15 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | -------- | | -------- | -------- |
| 401 | If the input parameter is not valid parameter. | | 401 | 调用接口入参错误。 |
以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md) |以上错误码的详细介绍请参见[卡片错误码](../errorcodes/errorcode-form.md)。||
**示例:** **示例:**
```ts ```ts
var want = { import formProvider from '@ohos.app.form.formProvider';
let want = {
abilityName: "FormAbility", abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_dimension": 2,
...@@ -452,10 +471,10 @@ try { ...@@ -452,10 +471,10 @@ try {
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } 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&lt;boolean&gt;): void ...@@ -478,37 +497,38 @@ isRequestPublishFormSupported(callback: AsyncCallback&lt;boolean&gt;): void
**示例:** **示例:**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.isRequestPublishFormSupported((error, isSupported) => { formProvider.isRequestPublishFormSupported((error, isSupported) => {
if (error) { if (error) {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); console.log(`callback error, code: ${error.code}, message: ${error.message})`);
} else { } else {
if (isSupported) { if (isSupported) {
var want = { var want = {
abilityName: "FormAbility", abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget", "ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry" "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));
} }
}); };
} catch (error) { try {
console.log(`catch err->${JSON.stringify(error)}`); 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) { } 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&lt;boolean&gt; ...@@ -531,32 +551,33 @@ isRequestPublishFormSupported(): Promise&lt;boolean&gt;
**示例:** **示例:**
```ts ```ts
import formProvider from '@ohos.app.form.formProvider';
try { try {
formProvider.isRequestPublishFormSupported().then((isSupported) => { formProvider.isRequestPublishFormSupported().then((isSupported) => {
if (isSupported) { if (isSupported) {
var want = { var want = {
abilityName: "FormAbility", abilityName: "FormAbility",
parameters: { parameters: {
"ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_dimension": 2,
"ohos.extra.param.key.form_name": "widget", "ohos.extra.param.key.form_name": "widget",
"ohos.extra.param.key.module_name": "entry" "ohos.extra.param.key.module_name": "entry"
} }
}; };
try { try {
formProvider.requestPublishForm(want).then((data) => { formProvider.requestPublishForm(want).then((data) => {
console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } catch (error) {
console.log(`catch err->${JSON.stringify(error)}`); console.log(`catch error, code: ${error.code}, message: ${error.message})`);
} }
} }
}).catch((error) => { }).catch((error) => {
console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); console.log(`promise error, code: ${error.code}, message: ${error.message})`);
}); });
} catch (error) { } 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
...@@ -4,307 +4,27 @@ ...@@ -4,307 +4,27 @@
该模块提供以下关系型数据库相关的常用功能: 该模块提供以下关系型数据库相关的常用功能:
- [RdbPredicatesV9](#rdbpredicatesv99): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 - [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。
- [RdbStoreV9](#rdbstorev99):提供管理关系数据库(RDB)方法的接口。 - [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。
> **说明:** > **说明:**
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> 从API Version 9开始,该接口不再维护,推荐使用新接口[@ohos.data.relationalStore](js-apis-data-relationalStore.md)。
## 导入模块 ## 导入模块
```js ```js
import data_rdb from '@ohos.data.rdb'; import data_rdb from '@ohos.data.rdb';
``` ```
## data_rdb.getRdbStore
## data_rdb.getRdbStoreV9<sup>9+</sup>
getRdbStoreV9(context: Context, config: StoreConfigV9, version: number, callback: AsyncCallback&lt;RdbStoreV9&gt;): void
获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 |
| version | number | 是 | 数据库版本。<br>目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 |
| callback | AsyncCallback&lt;[RdbStoreV9](#rdbstorev9)&gt; | 是 | 指定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.getRdbStoreV9<sup>9+</sup>
getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise&lt;RdbStoreV9&gt;
获得一个相关的RdbStoreV9,操作关系型数据库,用户可以根据自己的需求配置RdbStoreV9的参数,然后通过RdbStoreV9调用相关接口可以执行相关的数据操作,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| config | [StoreConfigV9](#storeconfigv99) | 是 | 与此RDB存储相关的数据库配置。 |
| version | number | 是 | 数据库版本。<br>目前暂不支持通过version自动识别数据库升级降级操作,只能由开发者自行维护。 |
**返回值**
| 类型 | 说明 |
| ----------------------------------------- | --------------------------------- |
| Promise&lt;[RdbStoreV9](#rdbstorev99)&gt; | 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.deleteRdbStoreV9<sup>9+</sup>
deleteRdbStoreV9(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
删除数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| name | string | 是 | 数据库名称。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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.deleteRdbStoreV9<sup>9+</sup>
deleteRdbStoreV9(context: Context, name: string): Promise&lt;void&gt;
使用指定的数据库文件配置删除数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| name | string | 是 | 数据库名称。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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<sup>(deprecated)</sup>
getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback&lt;RdbStore&gt;): void getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback&lt;RdbStore&gt;): void
获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -359,16 +79,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { ...@@ -359,16 +79,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) {
}) })
``` ```
## data_rdb.getRdbStore<sup>(deprecated)</sup> ## data_rdb.getRdbStore
getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt; getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt;
获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.getRdbStoreV9](#data_rdbgetrdbstorev99-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -426,16 +142,12 @@ promise.then(async (rdbStore) => { ...@@ -426,16 +142,12 @@ promise.then(async (rdbStore) => {
}) })
``` ```
## data_rdb.deleteRdbStore<sup>(deprecated)</sup> ## data_rdb.deleteRdbStore
deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
删除数据库,使用callback异步回调。 删除数据库,使用callback异步回调。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -487,2205 +199,65 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { ...@@ -487,2205 +199,65 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
}) })
``` ```
## data_rdb.deleteRdbStore<sup>(deprecated)</sup> ## data_rdb.deleteRdbStore
deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
使用指定的数据库文件配置删除数据库,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[data_rdb.deleteRdbStoreV9](#data_rdbdeleterdbstorev99-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| name | string | 是 | 数据库名称。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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)
})
```
## RdbPredicatesV9<sup>9+</sup>
表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。
### constructor<sup>9+</sup>
constructor(name: string)
构造函数。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------ |
| name | string | 是 | 数据库表名。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
```
### inDevices<sup>9+</sup>
inDevices(devices: Array&lt;string&gt;): RdbPredicatesV9
同步分布式数据库时连接到组网内指定的远程设备。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------- | ---- | -------------------------- |
| devices | Array&lt;string&gt; | 是 | 指定的组网内的远程设备ID。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.inDevices(['12345678abcde'])
```
### inAllDevices<sup>9+</sup>
inAllDevices(): RdbPredicatesV9
同步分布式数据库时连接到组网内所有的远程设备。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesv9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.inAllDevices()
```
### equalTo<sup>9+</sup>
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")
```
### notEqualTo<sup>9+</sup>
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")
```
### beginWrap<sup>9+</sup>
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()
```
### endWrap<sup>9+</sup>
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()
```
### or<sup>9+</sup>
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")
```
### and<sup>9+</sup>
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)
```
### contains<sup>9+</sup>
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")
```
### beginsWith<sup>9+</sup>
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")
```
### endsWith<sup>9+</sup>
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")
```
### isNull<sup>9+</sup>
isNull(field: string): RdbPredicatesV9
配置谓词以匹配值为null的字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| field | string | 是 | 数据库表中的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.isNull("NAME")
```
### isNotNull<sup>9+</sup>
isNotNull(field: string): RdbPredicatesV9
配置谓词以匹配值不为null的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| field | string | 是 | 数据库表中的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.isNotNull("NAME")
```
### like<sup>9+</sup>
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%")
```
### glob<sup>9+</sup>
glob(field: string, value: string): RdbPredicatesV9
配置RdbPredicatesV9匹配数据字段为string的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| field | string | 是 | 数据库表中的列名。 |
| value | string | 是 | 指示要与谓词匹配的值。<br>支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.glob("NAME", "?h*g")
```
### between<sup>9+</sup>
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)
```
### notBetween<sup>9+</sup>
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)
```
### greaterThan<sup>9+</sup>
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)
```
### lessThan<sup>9+</sup>
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)
```
### greaterThanOrEqualTo<sup>9+</sup>
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)
```
### lessThanOrEqualTo<sup>9+</sup>
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)
```
### orderByAsc<sup>9+</sup>
orderByAsc(field: string): RdbPredicatesV9
配置谓词以匹配其值按升序排序的列。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| field | string | 是 | 数据库表中的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.orderByAsc("NAME")
```
### orderByDesc<sup>9+</sup>
orderByDesc(field: string): RdbPredicatesV9
配置谓词以匹配其值按降序排序的列。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------ |
| field | string | 是 | 数据库表中的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.orderByDesc("AGE")
```
### distinct<sup>9+</sup>
distinct(): RdbPredicatesV9
配置谓词以过滤重复记录并仅保留其中一个。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值**
| 类型 | 说明 |
| ------------------------------------ | ------------------------------ |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回可用于过滤重复记录的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.equalTo("NAME", "Rose").distinct()
```
### limitAs<sup>9+</sup>
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)
```
### offsetAs<sup>9+</sup>
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)
```
### groupBy<sup>9+</sup>
groupBy(fields: Array&lt;string&gt;): RdbPredicatesV9
配置RdbPredicatesV9按指定列分组查询结果。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | -------------------- |
| fields | Array&lt;string&gt; | 是 | 指定分组依赖的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | ---------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回分组查询列的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.groupBy(["AGE", "NAME"])
```
### indexedBy<sup>9+</sup>
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")
```
### in<sup>9+</sup>
in(field: string, value: Array&lt;ValueType&gt;): RdbPredicatesV9
配置RdbPredicatesV9以匹配数据字段为ValueType数组且值在给定范围内的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------ | ---- | --------------------------------------- |
| field | string | 是 | 数据库表中的列名。 |
| value | Array&lt;[ValueType](#valuetype)&gt; | 是 | 以ValueType型数组形式指定的要匹配的值。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.in("AGE", [18, 20])
```
### notIn<sup>9+</sup>
notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicatesV9
将RdbPredicatesV9配置为匹配数据字段为ValueType且值超出给定范围的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------ | ---- | ------------------------------------- |
| field | string | 是 | 数据库表中的列名。 |
| value | Array&lt;[ValueType](#valuetype)&gt; | 是 | 以ValueType数组形式指定的要匹配的值。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicatesV9](#rdbpredicatesv99) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicatesV9 = new data_rdb.RdbPredicatesV9("EMPLOYEE")
predicatesV9.notIn("NAME", ["Lisa", "Rose"])
```
## RdbStoreV9<sup>9+</sup>
提供管理关系数据库(RDB)方法的接口。
在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)
### insert<sup>9+</sup>
insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一行数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------- | ---- | ---------------------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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);
})
```
### insert<sup>9+</sup>
insert(table: string, values: ValuesBucket):Promise&lt;number&gt;
向目标表中插入一行数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------------- | ---- | -------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------------------------- |
| Promise&lt;number&gt; | 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");
})
```
### batchInsert<sup>9+</sup>
batchInsert(table: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一组数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | 是 | 表示要插入到表中的一组数据。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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);
})
```
### batchInsert<sup>9+</sup>
batchInsert(table: string, values: Array&lt;ValuesBucket&gt;):Promise&lt;number&gt;
向目标表中插入一组数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------------ | ---- | ---------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | 是 | 表示要插入到表中的一组数据。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------------------------- |
| Promise&lt;number&gt; | 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);
})
```
### update<sup>9+</sup>
update(values: ValuesBucket, predicates: RdbPredicatesV9, callback: AsyncCallback&lt;number&gt;):void
根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的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)
})
```
### update<sup>9+</sup>
update(values: ValuesBucket, predicates: RdbPredicatesV9):Promise&lt;number&gt;
根据RdbPredicatesV9的指定实例对象更新数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicatesV9 | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的更新条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | 指定的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)
})
```
### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):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&lt;number&gt; | 是 | 指定的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)
})
```
### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | 指定的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)
})
```
### delete<sup>9+</sup>
delete(predicates: RdbPredicatesV9, callback: AsyncCallback&lt;number&gt;):void
根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ----------------------------------------- |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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)
})
```
### delete<sup>9+</sup>
delete(predicates: RdbPredicatesV9):Promise&lt;number&gt;
根据RdbPredicatesV9的指定实例对象从数据库中删除数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ----------------------------------------- |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的删除条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise&lt;number&gt; | 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)
})
```
### delete<sup>9+</sup>
delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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)
})
```
### delete<sup>9+</sup>
delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise&lt;number&gt; | 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)
})
```
### query<sup>9+</sup>
query(predicates: RdbPredicatesV9, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSetV9&gt;):void
根据指定条件查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 是 | 指定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)
})
```
### query<sup>9+</sup>
query(predicates: RdbPredicatesV9, columns?: Array&lt;string&gt;):Promise&lt;ResultSetV9&gt;
根据指定条件查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------ |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 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)
})
```
### query<sup>9+</sup>
query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSetV9&gt;):void
根据指定条件查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 是 | 指定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)
})
```
### query<sup>9+</sup>
query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSetV9&gt;
根据指定条件查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 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)
})
```
### remoteQuery<sup>9+</sup>
remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array&lt;string&gt; , callback: AsyncCallback&lt;ResultSetV9&gt;): void
根据指定条件查询远程设备数据库中的数据。使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| device | string | 是 | 指定的远程设备的networkId。 |
| table | string | 是 | 指定的目标表名。 |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSetV9](js-apis-data-resultset.md#resultset)&gt; | 是 | 指定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)
})
```
### remoteQuery<sup>9+</sup>
remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array&lt;string&gt;): Promise&lt;ResultSetV9&gt;
根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------ |
| device | string | 是 | 指定的远程设备的networkId。 |
| table | string | 是 | 指定的目标表名。 |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | RdbPredicatesV9的实例对象,指定查询的条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------------ | -------------------------------------------------- |
| Promise&lt;[ResultSetV9](js-apis-data-resultset.md#resultset)&gt; | 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)
})
```
### querySql<sup>9+</sup>
querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSetV9&gt;):void
根据指定SQL语句查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 是 | SQL语句中参数的值。 |
| callback | AsyncCallback&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 是 | 指定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)
})
```
### querySql<sup>9+</sup>
querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSetV9&gt;
根据指定SQL语句查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | --------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 否 | SQL语句中参数的值。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSetV9](js-apis-data-resultset.md)&gt; | 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)
})
```
### executeSql<sup>9+</sup>
executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void
执行包含指定参数但不返回值的SQL语句,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | ---------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 是 | SQL语句中参数的值。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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.')
})
```
### executeSql<sup>9+</sup>
executeSql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;void&gt;
执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | --------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 否 | SQL语句中参数的值。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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)
})
```
### beginTransaction<sup>9+</sup>
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()
})
```
### commit<sup>9+</sup>
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()
})
```
### rollBack<sup>9+</sup>
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()
}
})
```
### backup<sup>9+</sup>
backup(destName:string, callback: AsyncCallback&lt;void&gt;):void
以指定名称备份数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------ |
| destName | string | 是 | 指定数据库的备份文件名。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**示例:**
```js
rdbStoreV9.backup("dbBackup.db", function(err) {
if (err) {
console.info('Backup failed, err: ' + err)
return
}
console.info('Backup success.')
})
```
### backup<sup>9+</sup>
backup(destName:string): Promise&lt;void&gt;
以指定名称备份数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------ |
| destName | string | 是 | 指定数据库的备份文件名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
```js
let promiseBackup = rdbStoreV9.backup("dbBackup.db")
promiseBackup.then(()=>{
console.info('Backup success.')
}).catch((err)=>{
console.info('Backup failed, err: ' + err)
})
```
### restore<sup>9+</sup>
restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void
从指定的数据库备份文件恢复数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------ |
| srcName | string | 是 | 指定数据库的备份文件名。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**示例:**
```js
rdbStoreV9.restore("dbBackup.db", function(err) {
if (err) {
console.info('Restore failed, err: ' + err)
return
}
console.info('Restore success.')
})
```
### restore<sup>9+</sup>
restore(srcName:string): Promise&lt;void&gt;
从指定的数据库备份文件恢复数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------ |
| srcName | string | 是 | 指定数据库的备份文件名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
```js
let promiseRestore = rdbStoreV9.restore("dbBackup.db")
promiseRestore.then(()=>{
console.info('Restore success.')
}).catch((err)=>{
console.info('Restore failed, err: ' + err)
})
```
### setDistributedTables<sup>9+</sup>
setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void
设置分布式列表,使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------- |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式列表表名 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**示例:**
```js
rdbStoreV9.setDistributedTables(["EMPLOYEE"], function (err) {
if (err) {
console.info('SetDistributedTables failed, err: ' + err)
return
}
console.info('SetDistributedTables successfully.')
})
```
### setDistributedTables<sup>9+</sup>
setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt;
设置分布式列表,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | ------------------------ |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式列表表名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
```js
let promise = rdbStoreV9.setDistributedTables(["EMPLOYEE"])
promise.then(() => {
console.info("SetDistributedTables successfully.")
}).catch((err) => {
console.info("SetDistributedTables failed, err: " + err)
})
```
### obtainDistributedTableName<sup>9+</sup>
obtainDistributedTableName(device: string, table: string, callback: AsyncCallback&lt;string&gt;): void
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| device | string | 是 | 远程设备 。 |
| table | string | 是 | 本地表名。 |
| callback | AsyncCallback&lt;string&gt; | 是 | 指定的callback回调函数。如果操作成功,返回远程设备的分布式表名。 |
**示例:**
```js
rdbStoreV9.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) {
if (err) {
console.info('ObtainDistributedTableName failed, err: ' + err)
return
}
console.info('ObtainDistributedTableName successfully, tableName=.' + tableName)
})
```
### obtainDistributedTableName<sup>9+</sup>
obtainDistributedTableName(device: string, table: string): Promise&lt;string&gt;
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---------- |
| device | string | 是 | 远程设备。 |
| table | string | 是 | 本地表名。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------------------- |
| Promise&lt;string&gt; | 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)
})
```
### sync<sup>9+</sup>
sync(mode: SyncMode, predicates: RdbPredicatesV9, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;): void
在设备之间同步数据, 使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ |
| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 |
| callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | 是 | 指定的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])
}
})
```
### sync<sup>9+</sup>
sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise&lt;Array&lt;[string, number]&gt;&gt;
在设备之间同步数据,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------ |
| mode | [SyncMode](#syncmode8) | 是 | 指同步模式。该值可以是推、拉。 |
| predicates | [RdbPredicatesV9](#rdbpredicatesv99) | 是 | 约束同步数据和设备。 |
**返回值**
| 类型 | 说明 |
| -------------------------------------------- | ------------------------------------------------------------ |
| Promise&lt;Array&lt;[string, number]&gt;&gt; | 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')<sup>9+</sup>
on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void
注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------------------------- |
| event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指分布式数据库中数据更改事件的观察者。 |
**示例:**
```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')<sup>9+</sup>
off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
从数据库中删除指定类型的指定观察者, 使用callback异步回调。 使用指定的数据库文件配置删除数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------------------------- |
| event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指已注册的数据更改观察者。 |
**示例:** | 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>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')
}
```
## StoreConfigV9<sup>9+</sup> | 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
管理关系数据库配置。 **示例:**
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core FA模型示例:
| 名称 | 类型 | 必填 | 说明 | ```js
| ------------- | ------------- | ---- | --------------------------------------------------------- | // 获取context
| name | string | 是 | 数据库文件名。 | import featureAbility from '@ohos.ability.featureAbility'
| securityLevel | SecurityLevel | 是 | 设置数据库安全级别 | let context = featureAbility.getContext()
| encrypt | boolean | 否 | 指定数据库是否加密。<br/> true:加密。<br/> false:非加密。 |
## SecurityLevel<sup>9+</sup> // 获取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
}
}
| 名称 | 值 | 说明 | // 获取context后调用deleteRdbStore
| ---- | ---- | ------------------------------------------------------------ | let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
| S1 | 1 | 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。 | promise.then(()=>{
| S2 | 2 | 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。 | console.log("Delete RdbStore successfully.")
| S3 | 3 | 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。 | }).catch((err) => {
| S4 | 4 | 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。 | console.info("Delete RdbStore failed, err: " + err)
})
```
## ValueType ## ValueType
...@@ -2714,7 +286,7 @@ try { ...@@ -2714,7 +286,7 @@ try {
指数据库同步模式。 指数据库同步模式。
**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
| -------------- | ---- | ---------------------------------- | | -------------- | ---- | ---------------------------------- |
...@@ -2733,25 +305,26 @@ try { ...@@ -2733,25 +305,26 @@ try {
| --------------------- | ---- | ------------------ | | --------------------- | ---- | ------------------ |
| SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 | | SUBSCRIBE_TYPE_REMOTE | 0 | 订阅远程数据更改。 |
## RdbPredicates<sup>(deprecated)</sup> ## StoreConfig
表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false 管理关系数据库配置
> **说明:** **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[RdbPredicatesV9](#rdbpredicatesv99)替代。 | 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 数据库文件名。 |
## RdbPredicates
### constructor<sup>(deprecated)</sup> 表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。
### constructor
constructor(name: string) constructor(name: string)
构造函数。 构造函数。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[constructor](#constructor9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -2766,16 +339,12 @@ constructor(name: string) ...@@ -2766,16 +339,12 @@ constructor(name: string)
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
``` ```
### inDevices<sup>(deprecated)</sup> ### inDevices<sup>8+</sup>
inDevices(devices: Array&lt;string&gt;): RdbPredicates inDevices(devices: Array&lt;string&gt;): RdbPredicates
同步分布式数据库时连接到组网内指定的远程设备。 同步分布式数据库时连接到组网内指定的远程设备。
> **说明:**
>
> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inDevices](#indevices9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -2797,16 +366,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -2797,16 +366,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.inDevices(['12345678abcde']) predicates.inDevices(['12345678abcde'])
``` ```
### inAllDevices<sup>(deprecated)</sup> ### inAllDevices<sup>8+</sup>
inAllDevices(): RdbPredicates inAllDevices(): RdbPredicates
同步分布式数据库时连接到组网内所有的远程设备。 同步分布式数据库时连接到组网内所有的远程设备。
> **说明:**
>
> 从 API Version 8 开始支持,从 API Version 9 开始废弃,建议使用[inAllDevices](#inalldevices9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -2822,16 +387,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -2822,16 +387,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.inAllDevices() predicates.inAllDevices()
``` ```
### equalTo<sup>(deprecated)</sup> ### equalTo
equalTo(field: string, value: ValueType): RdbPredicates equalTo(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[equalTo](#equalto9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -2855,16 +416,12 @@ predicates.equalTo("NAME", "lisi") ...@@ -2855,16 +416,12 @@ predicates.equalTo("NAME", "lisi")
``` ```
### notEqualTo<sup>(deprecated)</sup> ### notEqualTo
notEqualTo(field: string, value: ValueType): RdbPredicates notEqualTo(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[notEqualTo](#notequalto9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -2888,16 +445,12 @@ predicates.notEqualTo("NAME", "lisi") ...@@ -2888,16 +445,12 @@ predicates.notEqualTo("NAME", "lisi")
``` ```
### beginWrap<sup>(deprecated)</sup> ### beginWrap
beginWrap(): RdbPredicates beginWrap(): RdbPredicates
向谓词添加左括号。 向谓词添加左括号。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[beginWrap](#beginwrap9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -2918,16 +471,12 @@ predicates.equalTo("NAME", "lisi") ...@@ -2918,16 +471,12 @@ predicates.equalTo("NAME", "lisi")
.endWrap() .endWrap()
``` ```
### endWrap<sup>(deprecated)</sup> ### endWrap
endWrap(): RdbPredicates endWrap(): RdbPredicates
向谓词添加右括号。 向谓词添加右括号。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[endWrap](#endwrap9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -2948,16 +497,12 @@ predicates.equalTo("NAME", "lisi") ...@@ -2948,16 +497,12 @@ predicates.equalTo("NAME", "lisi")
.endWrap() .endWrap()
``` ```
### or<sup>(deprecated)</sup> ### or
or(): RdbPredicates or(): RdbPredicates
将或条件添加到谓词中。 将或条件添加到谓词中。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[or](#or9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -2975,16 +520,12 @@ predicates.equalTo("NAME", "Lisa") ...@@ -2975,16 +520,12 @@ predicates.equalTo("NAME", "Lisa")
.equalTo("NAME", "Rose") .equalTo("NAME", "Rose")
``` ```
### and<sup>(deprecated)</sup> ### and
and(): RdbPredicates and(): RdbPredicates
向谓词添加和条件。 向谓词添加和条件。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[and](#and9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -3002,16 +543,12 @@ predicates.equalTo("NAME", "Lisa") ...@@ -3002,16 +543,12 @@ predicates.equalTo("NAME", "Lisa")
.equalTo("SALARY", 200.5) .equalTo("SALARY", 200.5)
``` ```
### contains<sup>(deprecated)</sup> ### contains
contains(field: string, value: string): RdbPredicates contains(field: string, value: string): RdbPredicates
配置谓词以匹配数据字段为string且value包含指定值的字段。 配置谓词以匹配数据字段为string且value包含指定值的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[contains](#contains9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3034,16 +571,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3034,16 +571,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.contains("NAME", "os") predicates.contains("NAME", "os")
``` ```
### beginsWith<sup>(deprecated)</sup> ### beginsWith
beginsWith(field: string, value: string): RdbPredicates beginsWith(field: string, value: string): RdbPredicates
配置谓词以匹配数据字段为string且值以指定字符串开头的字段。 配置谓词以匹配数据字段为string且值以指定字符串开头的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[beginsWith](#beginswith9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3066,16 +599,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3066,16 +599,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.beginsWith("NAME", "os") predicates.beginsWith("NAME", "os")
``` ```
### endsWith<sup>(deprecated)</sup> ### endsWith
endsWith(field: string, value: string): RdbPredicates endsWith(field: string, value: string): RdbPredicates
配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。 配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[endsWith](#endswith9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3098,16 +627,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3098,16 +627,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.endsWith("NAME", "se") predicates.endsWith("NAME", "se")
``` ```
### isNull<sup>(deprecated)</sup> ### isNull
isNull(field: string): RdbPredicates isNull(field: string): RdbPredicates
配置谓词以匹配值为null的字段。 配置谓词以匹配值为null的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNull](#isnull9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3128,16 +653,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3128,16 +653,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNull("NAME") predicates.isNull("NAME")
``` ```
### isNotNull<sup>(deprecated)</sup> ### isNotNull
isNotNull(field: string): RdbPredicates isNotNull(field: string): RdbPredicates
配置谓词以匹配值不为null的指定字段。 配置谓词以匹配值不为null的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[isNotNull](#isnotnull9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3159,16 +680,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3159,16 +680,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNotNull("NAME") predicates.isNotNull("NAME")
``` ```
### like<sup>(deprecated)</sup> ### like
like(field: string, value: string): RdbPredicates like(field: string, value: string): RdbPredicates
配置谓词以匹配数据字段为string且值类似于指定字符串的字段。 配置谓词以匹配数据字段为string且值类似于指定字符串的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[like](#like9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3191,16 +708,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3191,16 +708,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.like("NAME", "%os%") predicates.like("NAME", "%os%")
``` ```
### glob<sup>(deprecated)</sup> ### glob
glob(field: string, value: string): RdbPredicates glob(field: string, value: string): RdbPredicates
配置RdbPredicates匹配数据字段为string的指定字段。 配置RdbPredicates匹配数据字段为string的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[glob](#glob9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3223,16 +736,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3223,16 +736,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.glob("NAME", "?h*g") predicates.glob("NAME", "?h*g")
``` ```
### between<sup>(deprecated)</sup> ### between
between(field: string, low: ValueType, high: ValueType): RdbPredicates between(field: string, low: ValueType, high: ValueType): RdbPredicates
将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[between](#between9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3256,16 +765,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3256,16 +765,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.between("AGE", 10, 50) predicates.between("AGE", 10, 50)
``` ```
### notBetween<sup>(deprecated)</sup> ### notBetween
notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates
配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。 配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notBetween](#notbetween9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3289,16 +794,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3289,16 +794,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notBetween("AGE", 10, 50) predicates.notBetween("AGE", 10, 50)
``` ```
### greaterThan<sup>(deprecated)</sup> ### greaterThan
greaterThan(field: string, value: ValueType): RdbPredicates greaterThan(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为ValueType且值大于指定值的字段。 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThan](#greaterthan9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3321,16 +822,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3321,16 +822,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThan("AGE", 18) predicates.greaterThan("AGE", 18)
``` ```
### lessThan<sup>(deprecated)</sup> ### lessThan
lessThan(field: string, value: ValueType): RdbPredicates lessThan(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为valueType且value小于指定值的字段。 配置谓词以匹配数据字段为valueType且value小于指定值的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThan](#lessthan9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3353,16 +850,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3353,16 +850,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThan("AGE", 20) predicates.lessThan("AGE", 20)
``` ```
### greaterThanOrEqualTo<sup>(deprecated)</sup> ### greaterThanOrEqualTo
greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[greaterThanOrEqualTo](#greaterthanorequalto9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3385,16 +878,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3385,16 +878,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThanOrEqualTo("AGE", 18) predicates.greaterThanOrEqualTo("AGE", 18)
``` ```
### lessThanOrEqualTo<sup>(deprecated)</sup> ### lessThanOrEqualTo
lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates
配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[lessThanOrEqualTo](#lessthanorequalto9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3417,16 +906,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3417,16 +906,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThanOrEqualTo("AGE", 20) predicates.lessThanOrEqualTo("AGE", 20)
``` ```
### orderByAsc<sup>(deprecated)</sup> ### orderByAsc
orderByAsc(field: string): RdbPredicates orderByAsc(field: string): RdbPredicates
配置谓词以匹配其值按升序排序的列。 配置谓词以匹配其值按升序排序的列。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByAsc](#orderbyasc9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3448,16 +933,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3448,16 +933,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByAsc("NAME") predicates.orderByAsc("NAME")
``` ```
### orderByDesc<sup>(deprecated)</sup> ### orderByDesc
orderByDesc(field: string): RdbPredicates orderByDesc(field: string): RdbPredicates
配置谓词以匹配其值按降序排序的列。 配置谓词以匹配其值按降序排序的列。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[orderByDesc](#orderbydesc9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3479,16 +960,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3479,16 +960,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByDesc("AGE") predicates.orderByDesc("AGE")
``` ```
### distinct<sup>(deprecated)</sup> ### distinct
distinct(): RdbPredicates distinct(): RdbPredicates
配置谓词以过滤重复记录并仅保留其中一个。 配置谓词以过滤重复记录并仅保留其中一个。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[distinct](#distinct9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值** **返回值**
...@@ -3504,16 +981,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3504,16 +981,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct() predicates.equalTo("NAME", "Rose").distinct()
``` ```
### limitAs<sup>(deprecated)</sup> ### limitAs
limitAs(value: number): RdbPredicates limitAs(value: number): RdbPredicates
设置最大数据记录数的谓词。 设置最大数据记录数的谓词。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[limitAs](#limitas9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3535,16 +1008,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3535,16 +1008,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").limitAs(3) predicates.equalTo("NAME", "Rose").limitAs(3)
``` ```
### offsetAs<sup>(deprecated)</sup> ### offsetAs
offsetAs(rowOffset: number): RdbPredicates offsetAs(rowOffset: number): RdbPredicates
配置RdbPredicates以指定返回结果的起始位置。 配置RdbPredicates以指定返回结果的起始位置。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[offsetAs](#offsetas9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3566,16 +1035,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3566,16 +1035,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").offsetAs(3) predicates.equalTo("NAME", "Rose").offsetAs(3)
``` ```
### groupBy<sup>(deprecated)</sup> ### groupBy
groupBy(fields: Array&lt;string&gt;): RdbPredicates groupBy(fields: Array&lt;string&gt;): RdbPredicates
配置RdbPredicates按指定列分组查询结果。 配置RdbPredicates按指定列分组查询结果。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[groupBy](#groupby9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3597,16 +1062,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3597,16 +1062,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.groupBy(["AGE", "NAME"]) predicates.groupBy(["AGE", "NAME"])
``` ```
### indexedBy<sup>(deprecated)</sup> ### indexedBy
indexedBy(field: string): RdbPredicates indexedBy(field: string): RdbPredicates
配置RdbPredicates以指定索引列。 配置RdbPredicates以指定索引列。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[indexedBy](#indexedby9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3629,16 +1090,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3629,16 +1090,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.indexedBy("SALARY_INDEX") predicates.indexedBy("SALARY_INDEX")
``` ```
### in<sup>(deprecated)</sup> ### in
in(field: string, value: Array&lt;ValueType&gt;): RdbPredicates in(field: string, value: Array&lt;ValueType&gt;): RdbPredicates
配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。 配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[in](#in9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3661,16 +1118,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3661,16 +1118,12 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.in("AGE", [18, 20]) predicates.in("AGE", [18, 20])
``` ```
### notIn<sup>(deprecated)</sup> ### notIn
notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicates notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicates
将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。 将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[notIn](#notin9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3693,26 +1146,18 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ...@@ -3693,26 +1146,18 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notIn("NAME", ["Lisa", "Rose"]) predicates.notIn("NAME", ["Lisa", "Rose"])
``` ```
## RdbStore<sup>(deprecated)</sup> ## RdbStore
提供管理关系数据库(RDB)方法的接口。 提供管理关系数据库(RDB)方法的接口。
> **说明:** 在使用以下相关接口前,请使用[executeSql](#executesql8)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[RdbStoreV9](#rdbstorev99)替代。
在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据,具体可见[关系型数据库开发指导](../../database/database-relational-guidelines.md)
### insert<sup>(deprecated)</sup> ### insert
insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一行数据,使用callback异步回调。 向目标表中插入一行数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3741,16 +1186,12 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { ...@@ -3741,16 +1186,12 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) {
}) })
``` ```
### insert<sup>(deprecated)</sup> ### insert
insert(table: string, values: ValuesBucket):Promise&lt;number&gt; insert(table: string, values: ValuesBucket):Promise&lt;number&gt;
向目标表中插入一行数据,使用Promise异步回调。 向目标表中插入一行数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[insert](#insert9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3783,16 +1224,12 @@ promise.then((rowId) => { ...@@ -3783,16 +1224,12 @@ promise.then((rowId) => {
}) })
``` ```
### batchInsert<sup>(deprecated)</sup> ### batchInsert
batchInsert(table: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;):void batchInsert(table: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一组数据,使用callback异步回调。 向目标表中插入一组数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3835,16 +1272,12 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { ...@@ -3835,16 +1272,12 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) {
}) })
``` ```
### batchInsert<sup>(deprecated)</sup> ### batchInsert
batchInsert(table: string, values: Array&lt;ValuesBucket&gt;):Promise&lt;number&gt; batchInsert(table: string, values: Array&lt;ValuesBucket&gt;):Promise&lt;number&gt;
向目标表中插入一组数据,使用Promise异步回调。 向目标表中插入一组数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[batchInsert](#batchinsert9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3891,16 +1324,12 @@ promise.then((insertNum) => { ...@@ -3891,16 +1324,12 @@ promise.then((insertNum) => {
}) })
``` ```
### update<sup>(deprecated)</sup> ### update
update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。 根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3922,25 +1351,21 @@ const valueBucket = { ...@@ -3922,25 +1351,21 @@ const valueBucket = {
} }
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
rdbStore.update(valueBucket, predicates, function (err, ret) { rdbStore.update(valueBucket, predicates, function (err, rows) {
if (err) { if (err) {
console.info("Updated failed, err: " + err) console.info("Updated failed, err: " + err)
return return
} }
console.log("Updated row count: " + ret) console.log("Updated row count: " + rows)
}) })
``` ```
### update<sup>(deprecated)</sup> ### update
update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt; update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt;
根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。 根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[update](#update9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -3968,23 +1393,19 @@ const valueBucket = { ...@@ -3968,23 +1393,19 @@ const valueBucket = {
let predicates = new data_rdb.RdbPredicates("EMPLOYEE") let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa") predicates.equalTo("NAME", "Lisa")
let promise = rdbStore.update(valueBucket, predicates) let promise = rdbStore.update(valueBucket, predicates)
promise.then(async (ret) => { promise.then(async (rows) => {
console.log("Updated row count: " + ret) console.log("Updated row count: " + rows)
}).catch((err) => { }).catch((err) => {
console.info("Updated failed, err: " + err) console.info("Updated failed, err: " + err)
}) })
``` ```
### delete<sup>(deprecated)</sup> ### delete
delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。 根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4008,16 +1429,12 @@ rdbStore.delete(predicates, function (err, rows) { ...@@ -4008,16 +1429,12 @@ rdbStore.delete(predicates, function (err, rows) {
}) })
``` ```
### delete<sup>(deprecated)</sup> ### delete
delete(predicates: RdbPredicates):Promise&lt;number&gt; delete(predicates: RdbPredicates):Promise&lt;number&gt;
根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。 根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[delete](#delete9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4045,16 +1462,12 @@ promise.then((rows) => { ...@@ -4045,16 +1462,12 @@ promise.then((rows) => {
}) })
``` ```
### query<sup>(deprecated)</sup> ### query
query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
根据指定条件查询数据库中的数据,使用callback异步回调。 根据指定条件查询数据库中的数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4080,16 +1493,12 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e ...@@ -4080,16 +1493,12 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e
}) })
``` ```
### query<sup>(deprecated)</sup> ### query
query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
根据指定条件查询数据库中的数据,使用Promise异步回调。 根据指定条件查询数据库中的数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[query](#query9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4119,16 +1528,12 @@ query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;Resul ...@@ -4119,16 +1528,12 @@ query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;Resul
}) })
``` ```
### querySql<sup>(deprecated)</sup> ### querySql<sup>8+</sup>
querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
根据指定SQL语句查询数据库中的数据,使用callback异步回调。 根据指定SQL语句查询数据库中的数据,使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4152,16 +1557,12 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ...@@ -4152,16 +1557,12 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?",
}) })
``` ```
### querySql<sup>(deprecated)</sup> ### querySql<sup>8+</sup>
querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt;
根据指定SQL语句查询数据库中的数据,使用Promise异步回调。 根据指定SQL语句查询数据库中的数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[querySql](#querysql9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4189,16 +1590,12 @@ promise.then((resultSet) => { ...@@ -4189,16 +1590,12 @@ promise.then((resultSet) => {
}) })
``` ```
### executeSql<sup>(deprecated)</sup> ### executeSql<sup>8+</sup>
executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void executeSql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void
执行包含指定参数但不返回值的SQL语句,使用callback异步回调。 执行包含指定参数但不返回值的SQL语句,使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-1)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4222,16 +1619,12 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { ...@@ -4222,16 +1619,12 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) {
}) })
``` ```
### executeSql<sup>(deprecated)</sup> ### executeSql<sup>8+</sup>
executeSql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;void&gt; executeSql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;void&gt;
执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。 执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[executeSql](#executesql9-2)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4259,16 +1652,12 @@ promise.then(() => { ...@@ -4259,16 +1652,12 @@ promise.then(() => {
}) })
``` ```
### beginTransaction<sup>(deprecated)</sup> ### beginTransaction<sup>8+</sup>
beginTransaction():void beginTransaction():void
在开始执行SQL语句之前,开始事务。 在开始执行SQL语句之前,开始事务。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[beginTransaction](#begintransaction9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**示例:** **示例:**
...@@ -4290,16 +1679,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { ...@@ -4290,16 +1679,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
}) })
``` ```
### commit<sup>(deprecated)</sup> ### commit<sup>8+</sup>
commit():void commit():void
提交已执行的SQL语句。 提交已执行的SQL语句。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[commit](#commit9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**示例:** **示例:**
...@@ -4321,16 +1706,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { ...@@ -4321,16 +1706,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
}) })
``` ```
### rollBack<sup>(deprecated)</sup> ### rollBack<sup>8+</sup>
rollBack():void rollBack():void
回滚已经执行的SQL语句。 回滚已经执行的SQL语句。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[rollBack](#rollback9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**示例:** **示例:**
...@@ -4357,16 +1738,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { ...@@ -4357,16 +1738,12 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) {
}) })
``` ```
### setDistributedTables<sup>(deprecated)</sup> ### setDistributedTables<sup>8+</sup>
setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void setDistributedTables(tables: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void
设置分布式列表,使用callback异步回调。 设置分布式列表,使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-1)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4390,16 +1767,12 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { ...@@ -4390,16 +1767,12 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
}) })
``` ```
### setDistributedTables<sup>(deprecated)</sup> ### setDistributedTables<sup>8+</sup>
setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt; setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt;
设置分布式列表,使用Promise异步回调。 设置分布式列表,使用Promise异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[setDistributedTables](#setdistributedtables9-2)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4427,16 +1800,12 @@ promise.then(() => { ...@@ -4427,16 +1800,12 @@ promise.then(() => {
}) })
``` ```
### obtainDistributedTableName<sup>(deprecated)</sup> ### obtainDistributedTableName<sup>8+</sup>
obtainDistributedTableName(device: string, table: string, callback: AsyncCallback&lt;string&gt;): void obtainDistributedTableName(device: string, table: string, callback: AsyncCallback&lt;string&gt;): void
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-1)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4461,16 +1830,12 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, ...@@ -4461,16 +1830,12 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err,
}) })
``` ```
### obtainDistributedTableName<sup>(deprecated)</sup> ### obtainDistributedTableName<sup>8+</sup>
obtainDistributedTableName(device: string, table: string): Promise&lt;string&gt; obtainDistributedTableName(device: string, table: string): Promise&lt;string&gt;
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。 根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[obtainDistributedTableName](#obtaindistributedtablename9-2)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4499,16 +1864,12 @@ promise.then((tableName) => { ...@@ -4499,16 +1864,12 @@ promise.then((tableName) => {
}) })
``` ```
### sync<sup>(deprecated)</sup> ### sync<sup>8+</sup>
sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;): void sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;): void
在设备之间同步数据, 使用callback异步回调。 在设备之间同步数据, 使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-1)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4538,16 +1899,12 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul ...@@ -4538,16 +1899,12 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul
}) })
``` ```
### sync<sup>(deprecated)</sup> ### sync<sup>8+</sup>
sync(mode: SyncMode, predicates: RdbPredicates): Promise&lt;Array&lt;[string, number]&gt;&gt; sync(mode: SyncMode, predicates: RdbPredicates): Promise&lt;Array&lt;[string, number]&gt;&gt;
在设备之间同步数据,使用Promise异步回调。 在设备之间同步数据,使用Promise异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[sync](#sync9-2)替代。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -4581,16 +1938,12 @@ promise.then((result) =>{ ...@@ -4581,16 +1938,12 @@ promise.then((result) =>{
}) })
``` ```
### on('dataChange')<sup>(deprecated)</sup> ### on('dataChange')<sup>8+</sup>
on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void
注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。 注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[on](#ondatachange9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4598,7 +1951,7 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;stri ...@@ -4598,7 +1951,7 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;stri
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | string | 是 | 取值为'dataChange',表示数据更改。 | | event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | | type | [SubscribeType](#subscribetype8) | 是 | 订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指分布式数据库中数据更改事件的观察者。 | | observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指分布式数据库中数据更改事件的观察者。 |
**示例:** **示例:**
...@@ -4616,16 +1969,12 @@ try { ...@@ -4616,16 +1969,12 @@ try {
} }
``` ```
### off('dataChange')<sup>(deprecated)</sup> ### off('dataChange')<sup>8+</sup>
off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;string&gt;&gt;): void
从数据库中删除指定类型的指定观察者, 使用callback异步回调。 从数据库中删除指定类型的指定观察者, 使用callback异步回调。
> **说明:**
>
> 从 API Version 8开始支持,从 API Version 9 开始废弃,建议使用[off](#offdatachange9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -4633,7 +1982,7 @@ off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;stri ...@@ -4633,7 +1982,7 @@ off(event:'dataChange', type: SubscribeType, observer: Callback&lt;Array&lt;stri
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | string | 是 | 取值为'dataChange',表示数据更改。 | | event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype8) | 是 | 指在{@code SubscribeType}中定义的订阅类型。 | | type | [SubscribeType](#subscribetype8) | 是 | 订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指已注册的数据更改观察者。| | observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指已注册的数据更改观察者。|
**示例:** **示例:**
...@@ -4650,18 +1999,3 @@ try { ...@@ -4650,18 +1999,3 @@ try {
console.log('Unregister observer failed') console.log('Unregister observer failed')
} }
``` ```
## StoreConfig<sup>(deprecated)</sup>
管理关系数据库配置。
**说明:**
从 API Version 7开始支持,从 API Version 9 开始废弃,建议使用[StoreConfigV9](#storeconfigv99)替代。
**系统能力:**SystemCapability.DistributedDataManager.RelationalStore.Core
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| name | string | 是 | 数据库文件名。 |
# @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&lt;RdbStore&gt;): void
获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 |
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | 是 | 指定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&lt;RdbStore&gt;
获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 |
**返回值**
| 类型 | 说明 |
| ----------------------------------------- | --------------------------------- |
| Promise&lt;[RdbStore](#rdbstore)&gt; | 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&lt;void&gt;): void
删除数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| name | string | 是 | 数据库名称。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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&lt;void&gt;
使用指定的数据库文件配置删除数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | ------------------------------------------------------------ |
| context | Context | 是 | 应用的上下文。 <br>FA模型的应用Context定义见[Context](js-apis-inner-app-context.md)<br>Stage模型的应用Context定义见[Context](js-apis-ability-context.md)。 |
| name | string | 是 | 数据库名称。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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 | 否 | 指定数据库是否加密。<br/> true:加密。<br/> 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)\|&nbsp;Uint8Array&nbsp;\|&nbsp;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 | 订阅远程数据更改。 |
## ConflictResolution<sup>10+</sup>
插入和修改接口的冲突解决方式。
**系统能力:** 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 | 表示当冲突发生时,在插入或更新当前行之前删除导致约束违例的预先存在的行,并且命令会继续正常执行。 |
## OpenStatus<sup>10+</sup>
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&lt;string&gt;): RdbPredicates
同步分布式数据库时连接到组网内指定的远程设备。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------- | ---- | -------------------------- |
| devices | Array&lt;string&gt; | 是 | 指定的组网内的远程设备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 | 是 | 指示要与谓词匹配的值。<br>支持通配符,*表示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&lt;string&gt;): RdbPredicates
配置RdbPredicates按指定列分组查询结果。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | -------------------- |
| fields | Array&lt;string&gt; | 是 | 指定分组依赖的列名。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | ---------------------- |
| [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&lt;ValueType&gt;): RdbPredicates
配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------ | ---- | --------------------------------------- |
| field | string | 是 | 数据库表中的列名。 |
| value | Array&lt;[ValueType](#valuetype)&gt; | 是 | 以ValueType型数组形式指定的要匹配的值。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------ | -------------------------- |
| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 |
**示例:**
```js
let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.in("AGE", [18, 20])
```
### notIn
notIn(field: string, value: Array&lt;ValueType&gt;): RdbPredicates
将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------ | ---- | ------------------------------------- |
| field | string | 是 | 数据库表中的列名。 |
| value | Array&lt;[ValueType](#valuetype)&gt; | 是 | 以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)
### 属性<sup>10+</sup>
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
| 名称 | 类型 | 必填 | 说明 |
| ------------ | ----------- | ---- | -------------------------------- |
| openStatus<sup>10+</sup> | number | 是 | RdbStore的状态。值为0时,表示RdbStore首次创建,处于ON_CREATE状态。值为1时,表示RdbStore非首次创建,处于ON_OPEN状态。 |
### insert
insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一行数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------- | ---- | ---------------------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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);
})
```
### insert<sup>10+</sup>
insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一行数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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&lt;number&gt;
向目标表中插入一行数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ----------------------------- | ---- | -------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------------------------- |
| Promise&lt;number&gt; | 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");
})
```
### insert<sup>10+</sup>
insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise&lt;number&gt;
向目标表中插入一行数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | -------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | 表示要插入到表中的数据行。 |
| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------------------------- |
| Promise&lt;number&gt; | 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&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;):void
向目标表中插入一组数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | 是 | 表示要插入到表中的一组数据。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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&lt;ValuesBucket&gt;):Promise&lt;number&gt;
向目标表中插入一组数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------------------ | ---- | ---------------------------- |
| table | string | 是 | 指定的目标表名。 |
| values | Array&lt;[ValuesBucket](#valuesbucket)&gt; | 是 | 表示要插入到表中的一组数据。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------------------------- |
| Promise&lt;number&gt; | 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&lt;number&gt;):void
根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的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)
})
```
### update<sup>10+</sup>
update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback&lt;number&gt;):void
根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 |
| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的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&lt;number&gt;
根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | 指定的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)
})
```
### update<sup>10+</sup>
update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise&lt;number&gt;
根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 |
| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | 指定的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&lt;number&gt;):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&lt;number&gt; | 是 | 指定的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&lt;number&gt;
根据DataSharePredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| values | [ValuesBucket](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的更新条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------- |
| Promise&lt;number&gt; | 指定的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&lt;number&gt;):void
根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ----------------------------------------- |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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&lt;number&gt;
根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ----------------------------------------- |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的删除条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise&lt;number&gt; | 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&lt;number&gt;):void
根据DataSharePredicates的指定实例对象从数据库中删除数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定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&lt;number&gt;
根据DataSharePredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的删除条件。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ------------------------------- |
| Promise&lt;number&gt; | 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&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
根据指定条件查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | 是 | 指定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&lt;string&gt;):Promise&lt;ResultSet&gt;
根据指定条件查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------ |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | 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&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
根据指定条件查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | 是 | 指定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&lt;string&gt;):Promise&lt;ResultSet&gt;
根据指定条件查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**系统接口:** 此接口为系统接口。
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ |
| table | string | 是 | 指定的目标表名。 |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | 是 | DataSharePredicates的实例对象指定的查询条件。 |
| columns | Array&lt;string&gt; | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | 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&lt;string&gt; , callback: AsyncCallback&lt;ResultSet&gt;): void
根据指定条件查询远程设备数据库中的数据。使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| device | string | 是 | 指定的远程设备的networkId。 |
| table | string | 是 | 指定的目标表名。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | 是 | 指定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&lt;string&gt;): Promise&lt;ResultSet&gt;
根据指定条件查询远程设备数据库中的数据。使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------------------------ |
| device | string | 是 | 指定的远程设备的networkId。 |
| table | string | 是 | 指定的目标表名。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象,指定查询的条件。 |
| columns | Array&lt;string&gt; | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------------ | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | 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&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
根据指定SQL语句查询数据库中的数据,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 是 | SQL语句中参数的值。 |
| callback | AsyncCallback&lt;[ResultSet](#resultset)&gt; | 是 | 指定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&lt;ValueType&gt;):Promise&lt;ResultSet&gt;
根据指定SQL语句查询数据库中的数据,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | --------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 否 | SQL语句中参数的值。 |
**返回值**
| 类型 | 说明 |
| ------------------------------------------------------- | -------------------------------------------------- |
| Promise&lt;[ResultSet](#resultset)&gt; | 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&lt;ValueType&gt;, callback: AsyncCallback&lt;void&gt;):void
执行包含指定参数但不返回值的SQL语句,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | ---------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 是 | SQL语句中参数的值。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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&lt;ValueType&gt;):Promise&lt;void&gt;
执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | --------------------- |
| sql | string | 是 | 指定要执行的SQL语句。 |
| bindArgs | Array&lt;[ValueType](#valuetype)&gt; | 否 | SQL语句中参数的值。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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&lt;void&gt;):void
以指定名称备份数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------ |
| destName | string | 是 | 指定数据库的备份文件名。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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&lt;void&gt;
以指定名称备份数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ------------------------ |
| destName | string | 是 | 指定数据库的备份文件名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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&lt;void&gt;):void
从指定的数据库备份文件恢复数据库,使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ------------------------ |
| srcName | string | 是 | 指定数据库的备份文件名。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定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&lt;void&gt;
从指定的数据库备份文件恢复数据库,使用Promise异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------ |
| srcName | string | 是 | 指定数据库的备份文件名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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&lt;string&gt;, callback: AsyncCallback&lt;void&gt;): void
设置分布式列表,使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------------------- |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式列表表名 |
| callback | AsyncCallback&lt;void&gt; | 是 | 指定callback回调函数。 |
**示例:**
```js
rdbStore.setDistributedTables(["EMPLOYEE"], function (err) {
if (err) {
console.info('SetDistributedTables failed, err: ' + err)
return
}
console.info('SetDistributedTables successfully.')
})
```
### setDistributedTables
setDistributedTables(tables: Array&lt;string&gt;): Promise&lt;void&gt;
设置分布式列表,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------- | ---- | ------------------------ |
| tables | Array&lt;string&gt; | 是 | 要设置的分布式列表表名。 |
**返回值**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的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&lt;string&gt;): void
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名, 使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
| device | string | 是 | 远程设备 。 |
| table | string | 是 | 本地表名。 |
| callback | AsyncCallback&lt;string&gt; | 是 | 指定的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&lt;string&gt;
根据本地表名获取指定远程设备的分布式表名。在查询远程设备数据库时,需要使用分布式表名,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ---------- |
| device | string | 是 | 远程设备。 |
| table | string | 是 | 本地表名。 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------------------------------------------- |
| Promise&lt;string&gt; | 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&lt;Array&lt;[string, number]&gt;&gt;): void
在设备之间同步数据, 使用callback异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ |
| mode | [SyncMode](#syncmode) | 是 | 指同步模式。该值可以是推、拉。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | 约束同步数据和设备。 |
| callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | 是 | 指定的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&lt;Array&lt;[string, number]&gt;&gt;
在设备之间同步数据,使用Promise异步回调。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------------------ | ---- | ------------------------------ |
| mode | [SyncMode](#syncmode) | 是 | 指同步模式。该值可以是推、拉。 |
| predicates | [RdbPredicates](#rdbpredicates) | 是 | 约束同步数据和设备。 |
**返回值**
| 类型 | 说明 |
| -------------------------------------------- | ------------------------------------------------------------ |
| Promise&lt;Array&lt;[string, number]&gt;&gt; | 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&lt;Array&lt;string&gt;&gt;): void
注册数据库的观察者。当分布式数据库中的数据发生更改时,将调用回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ------------------------------------------- |
| event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype) | 是 | 订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指分布式数据库中数据更改事件的观察者。 |
**示例:**
```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&lt;Array&lt;string&gt;&gt;): void
从数据库中删除指定类型的指定观察者, 使用callback异步回调。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------- | ---- | ------------------------------------------ |
| event | string | 是 | 取值为'dataChange',表示数据更改。 |
| type | [SubscribeType](#subscribetype) | 是 | 订阅类型。 |
| observer | Callback&lt;Array&lt;string&gt;&gt; | 是 | 指已注册的数据更改观察者。 |
**示例:**
```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&lt;string&gt; | 是 | 获取结果集中所有列的名称。 |
| 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. |
...@@ -5,545 +5,13 @@ ...@@ -5,545 +5,13 @@
> **说明:** > **说明:**
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> 从API Version 9开始,该接口不再维护,推荐使用新接口[@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset)。
## ResultSetV9<sup>9+</sup> ## ResultSet
提供通过查询数据库生成的数据库结果集的访问方法。
### 使用说明
需要通过[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);
});
```
### 属性<sup>9+</sup>
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
| 名称 | 类型 | 必填 | 说明 |
| ------------ | ------------------- | ---- | -------------------------------- |
| columnNames | Array&lt;string&gt; | 是 | 获取结果集中所有列的名称。 |
| columnCount | number | 是 | 获取结果集中的列数。 |
| rowCount | number | 是 | 获取结果集中的行数。 |
| rowIndex | number | 是 | 获取结果集当前行的索引。 |
| isAtFirstRow | boolean | 是 | 检查结果集是否位于第一行。 |
| isAtLastRow | boolean | 是 | 检查结果集是否位于最后一行。 |
| isEnded | boolean | 是 | 检查结果集是否位于最后一行之后。 |
| isStarted | boolean | 是 | 检查指针是否移动过。 |
| isClosed | boolean | 是 | 检查当前结果集是否关闭。 |
### getColumnIndex<sup>9+</sup>
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"));
```
### getColumnName<sup>9+</sup>
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);
```
### goTo<sup>9+</sup>
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');
});
```
### goToRow<sup>9+</sup>
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');
});
```
### goToFirstRow<sup>9+</sup>
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');
});
```
### goToLastRow<sup>9+</sup>
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');
});
```
### goToNextRow<sup>9+</sup>
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');
});
```
### goToPreviousRow<sup>9+</sup>
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');
});
```
### getBlob<sup>9+</sup>
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"));
```
### getString<sup>9+</sup>
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"));
```
### getLong<sup>9+</sup>
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"));
```
### getDouble<sup>9+</sup>
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"));
```
### isColumnNull<sup>9+</sup>
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"));
```
### close<sup>9+</sup>
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<sup>(deprecated)</sup>
提供通过查询数据库生成的数据库结果集的访问方法。 提供通过查询数据库生成的数据库结果集的访问方法。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[ResultSetV9](#resultsetv99)替代。
### 使用说明 ### 使用说明
需要通过[RdbStore.query()](js-apis-data-rdb.md#query)获取resultSet对象。 需要通过[RdbStore.query()](js-apis-data-rdb.md#query)获取resultSet对象。
...@@ -559,11 +27,7 @@ promise.then((resultSet) => { ...@@ -559,11 +27,7 @@ promise.then((resultSet) => {
}); });
``` ```
### 属性<sup>(deprecated)</sup> ### 属性
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[属性](#属性9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -579,16 +43,12 @@ promise.then((resultSet) => { ...@@ -579,16 +43,12 @@ promise.then((resultSet) => {
| isStarted | boolean | 是 | 检查指针是否移动过。 | | isStarted | boolean | 是 | 检查指针是否移动过。 |
| isClosed | boolean | 是 | 检查当前结果集是否关闭。 | | isClosed | boolean | 是 | 检查当前结果集是否关闭。 |
### getColumnIndex<sup>(deprecated)</sup> ### getColumnIndex
getColumnIndex(columnName: string): number getColumnIndex(columnName: string): number
根据指定的列名获取列索引。 根据指定的列名获取列索引。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnIndex](#getcolumnindex9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -613,16 +73,12 @@ getColumnIndex(columnName: string): number ...@@ -613,16 +73,12 @@ getColumnIndex(columnName: string): number
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
``` ```
### getColumnName<sup>(deprecated)</sup> ### getColumnName
getColumnName(columnIndex: number): string getColumnName(columnIndex: number): string
根据指定的列索引获取列名。 根据指定的列索引获取列名。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getColumnName](#getcolumnname9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -645,16 +101,12 @@ getColumnName(columnIndex: number): string ...@@ -645,16 +101,12 @@ getColumnName(columnIndex: number): string
const age = resultSet.getColumnName(2); const age = resultSet.getColumnName(2);
``` ```
### goTo<sup>(deprecated)</sup> ### goTo
goTo(offset:number): boolean goTo(offset:number): boolean
向前或向后转至结果集的指定行,相对于其当前位置偏移。 向前或向后转至结果集的指定行,相对于其当前位置偏移。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goTo](#goto9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -682,16 +134,12 @@ goTo(offset:number): boolean ...@@ -682,16 +134,12 @@ goTo(offset:number): boolean
}); });
``` ```
### goToRow<sup>(deprecated)</sup> ### goToRow
goToRow(position: number): boolean goToRow(position: number): boolean
转到结果集的指定行。 转到结果集的指定行。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToRow](#gotorow9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -719,16 +167,12 @@ goToRow(position: number): boolean ...@@ -719,16 +167,12 @@ goToRow(position: number): boolean
}); });
``` ```
### goToFirstRow<sup>(deprecated)</sup> ### goToFirstRow
goToFirstRow(): boolean goToFirstRow(): boolean
转到结果集的第一行。 转到结果集的第一行。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToFirstRow](#gotofirstrow9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值:** **返回值:**
...@@ -750,16 +194,12 @@ goToFirstRow(): boolean ...@@ -750,16 +194,12 @@ goToFirstRow(): boolean
}); });
``` ```
### goToLastRow<sup>(deprecated)</sup> ### goToLastRow
goToLastRow(): boolean goToLastRow(): boolean
转到结果集的最后一行。 转到结果集的最后一行。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToLastRow](#gotolastrow9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值:** **返回值:**
...@@ -781,16 +221,12 @@ goToLastRow(): boolean ...@@ -781,16 +221,12 @@ goToLastRow(): boolean
}); });
``` ```
### goToNextRow<sup>(deprecated)</sup> ### goToNextRow
goToNextRow(): boolean goToNextRow(): boolean
转到结果集的下一行。 转到结果集的下一行。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToNextRow](#gotonextrow9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值:** **返回值:**
...@@ -812,16 +248,12 @@ goToNextRow(): boolean ...@@ -812,16 +248,12 @@ goToNextRow(): boolean
}); });
``` ```
### goToPreviousRow<sup>(deprecated)</sup> ### goToPreviousRow
goToPreviousRow(): boolean goToPreviousRow(): boolean
转到结果集的上一行。 转到结果集的上一行。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[goToPreviousRow](#gotopreviousrow9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**返回值:** **返回值:**
...@@ -843,16 +275,12 @@ goToPreviousRow(): boolean ...@@ -843,16 +275,12 @@ goToPreviousRow(): boolean
}); });
``` ```
### getBlob<sup>(deprecated)</sup> ### getBlob
getBlob(columnIndex: number): Uint8Array getBlob(columnIndex: number): Uint8Array
以字节数组的形式获取当前行中指定列的值。 以字节数组的形式获取当前行中指定列的值。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getBlob](#getblob9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -873,16 +301,12 @@ getBlob(columnIndex: number): Uint8Array ...@@ -873,16 +301,12 @@ getBlob(columnIndex: number): Uint8Array
const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES"));
``` ```
### getString<sup>(deprecated)</sup> ### getString
getString(columnIndex: number): string getString(columnIndex: number): string
以字符串形式获取当前行中指定列的值。 以字符串形式获取当前行中指定列的值。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getString](#getstring9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -903,16 +327,12 @@ getString(columnIndex: number): string ...@@ -903,16 +327,12 @@ getString(columnIndex: number): string
const name = resultSet.getString(resultSet.getColumnIndex("NAME")); const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
``` ```
### getLong<sup>(deprecated)</sup> ### getLong
getLong(columnIndex: number): number getLong(columnIndex: number): number
以Long形式获取当前行中指定列的值。 以Long形式获取当前行中指定列的值。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getLong](#getlong9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -933,16 +353,12 @@ getLong(columnIndex: number): number ...@@ -933,16 +353,12 @@ getLong(columnIndex: number): number
const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
``` ```
### getDouble<sup>(deprecated)</sup> ### getDouble
getDouble(columnIndex: number): number getDouble(columnIndex: number): number
以double形式获取当前行中指定列的值。 以double形式获取当前行中指定列的值。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[getDouble](#getdouble9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -963,16 +379,12 @@ getDouble(columnIndex: number): number ...@@ -963,16 +379,12 @@ getDouble(columnIndex: number): number
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
``` ```
### isColumnNull<sup>(deprecated)</sup> ### isColumnNull
isColumnNull(columnIndex: number): boolean isColumnNull(columnIndex: number): boolean
检查当前行中指定列的值是否为null。 检查当前行中指定列的值是否为null。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[isColumnNull](#iscolumnnull9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**参数:** **参数:**
...@@ -993,16 +405,12 @@ isColumnNull(columnIndex: number): boolean ...@@ -993,16 +405,12 @@ isColumnNull(columnIndex: number): boolean
const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES"));
``` ```
### close<sup>(deprecated)</sup> ### close
close(): void close(): void
关闭结果集。 关闭结果集。
> **说明:**
>
> 从 API Version 7 开始支持,从 API Version 9 开始废弃,建议使用[close](#close9)替代。
**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core **系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core
**示例:** **示例:**
......
# FormExtensionContext # FormExtensionContext
FormExtensionContext模块是FormExtension的上下文环境,继承自ExtensionContext。 FormExtensionContext模块是FormExtensionAbility的上下文环境,继承自ExtensionContext。
FormExtensionContext模块提供FormExtension具有的接口和能力。 FormExtensionContext模块提供FormExtensionAbility具有的接口和能力。
> **说明:** > **说明:**
> >
...@@ -11,23 +11,24 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。 ...@@ -11,23 +11,24 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。
## 使用说明 ## 使用说明
在使用FormExtensionContext的功能前,需要通过FormExtension获取。 在使用FormExtensionContext的功能前,需要通过FormExtensionAbility获取。
```ts ```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'; import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility { export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm() { onAddForm(want) {
let formContext = this.context; // 获取FormExtensionContext let formContext = this.context; // 获取FormExtensionContext
// ... // ...
let dataObj1 = { let dataObj1 = {
temperature:"11c", temperature: "11c",
"time":"11:00" "time": "11:00"
}; };
let obj1 = formBindingData.createFormBindingData(dataObj1); let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1; return obj1;
} }
} };
``` ```
## startAbility ## startAbility
...@@ -50,23 +51,29 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void ...@@ -50,23 +51,29 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
```ts ```ts
var want = { import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
deviceId: "",
bundleName: "com.example.formstartability", export default class MyFormExtensionAbility extends FormExtensionAbility {
abilityName: "MainAbility", onFormEvent(formId, message) {
action: "action1", // 当触发卡片message事件时,执行startAbility
entities: ["entity1"], console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
type: "MIMETYPE", let want = {
uri: "key={true,true,false}", deviceId: "",
parameters: {} bundleName: "com.example.formstartability",
} abilityName: "MainAbility",
this.context.startAbility(want, (error, data) => { parameters: {
if (error) { "message": message
console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); }
} else { };
console.log(`FormExtensionContext startAbility success`); this.context.startAbility(want, (error, data) => {
} if (error) {
}) console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error));
} else {
console.log('FormExtensionContext startAbility success');
}
});
}
};
``` ```
## startAbility ## startAbility
...@@ -89,24 +96,30 @@ startAbility(want: Want): Promise&lt;void&gt; ...@@ -89,24 +96,30 @@ startAbility(want: Want): Promise&lt;void&gt;
| 类型 | 说明 | | 类型 | 说明 |
| ------------ | ---------------------------------- | | ------------ | ---------------------------------- |
| Promise&lt;void&lt; | 无返回结果的Promise对象。 | | Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:** **示例:**
```ts ```ts
var want = { import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
deviceId: "",
bundleName: "com.example.formstartability", export default class MyFormExtensionAbility extends FormExtensionAbility {
abilityName: "MainAbility", onFormEvent(formId, message) {
action: "action1", // 当触发卡片message事件时,执行startAbility
entities: ["entity1"], console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
type: "MIMETYPE", let want = {
uri: "key={true,true,false}", deviceId: "",
parameters: {} bundleName: "com.example.formstartability",
} abilityName: "MainAbility",
this.context.startAbility(want).then(() => { parameters: {
console.info("StartAbility Success"); "message": message
}).catch((error) => { }
console.info("StartAbility failed"); };
}); this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
console.info("StartAbility failed");
});
}
};
``` ```
\ No newline at end of file
...@@ -70,7 +70,7 @@ Not found. ...@@ -70,7 +70,7 @@ Not found.
**可能原因** **可能原因**
在调用删除数据库、数据查询、数据删除等接口时未找到相关数据,可能原因如下。 在调用删除数据库、数据查询、数据同步等接口时未找到相关数据,可能原因如下。
1. 删除数据库操作时,数据库不存在或已删除。 1. 删除数据库操作时,数据库不存在或已删除。
2. 数据库数据查询操作时,相关数据不存在或已删除。 2. 数据库数据查询操作时,相关数据不存在或已删除。
3. 数据库数据同步操作时,数据库不存在或已删除。 3. 数据库数据同步操作时,数据库不存在或已删除。
......
...@@ -18,6 +18,8 @@ ...@@ -18,6 +18,8 @@
进行权限校验的开发步骤为: 进行权限校验的开发步骤为:
1. 获取调用者的身份标识:tokenId。 1. 获取调用者的身份标识:tokenId。
> **说明:**<br>
> 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。
2. 待校验的权限名:ohos.permission.PERMISSION。 2. 待校验的权限名:ohos.permission.PERMISSION。
3. 使用verifyAccessToken接口对当前调用者进行权限校验。 3. 使用verifyAccessToken接口对当前调用者进行权限校验。
4. 根据权限校验结果采取对应的措施。 4. 根据权限校验结果采取对应的措施。
...@@ -42,5 +44,3 @@ ...@@ -42,5 +44,3 @@
} }
``` ```
> **说明:**
> 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。
\ No newline at end of file
# 媒体子系统 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<CameraManager>): void;<br/>function getCameraManager(context: Context): Promise<CameraManager>; | 是 | 废弃 |
| ohos.multimedia.camera | CameraErrorCode | INVALID_ARGUMENT = 7400101,<br/>OPERATION_NOT_ALLOWED = 7400102,<br/>SESSION_NOT_CONFIG = 7400103,<br/>SESSION_NOT_RUNNING = 7400104,<br/>SESSION_CONFIG_LOCKED = 7400105,<br/>DEVICE_SETTING_LOCKED = 7400106,<br/>CONFILICT_CAMERA = 7400107,<br/>DEVICE_DISABLED = 7400108,<br/>SERVICE_FATAL_ERROR = 7400201 | 是 | 新增 |
| ohos.multimedia.camera | CameraManager | getSupportedCameras(): Array<CameraDevice>;<br/>getSupportedOutputCapability(camera: CameraDevice): CameraOutputCapability;<br/>createCameraInput(camera: CameraDevice): CameraInput;<br/>createCameraInput(position: CameraPosition, type: CameraType): CameraInput;<br/>createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput;<br/>createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput;<br/>createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput;<br/>createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): MetadataOutput;<br/>createCaptureSession(): CaptureSession; | 是 | 新增 |
| ohos.multimedia.camera | CameraManager | getSupportedCameras(callback: AsyncCallback<Array<CameraDevice>>): void;<br/>getSupportedCameras(): Promise<Array<CameraDevice>>;<br/>getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback<CameraOutputCapability>): void;<br/>getSupportedOutputCapability(camera: CameraDevice): Promise<CameraOutputCapability>;<br/>createCameraInput(camera: CameraDevice, callback: AsyncCallback<CameraInput>): void;<br/>createCameraInput(camera: CameraDevice): Promise<CameraInput>;<br/>createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback<CameraInput>): void;<br/>createCameraInput(position: CameraPosition, type: CameraType): Promise<CameraInput>;<br/>createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PreviewOutput>): void;<br/>createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput>;<br/>createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback<PhotoOutput>): void;<br/>createPhotoOutput(profile: Profile, surfaceId: string): Promise<PhotoOutput>;<br/>createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback<VideoOutput>): void;<br/>createVideoOutput(profile: VideoProfile, surfaceId: string): Promise<VideoOutput>;<br/>createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>, callback: AsyncCallback<MetadataOutput>): void;<br/>createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): Promise<MetadataOutput>;<br/>createCaptureSession(callback: AsyncCallback<CaptureSession>): void;<br/>createCaptureSession(): Promise<CaptureSession>; | 是 | 废弃 |
| 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<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | CameraInput | release(callback: AsyncCallback<void>): void;<br/>release(): Promise<void>;<br/>on(type: 'error', camera: CameraDevice, callback: ErrorCallback<CameraInputError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | CameraInputErrorCode | ERROR_UNKNOWN = -1<br/>ERROR_NO_PERMISSION = 0<br/>ERROR_DEVICE_PREEMPTED = 1<br/>ERROR_DEVICE_DISCONNECTED = 2<br/>ERROR_DEVICE_IN_USE = 3<br/>ERROR_DRIVER_ERROR = 4 | 是 | 废弃 |
| ohos.multimedia.camera | CameraInputError | code: CameraInputErrorCode | 是 | 废弃 |
| ohos.multimedia.camera | CaptureSession | beginConfig(): void;<br/>addInput(cameraInput: CameraInput): void;<br/>removeInput(cameraInput: CameraInput): void;<br/>addOutput(cameraOutput: CameraOutput): void;<br/>removeOutput(cameraOutput: CameraOutput): void;<br/>hasFlash(): boolean;<br/>isFlashModeSupported(flashMode: FlashMode): boolean;<br/>getFlashMode(): FlashMode;<br/>setFlashMode(flashMode: FlashMode): void;<br/>isExposureModeSupported(aeMode: ExposureMode): boolean;<br/>getExposureMode(): ExposureMode;<br/>setExposureMode(aeMode: ExposureMode): void;<br/>getMeteringPoint(): Point;<br/>setMeteringPoint(point: Point): void;<br/>getExposureBiasRange(): Array<number>;<br/>setExposureBias(exposureBias: number): void;<br/>getExposureValue(): number;<br/>isFocusModeSupported(afMode: FocusMode): boolean;<br/>getFocusMode(): FocusMode;<br/>setFocusMode(afMode: FocusMode): void;<br/>setFocusPoint(point: Point): void;<br/>getFocusPoint(): Point;<br/>getFocalLength(): number;<br/>getZoomRatioRange(): Array<number>;<br/>getZoomRatio(): number;<br/>setZoomRatio(zoomRatio: number): void;<br/>isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean;<br/>getActiveVideoStabilizationMode(): VideoStabilizationMode;<br/>setVideoStabilizationMode(mode: VideoStabilizationMode): void;<br/>on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | CaptureSession | beginConfig(callback: AsyncCallback<void>): void;<br/>beginConfig(): Promise<void>;<br/>addInput(cameraInput: CameraInput, callback: AsyncCallback<void>): void;<br/>addInput(cameraInput: CameraInput): Promise<void>;<br/>removeInput(cameraInput: CameraInput, callback: AsyncCallback<void>): void;<br/>removeInput(cameraInput: CameraInput): Promise<void>;<br/>addOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>addOutput(cameraOutput: CameraOutput): Promise<void>;<br/>removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void;<br/>removeOutput(cameraOutput: CameraOutput): Promise<void>;<br/>hasFlash(callback: AsyncCallback<boolean>): void;<br/>hasFlash(): Promise<boolean>;<br/>isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean>): void;<br/>isFlashModeSupported(flashMode: FlashMode): Promise<boolean>;<br/>getFlashMode(callback: AsyncCallback<FlashMode>): void;<br/>getFlashMode(): Promise<FlashMode>;<br/>setFlashMode(flashMode: FlashMode, callback: AsyncCallback<void>): void;<br/>setFlashMode(flashMode: FlashMode): Promise<void>;<br/>isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean>): void;<br/>isExposureModeSupported(aeMode: ExposureMode): Promise<boolean>;<br/>getExposureMode(callback: AsyncCallback<ExposureMode>): void;<br/>getExposureMode(): Promise<ExposureMode>;<br/>setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void>): void;<br/>setExposureMode(aeMode: ExposureMode): Promise<void>;<br/>getMeteringPoint(callback: AsyncCallback<Point>): void;<br/>getMeteringPoint(): Promise<Point>;<br/>setMeteringPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setMeteringPoint(point: Point): Promise<void>;<br/>getExposureBiasRange(callback: AsyncCallback<Array<number>>): void;<br/>getExposureBiasRange(): Promise<Array<number>>;<br/>setExposureBias(exposureBias: number, callback: AsyncCallback<void>): void;<br/>setExposureBias(exposureBias: number): Promise<void>;<br/>getExposureValue(callback: AsyncCallback<number>): void;<br/>getExposureValue(): Promise<number>;<br/>isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void;<br/>isFocusModeSupported(afMode: FocusMode): Promise<boolean>;<br/>getFocusMode(callback: AsyncCallback<FocusMode>): void;<br/>getFocusMode(): Promise<FocusMode>;<br/>setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void;<br/>setFocusMode(afMode: FocusMode): Promise<void>;<br/>setFocusPoint(point: Point, callback: AsyncCallback<void>): void;<br/>setFocusPoint(point: Point): Promise<void>;<br/>getFocusPoint(callback: AsyncCallback<Point>): void;<br/>getFocusPoint(): Promise<Point>;<br/>getFocalLength(callback: AsyncCallback<number>): void;<br/>getFocalLength(): Promise<number>;<br/>getZoomRatioRange(callback: AsyncCallback<Array<number>>): void;<br/>getZoomRatioRange(): Promise<Array<number>>;<br/>getZoomRatio(callback: AsyncCallback<number>): void;<br/>getZoomRatio(): Promise<number>;<br/>setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void;<br/>setZoomRatio(zoomRatio: number): Promise<void>;<br/>isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback<boolean>): void;<br/>isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise<boolean>;<br/>getActiveVideoStabilizationMode(callback: AsyncCallback<VideoStabilizationMode>): void;<br/>getActiveVideoStabilizationMode(): Promise<VideoStabilizationMode>;<br/>setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback<void>): void;<br/>setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void>;<br/>on(type: 'error', callback: ErrorCallback<CaptureSessionError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | CaptureSessionErrorCode | ERROR_UNKNOWN = -1<br/>ERROR_INSUFFICIENT_RESOURCES = 0<br/>ERROR_TIMEOUT = 1 | 是 | 废弃 |
| ohos.multimedia.camera | CaptureSessionError | code: CaptureSessionErrorCode | 是 | 废弃 |
| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | PreviewOutput | on(type: 'error', callback: ErrorCallback<PreviewOutputError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | PreviewOutputErrorCode | ERROR_UNKNOWN = -1 | 是 | 废弃 |
| ohos.multimedia.camera | PreviewOutputError | code: PreviewOutputErrorCode | 是 | 废弃 |
| ohos.multimedia.camera | PhotoOutput | capture(): Promise<void>;<br/>isMirrorSupported(): boolean;<br/>on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | PhotoOutput | isMirrorSupported(callback: AsyncCallback<boolean>): void;<br/>isMirrorSupported(): Promise<boolean>;<br/>on(type: 'error', callback: ErrorCallback<PhotoOutputError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | PhotoOutputErrorCode | ERROR_UNKNOWN = -1<br/>ERROR_DRIVER_ERROR = 0<br/>ERROR_INSUFFICIENT_RESOURCES = 1<br/>ERROR_TIMEOUT = 2 | 是 | 废弃 |
| ohos.multimedia.camera | PhotoOutputError | code: PhotoOutputErrorCode | 是 | 废弃 |
| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | VideoOutput | on(type: 'error', callback: ErrorCallback<VideoOutputError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | VideoOutputErrorCode | ERROR_UNKNOWN = -1<br/>ERROR_DRIVER_ERROR = 0 | 是 | 废弃 |
| ohos.multimedia.camera | VideoOutputError | code: VideoOutputErrorCode | 是 | 废弃 |
| ohos.multimedia.camera | MetadataObject | readonly type: MetadataObjectType;<br/>readonly timestamp: number; | 是 | 新增 |
| ohos.multimedia.camera | MetadataObject | getType(callback: AsyncCallback<MetadataObjectType>): void;<br/>getType(): Promise<MetadataObjectType>;<br/>getTimestamp(callback: AsyncCallback<number>): void;<br/>getTimestamp(): Promise<number>;<br/>getBoundingBox(callback: AsyncCallback<Rect>): void;<br/>getBoundingBox(): Promise<Rect>; | 是 | 废弃 |
| ohos.multimedia.camera | MetadataFaceObject | readonly boundingBox: Rect | 是 | 新增 |
| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 新增 |
| ohos.multimedia.camera | MetadataOutput | on(type: 'error', callback: ErrorCallback<BusinessError>): void; | 是 | 废弃 |
| ohos.multimedia.camera | MetadataOutputErrorCode | ERROR_UNKNOWN = -1<br/>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<void>;
3. MetadataObject 接口中新增 readonly type: MetadataObjectType;
4. MetadataObject 接口中新增 readonly timestamp: number;
5. MetadataObject 接口中新增 readonly boundingBox: Rect;
**废弃接口**
1. CameraInput 中废弃接口 release(callback: AsyncCallback<void>): void; 以及 release(): Promise<void>;
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<MetadataObjectType>): void;
13. 废弃接口 MetadataObject 中 getType(): Promise<MetadataObjectType>;
14. 废弃接口 MetadataObject 中 getTimestamp(callback: AsyncCallback<number>): void;
15. 废弃接口 MetadataObject 中 getTimestamp(): Promise<number>;
16. 废弃接口 MetadataObject 中 getBoundingBox(callback: AsyncCallback<Rect>): void;
17. 废弃接口 MetadataObject 中 getBoundingBox(): Promise<Rect>;
18. 废弃枚举 MetadataOutputErrorCode 以及所有它里边的枚举值(ERROR_UNKNOWN = -1,ERROR_INSUFFICIENT_RESOURCES = 0);
19. 废弃接口 MetadataOutputError 以及接口属性 code:MetadataOutputErrorCode;
**接口变更**
1. camera 模块中接口 getCameraManager 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getCameraManager(context: Context, callback: AsyncCallback<CameraManager>): void; 以及 getCameraManager(context: Context): Promise<CameraManager>; 变更为 getCameraManager(context: Context): CameraManager;
参考代码如下:
```
let cameraManager = camera.getCameraManager(context);
```
2. CameraManager 中接口 getSupportedCameras 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getSupportedCameras(callback: AsyncCallback<Array<CameraDevice>>): void; 以及 getSupportedCameras(): Promise<Array<CameraDevice>>; 变更为 getSupportedCameras(): Array<CameraDevice>;
参考代码如下:
```
let cameras = cameraManager.getSupportedCameras();
```
3. CameraManager 中接口 getSupportedOutputCapability 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getSupportedOutputCapability(camera: CameraDevice, callback: AsyncCallback<CameraOutputCapability>): void; 以及 getSupportedOutputCapability(camera: CameraDevice): Promise<CameraOutputCapability>; 变更为 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<CameraInput>): void; 以及 createCameraInput(camera: CameraDevice): Promise<CameraInput>; 变更为 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<CameraInput>): void; 以及 createCameraInput(position: CameraPosition, type: CameraType): Promise<CameraInput>; 变更为 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<PreviewOutput>): void; 以及 createPreviewOutput(profile: Profile, surfaceId: string): Promise<PreviewOutput>; 变更为 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<PhotoOutput>): void; 以及 createPhotoOutput(profile: Profile, surfaceId: string): Promise<PhotoOutput>; 变更为 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<VideoOutput>): void; 以及 createVideoOutput(profile: VideoProfile, surfaceId: string): Promise<VideoOutput>; 变更为 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<MetadataObjectType>, callback: AsyncCallback<MetadataOutput>): void; 以及 createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): Promise<MetadataOutput>; 变更为 createMetadataOutput(metadataObjectTypes: Array<MetadataObjectType>): MetadataOutput;
参考代码如下:
```
let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
let metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes);
```
10. CameraManager 中接口 createCaptureSession 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 createCaptureSession(callback: AsyncCallback<CaptureSession>): void; 以及 createCaptureSession(): Promise<CaptureSession>; 变更为 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<CameraInputError>): void; 变更为 on(type: 'error', camera: CameraDevice, callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
let cameraDevice = cameras[0];
cameraInput.on('error', cameraDevice, (BusinessError) => {
})
```
13. CaptureSession 中接口 beginConfig 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 beginConfig(callback: AsyncCallback<void>): void; 以及 beginConfig(): Promise<void>; 变更为 beginConfig(): void;
参考代码如下:
```
captureSession.beginConfig();
```
14. CaptureSession 中接口 addInput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 addInput(cameraInput: CameraInput, callback: AsyncCallback<void>): void; 以及 addInput(cameraInput: CameraInput): Promise<void>; 变更为 addInput(cameraInput: CameraInput): void;
参考代码如下:
```
captureSession.addInput(cameraInput);
```
15. CaptureSession 中接口 removeInput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 removeInput(cameraInput: CameraInput, callback: AsyncCallback<void>): void; 以及 removeInput(cameraInput: CameraInput): Promise<void>; 变更为 removeInput(cameraInput: CameraInput): void;
参考代码如下:
```
captureSession.removeInput(cameraInput);
```
16. CaptureSession 中接口 addOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 addOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void; 以及 addOutput(cameraOutput: CameraOutput): Promise<void>; 变更为 addOutput(cameraOutput: CameraOutput): void;
参考代码如下:
```
captureSession.addOutput(previewOutput);
```
17. CaptureSession 中接口 removeOutput 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 removeOutput(cameraOutput: CameraOutput, callback: AsyncCallback<void>): void; 以及 removeOutput(cameraOutput: CameraOutput): Promise<void>; 变更为 removeOutput(cameraOutput: CameraOutput): void;
参考代码如下:
```
captureSession.removeOutput(previewOutput);
```
18. CaptureSession 中接口 hasFlash 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 hasFlash(callback: AsyncCallback<boolean>): void; 以及 hasFlash(): Promise<boolean>; 变更为 hasFlash(): boolean;
参考代码如下:
```
let status = captureSession.hasFlash();
```
19. CaptureSession 中接口 isFlashModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback<boolean>): void; 以及 isFlashModeSupported(flashMode: FlashMode): Promise<boolean>; 变更为 isFlashModeSupported(flashMode: FlashMode): boolean;
参考代码如下:
```
let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
```
20. CaptureSession 中接口 getFlashMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFlashMode(callback: AsyncCallback<FlashMode>): void; 以及 getFlashMode(): Promise<FlashMode>; 变更为 getFlashMode(): FlashMode;
参考代码如下:
```
let flashMode = captureSession.getFlashMode();
```
21. CaptureSession 中接口 isExposureModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback<boolean>): void; 以及 isExposureModeSupported(aeMode: ExposureMode): Promise<boolean>; 变更为 isExposureModeSupported(aeMode: ExposureMode): boolean;
参考代码如下:
```
let isSupported = captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
```
22. CaptureSession 中接口 getExposureMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureMode(callback: AsyncCallback<ExposureMode>): void; 以及 getExposureMode(): Promise<ExposureMode>; 变更为 getExposureMode(): ExposureMode;
参考代码如下:
```
let exposureMode = captureSession.getExposureMode();
```
23. CaptureSession 中接口 setExposureMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setExposureMode(aeMode: ExposureMode, callback: AsyncCallback<void>): void; 以及 setExposureMode(aeMode: ExposureMode): Promise<void>; 变更为 setExposureMode(aeMode: ExposureMode): void;
参考代码如下:
```
captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
```
24. CaptureSession 中接口 getMeteringPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getMeteringPoint(callback: AsyncCallback<Point>): void; 以及 getMeteringPoint(): Promise<Point>; 变更为 getMeteringPoint(): Point;
参考代码如下:
```
let exposurePoint = captureSession.getMeteringPoint();
```
25. CaptureSession 中接口 setMeteringPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setMeteringPoint(point: Point, callback: AsyncCallback<void>): void; 以及 setMeteringPoint(point: Point): Promise<void>; 变更为 setMeteringPoint(point: Point): void;
参考代码如下:
```
let Point2 = {x: 2, y: 2};
captureSession.setMeteringPoint(Point2);
```
26. CaptureSession 中接口 getExposureBiasRange 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureBiasRange(callback: AsyncCallback<Array<number>>): void; 以及 getExposureBiasRange(): Promise<Array<number>>; 变更为 getExposureBiasRange(): Array<number>;
参考代码如下:
```
let biasRangeArray = captureSession.getExposureBiasRange();
```
27. CaptureSession 中接口 setExposureBias 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setExposureBias(exposureBias: number, callback: AsyncCallback<void>): void; 以及 setExposureBias(exposureBias: number): Promise<void>; 变更为 setExposureBias(exposureBias: number): void;
参考代码如下:
```
let exposureBias = biasRangeArray[0];
captureSession.setExposureBias(exposureBias);
```
28. CaptureSession 中接口 getExposureValue 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getExposureValue(callback: AsyncCallback<number>): void; 以及 getExposureValue(): Promise<number>; 变更为 getExposureValue(): number;
参考代码如下:
```
let exposureValue = captureSession.getExposureValue();
```
29. CaptureSession 中接口 isFocusModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback<boolean>): void; 以及 isFocusModeSupported(afMode: FocusMode): Promise<boolean>; 变更为 isFocusModeSupported(afMode: FocusMode): boolean;
参考代码如下:
```
let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO);
```
30. CaptureSession 中接口 getFocusMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocusMode(callback: AsyncCallback<FocusMode>): void; 以及 getFocusMode(): Promise<FocusMode>; 变更为 getFocusMode(): FocusMode;
参考代码如下:
```
let afMode = captureSession.getFocusMode();
```
31. CaptureSession 中接口 setFocusMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setFocusMode(afMode: FocusMode, callback: AsyncCallback<void>): void; 以及 setFocusMode(afMode: FocusMode): Promise<void>; 变更为 setFocusMode(afMode: FocusMode): void;
参考代码如下:
```
captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO);
```
32. CaptureSession 中接口 setFocusPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setFocusPoint(point: Point, callback: AsyncCallback<void>): void; 以及 setFocusPoint(point: Point): Promise<void>; 变更为 setFocusPoint(point: Point): void;
参考代码如下:
```
let Point2 = {x: 2, y: 2};
captureSession.setFocusPoint(Point2);
```
33. CaptureSession 中接口 getFocusPoint 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocusPoint(callback: AsyncCallback<Point>): void; 以及 getFocusPoint(): Promise<Point>; 变更为 getFocusPoint(): Point;
参考代码如下:
```
let point = captureSession.getFocusPoint();
```
34. CaptureSession 中接口 getFocalLength 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getFocalLength(callback: AsyncCallback<number>): void; 以及 getFocalLength(): Promise<number>; 变更为 getFocalLength(): number;
参考代码如下:
```
let focalLength = captureSession.getFocalLength();
```
35. CaptureSession 中接口 getZoomRatioRange 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getZoomRatioRange(callback: AsyncCallback<Array<number>>): void; 以及 getZoomRatioRange(): Promise<Array<number>>; 变更为 getZoomRatioRange(): Array<number>;
参考代码如下:
```
let zoomRatioRange = captureSession.getZoomRatioRange();
```
36. CaptureSession 中接口 getZoomRatio 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getZoomRatio(callback: AsyncCallback<number>): void; 以及 getZoomRatio(): Promise<number>; 变更为 getZoomRatio(): number;
参考代码如下:
```
let zoomRatio = captureSession.getZoomRatio();
```
37. CaptureSession 中接口 setZoomRatio 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setZoomRatio(zoomRatio: number, callback: AsyncCallback<void>): void; 以及 setZoomRatio(zoomRatio: number): Promise<void>; 变更为 setZoomRatio(zoomRatio: number): void;
参考代码如下:
```
let zoomRatio = zoomRatioRange[0];
captureSession.setZoomRatio(zoomRatio);
```
38. CaptureSession 中接口 isVideoStabilizationModeSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback<boolean>): void; 以及 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise<boolean>; 变更为 isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean;
参考代码如下:
```
let isSupported = captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF);
```
39. CaptureSession 中接口 getActiveVideoStabilizationMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 getActiveVideoStabilizationMode(callback: AsyncCallback<VideoStabilizationMode>): void; 以及 getActiveVideoStabilizationMode(): Promise<VideoStabilizationMode>; 变更为 getActiveVideoStabilizationMode(): VideoStabilizationMode;
参考代码如下:
```
let vsMode = captureSession.getActiveVideoStabilizationMode();
```
40. CaptureSession 中接口 setVideoStabilizationMode 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback<void>): void; 以及 setVideoStabilizationMode(mode: VideoStabilizationMode): Promise<void>; 变更为 setVideoStabilizationMode(mode: VideoStabilizationMode): void;
参考代码如下:
```
captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF);
```
41. CaptureSession 中,on(type: 'error') callback 类型由 ErrorCallback<CaptureSessionError> 变更为 ErrorCallback<BusinessError>,因此旧接口 on(type: 'error', callback: ErrorCallback<CaptureSessionError>): void; 变更为 on(type: 'error', callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
captureSession.on('error', (BusinessError) => {
})
```
42. PreviewOutput 中,on(type: 'error') callback 类型由 ErrorCallback<PreviewOutputError> 变更为 ErrorCallback<BusinessError>,因此旧接口 on(type: 'error', callback: ErrorCallback<PreviewOutputError>): void; 变更为 on(type: 'error', callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
previewOutput.on('error', (BusinessError) => {
})
```
43. PhotoOutput 中接口 isMirrorSupported 返回方式由异步 callback 跟异步 promise 变更为同步返回,因此旧接口 isMirrorSupported(callback: AsyncCallback<boolean>): void; 以及 isMirrorSupported(): Promise<boolean>; 变更为 isMirrorSupported(): boolean;
参考代码如下:
```
let isSupported = photoOutput.isMirrorSupported();
```
44. PhotoOutput 中,on(type: 'error') callback 类型由 ErrorCallback<PhotoOutputError> 变更为 ErrorCallback<BusinessError>,因此旧接口 on(type: 'error', callback: ErrorCallback<PhotoOutputError>): void; 变更为 on(type: 'error', callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
PhotoOutput.on('error', (BusinessError) => {
})
```
45. VideoOutput 中,on(type: 'error') callback 类型由 ErrorCallback<VideoOutputError> 变更为 ErrorCallback<BusinessError>,因此旧接口 on(type: 'error', callback: ErrorCallback<VideoOutputError>): void; 变更为 on(type: 'error', callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
VideoOutput.on('error', (BusinessError) => {
})
```
46. MetadataOutput 中,on(type: 'error') callback 类型由 ErrorCallback<MetadataOutputError> 变更为 ErrorCallback<BusinessError>,因此旧接口 on(type: 'error', callback: ErrorCallback<MetadataOutputError>): void; 变更为 on(type: 'error', callback: ErrorCallback<BusinessError>): void;
参考代码如下:
```
MetadataOutput.on('error', (BusinessError) => {
})
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册