提交 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
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. |
| saveAppState(): boolean; | Saves the ability status of an application. |
| restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.|
......
......@@ -6,7 +6,7 @@ Applicable to: OpenHarmony SDK 3.2.5.5
1. Locate the crash-related code based on the service log.
2. View the error information in the crash file. The crash file is located at **/data/log/faultlog/faultlogger/**.
2. View the error information in the crash file, which is located at **/data/log/faultlog/faultlogger/**.
## Why cannot access controls in the UiTest test framework?
......
......@@ -51,9 +51,9 @@ build() {
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
1. Obtain data in Uint8Array format by calling the **RawFile** API of **resourceManager**.
1. Obtain Uint8Array data by calling the **RawFile** API of **resourceManager**.
2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API.
2. Convert the Uint8Array data to strings by calling the **String.fromCharCode** API.
Reference: [Resource Manager](../reference/apis/js-apis-resource-manager.md)
......
......@@ -19,112 +19,121 @@ const color = new ArrayBuffer(96); // Create a buffer to store image pixel data.
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data.
// Create a PixelMap object.
const color = new ArrayBuffer(96);
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
console.log('Succeeded in creating pixelmap.');
})
// Read pixels.
const area = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
pixelmap.readPixels(area,() => {
var bufferArr = new Uint8Array(area.pixels);
var res = true;
for (var i = 0; i < bufferArr.length; i++) {
console.info(' buffer ' + bufferArr[i]);
if(res) {
if(bufferArr[i] == 0) {
res = false;
console.log('readPixels end.');
break;
}
}
// Failed to create the PixelMap object.
if (err) {
console.info('create pixelmap failed, err' + err);
return
}
})
// Store pixels.
const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer);
var res = true;
for (var i = 0; i < bufferArr.length; i++) {
if(res) {
if (bufferArr[i] !== 0) {
res = false;
console.log('readPixelsToBuffer end.');
break;
}
}
// Read pixels.
const area = {
pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
})
// Write pixels.
pixelmap.writePixels(area,() => {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}
pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels);
var res = true;
for (var i = 0; i < readArr.length; i++) {
pixelmap.readPixels(area,() => {
let bufferArr = new Uint8Array(area.pixels);
let res = true;
for (let i = 0; i < bufferArr.length; i++) {
console.info(' buffer ' + bufferArr[i]);
if(res) {
if (readArr[i] !== 0) {
if(bufferArr[i] == 0) {
res = false;
console.log('readPixels end.please check buffer');
console.log('readPixels end.');
break;
}
}
}
})
})
// Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => {
// Store pixels.
const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => {
var bufferArr = new Uint8Array(readBuffer);
var res = true;
for (var i = 0; i < bufferArr.length; i++) {
pixelmap.readPixelsToBuffer(readBuffer,() => {
let bufferArr = new Uint8Array(readBuffer);
let res = true;
for (let i = 0; i < bufferArr.length; i++) {
if(res) {
if (bufferArr[i] !== i) {
if (bufferArr[i] !== 0) {
res = false;
console.log('readPixels end.please check buffer');
console.log('readPixelsToBuffer end.');
break;
}
}
}
})
})
// Write pixels.
pixelmap.writePixels(area,() => {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}
pixelmap.readPixels(readArea,() => {
let readArr = new Uint8Array(readArea.pixels);
let res = true;
for (let i = 0; i < readArr.length; i++) {
if(res) {
if (readArr[i] !== 0) {
res = false;
console.log('readPixels end.please check buffer');
break;
}
}
}
})
})
// Obtain image information.
pixelmap.getImageInfo((error, imageInfo) => {
if (imageInfo !== null) {
console.log('Succeeded in getting imageInfo');
}
})
const writeColor = new ArrayBuffer(96); // Pixel data of the image.
// Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => {
let bufferArr = new Uint8Array(readBuffer);
let res = true;
for (let i = 0; i < bufferArr.length; i++) {
if(res) {
if (bufferArr[i] !== i) {
res = false;
console.log('readPixels end.please check buffer');
break;
}
}
}
})
})
// Release the PixelMap object.
pixelmap.release(()=>{
console.log('Succeeded in releasing pixelmap');
// Obtain image information.
pixelmap.getImageInfo((err, imageInfo) => {
// Failed to obtain the image information.
if (err || imageInfo == null) {
console.info('getImageInfo failed, err' + err);
return
}
if (imageInfo !== null) {
console.log('Succeeded in getting imageInfo');
}
})
// Release the PixelMap object.
pixelmap.release(()=>{
console.log('Succeeded in releasing pixelmap');
})
})
// Create an image source (uri).
let path = '/data/local/tmp/test.jpg';
const imageSourceApi = image.createImageSource(path);
const imageSourceApi1 = image.createImageSource(path);
// Create an image source (fd).
let fd = 29;
const imageSourceApi = image.createImageSource(fd);
const imageSourceApi2 = image.createImageSource(fd);
// Create an image source (data).
const data = new ArrayBuffer(96);
const imageSourceApi = image.createImageSource(data);
const imageSourceApi3 = image.createImageSource(data);
// Release the image source.
imageSourceApi.release(() => {
imageSourceApi3.release(() => {
console.log('Succeeded in releasing imagesource');
})
......@@ -133,6 +142,10 @@ const imagePackerApi = image.createImagePacker();
const imageSourceApi = image.createImageSource(0);
let packOpts = { format:"image/jpeg", quality:98 };
imagePackerApi.packing(imageSourceApi, packOpts, (err, data) => {
if (err) {
console.info('packing from imagePackerApi failed, err' + err);
return
}
console.log('Succeeded in packing');
})
......@@ -161,36 +174,33 @@ let decodingOptions = {
// Create a pixel map in callback mode.
imageSourceApi.createPixelMap(decodingOptions, (err, pixelmap) => {
// Failed to create the PixelMap object.
if (err) {
console.info('create pixelmap failed, err' + err);
return
}
console.log('Succeeded in creating pixelmap.');
})
// Create a pixel map in promise mode.
imageSourceApi.createPixelMap().then(pixelmap => {
console.log('Succeeded in creating pixelmap.');
})
// Capture error information when an exception occurs during function invoking.
catch(error => {
console.log('Failed in creating pixelmap.' + error);
})
// Obtain the number of bytes in each line of pixels.
var num = pixelmap.getBytesNumberPerRow();
// Obtain the number of bytes in each line of pixels.
let num = pixelmap.getBytesNumberPerRow();
// Obtain the total number of pixel bytes.
var pixelSize = pixelmap.getPixelBytesNumber();
// Obtain the total number of pixel bytes.
let pixelSize = pixelmap.getPixelBytesNumber();
// Obtain the pixel map information.
pixelmap.getImageInfo().then( imageInfo => {});
// Obtain the pixel map information.
pixelmap.getImageInfo().then( imageInfo => {});
// Release the PixelMap object.
pixelmap.release(()=>{
console.log('Succeeded in releasing pixelmap');
})
// Capture release failure information.
catch(error => {
console.log('Failed in releasing pixelmap.' + error);
// Release the PixelMap object.
pixelmap.release(()=>{
console.log('Succeeded in releasing pixelmap');
})
}).catch(error => {
console.log('Failed in creating pixelmap.' + error);
})
```
......@@ -216,7 +226,7 @@ if (imagePackerApi == null) {
}
// Set encoding parameters if the image packer is successfully created.
let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg.
let packOpts = { format:"image/jpeg", // The supported encoding format is jpg.
quality:98 } // Image quality, which ranges from 0 to 100.
// Encode the image.
......@@ -233,8 +243,9 @@ imageSourceApi.getImageInfo((err, imageInfo) => {
console.log('Succeeded in getting imageInfo');
})
const array = new ArrayBuffer(100); // Incremental data.
// Update incremental data.
imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error, data)=> {})
imageSourceApi.updateData(array, false, 0, 10,(error, data)=> {})
```
......@@ -246,10 +257,15 @@ Example scenario: The camera functions as the client to transmit image data to t
public async init(surfaceId: any) {
// (Server code) Create an ImageReceiver object.
var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1);
let receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1);
// Obtain the surface ID.
receiver.getReceivingSurfaceId((err, surfaceId) => {
// Failed to obtain the surface ID.
if (err) {
console.info('getReceivingSurfaceId failed, err' + err);
return
}
console.info("receiver getReceivingSurfaceId success");
});
// Register a surface listener, which is triggered after the buffer of the surface is ready.
......
......@@ -230,27 +230,27 @@ When referencing resources in the **rawfile** subdirectory, use the **"$rawfile(
>
> The return value of **$r** is a **Resource** object. You can obtain the corresponding string by using the [getStringValue](../reference/apis/js-apis-resource-manager.md) API.
In the **.ets** file, you can use the resources defined in the **resources** directory.
In the **.ets** file, you can use the resources defined in the **resources** directory. The following is a resource usage example based on the resource file examples in [Resource Group Sub-directories](#resource-group-subdirectories):
```ts
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Text($r('app.string.message_arrive', "five of the clock")) // Reference string resources. The second parameter of $r is used to replace %s.
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.plural.eat_apple', 5, 5)) // Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d.
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
// Reference string resources. The second parameter of $r is used to replace %s, and value is "We will arrive at five'o clock".
Text($r('app.string.message_arrive', "five'o clock"))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
// Reference plural resources. The first parameter indicates the plural resource, the second parameter indicates the number of plural resources, and the third parameter indicates the substitute of %d.
// The value is "5 apple" in singular form and "5 apples" in plural form.
Text($r('app.plural.eat_apple', 5, 5))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // Reference media resources.
......@@ -274,14 +274,20 @@ To reference a system resource, use the **"$r('sys.type.resource_id')"** format.
```ts
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2})
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')})
.height(200)
.width(300)
.border({
color: $r('sys.color.ohos_id_color_palette_aux1'),
radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2
})
.margin({
top: $r('sys.float.ohos_id_elements_margin_horizontal_m'),
bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')
})
.height(200)
.width(300)
```
......@@ -55,7 +55,7 @@ Initiates a call based on the specified options. This API uses an asynchronous c
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. |
| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure |
**Example**
......@@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the specified p
| Name | Type | Mandatory | Description |
| ----------- | -------------------------------------------------- | ---- | -------------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. |
| options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number options. |
| callback | AsyncCallback&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**
......@@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100.
| Name | Type | Mandatory | Description |
| ----------- | -------------------------------------------- | ---- | ------------------------------------ |
| phoneNumber | string | Yes | Phone number. |
| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. |
| options | [NumberFormatOptions](#numberformatoptions7) | No | Number formatting options, for example, country code. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. |
**Example**
......@@ -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>
answer\(callId: number, callback: AsyncCallback<void\>\): void
......@@ -658,7 +631,7 @@ promise.then(data => {
## 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.
......@@ -672,22 +645,23 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ---------- |
| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
```js
call.hangup((err, data) => {
call.hangup(1, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.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.
......@@ -699,13 +673,12 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------------------------------------- |
| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
```js
call.hangup(1, (err, data) => {
call.answer((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -746,11 +719,11 @@ promise.then(data => {
});
```
## call.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.
......@@ -767,38 +740,7 @@ This is a system API.
**Example**
```js
call.reject((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.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) => {
call.hangup((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(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>
holdCall\(callId: number, callback: AsyncCallback<void\>\): void
......@@ -1344,8 +1345,8 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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.|
| 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>- **0**: Call waiting is disabled.<br>- **1**: Call waiting is enabled.|
**Example**
......@@ -2399,7 +2400,7 @@ promise.then(data => {
});
```
## call.setAudioDevice<sup>8+</sup>
## call.setAudioDevice<sup>9+</sup>
setAudioDevice\(device: AudioDevice, callback: AsyncCallback<void\>\): void
......@@ -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
......
# Internationalization – I18N
This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The I18N module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402.
The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
> **NOTE**
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md).
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -247,9 +244,9 @@ This is a system API.
**Parameters**
| Name | Type | Description |
| -------- | ------ | ----- |
| language | string | Language ID.|
| Name | Type | Mandatory | Description |
| -------- | ------ | ----- | ----- |
| language | string | Yes | Language ID.|
**Error codes**
......@@ -313,9 +310,9 @@ This is a system API.
**Parameters**
| Name | Type | Description |
| ------ | ------ | ----- |
| region | string | Region ID.|
| Name | Type | Mandatory | Description |
| -------- | ------ | ----- | ----- |
| region | string | Yes | Region ID.|
**Error codes**
......@@ -379,9 +376,9 @@ This is a system API.
**Parameters**
| Name | Type | Description |
| ------ | ------ | --------------- |
| locale | string | System locale ID, for example, **zh-CN**.|
| Name | Type | Mandatory | Description |
| -------- | ------ | ----- | ----- |
| locale | string | Yes | System locale ID, for example, **zh-CN**.|
**Error codes**
......@@ -713,9 +710,9 @@ Checks whether the localized script for the specified language is displayed from
**Parameters**
| Name | Type | Description |
| ------ | ------ | ------- |
| locale | string | Locale ID.|
| Name | Type | Mandatory | Description |
| -------- | ------ | ----- | ----- |
| locale | string | Yes | Locale ID.|
**Return value**
......@@ -905,7 +902,7 @@ Sets the start day of a week for this **Calendar** object.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | --------------------- |
| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
| value | number | Yes | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
**Example**
```js
......@@ -947,7 +944,7 @@ Sets the minimum number of days in the first week of a year.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ------------ |
| value | number | No | Minimum number of days in the first week of a year.|
| value | number | Yes | Minimum number of days in the first week of a year.|
**Example**
```js
......
# 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.
......
......@@ -332,7 +332,6 @@ connection.getDefaultNet().then(function (netHandle) {
});
```
## connection.reportNetConnected
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
......@@ -490,7 +489,6 @@ connection.getAddressesByName(host).then(function (addresses) {
})
```
## connection.enableAirplaneMode
enableAirplaneMode(callback: AsyncCallback\<void>): void
......@@ -539,7 +537,6 @@ connection.enableAirplaneMode().then(function (error) {
})
```
## connection.disableAirplaneMode
disableAirplaneMode(callback: AsyncCallback\<void>): void
......@@ -588,7 +585,6 @@ connection.disableAirplaneMode().then(function (error) {
})
```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
......@@ -825,7 +821,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle**
| Name| Type | Description |
| ------ | ------ | ------------------------- |
| netId | number | Network ID. The value must be greater than or equal to 100.|
| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.|
### bindSocket
......@@ -847,33 +843,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
**Example**
```js
connection.getDefaultNet().then(function (netHandle) {
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
let socketType = "xxxx";
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({
address: "xxxx", port: xxxx, family: xxxx
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
netHandle.bindSocket(tcp, function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
if (err) {
console.log('bind fail');
}
netHandle.bindSocket(tcp, (error, data)=>{
if (error) {
console.log(JSON.stringify(error));
} else {
console.log(JSON.stringify(data));
}
})
})
} else {
let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
udp.bind({
address: "xxxx", port: xxxx, family: xxxx
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
console.log('bind fail');
}
udp.on('message', (data) => {
console.log(JSON.stringify(data))
});
netHandle.bindSocket(udp, function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
console.log(JSON.stringify(data))
});
netHandle.bindSocket(udp,(error, data)=>{
if (error) {
console.log(JSON.stringify(error));
} else {
console.log(JSON.stringify(data));
}
})
})
}
}
}
})
```
### bindSocket
......@@ -901,31 +914,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
**Example**
```js
connection.getDefaultNet().then(function (netHandle) {
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle)=>{
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
let socketType = "xxxx";
if(socketType == "TCPSocket") {
let socketType = "TCPSocket";
if (socketType == "TCPSocket") {
tcp.bind({
address: "xxxx", port: xxxx, family: xxxx
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
netHandle.bindSocket(tcp).then(err, data) {
console.log(JSON.stringify(data))
if (err) {
console.log('bind fail');
}
netHandle.bindSocket(tcp).then((err, data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
})
})
} else {
let callback = value => {
console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
udp.bind({
address: "xxxx", port: xxxx, family: xxxx
address: '192.168.xx.xxx', port: xxxx, family: 1
}, err => {
if (err) {
console.log('bind fail');
}
udp.on('message', (data) => {
console.log(JSON.stringify(data))
});
netHandle.bindSocket(tcp).then(err, data) {
console.log(JSON.stringify(data))
});
console.log(JSON.stringify(data));
})
netHandle.bindSocket(udp).then((err, data) => {
if (err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(data));
}
})
})
}
}
}
})
```
......
# Network Sharing Management
The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, and Bluetooth sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
>
......@@ -405,7 +405,7 @@ Obtains the names of NICs in the specified network sharing state. This API uses
**Example**
```js
import SharingIfaceState from '@ohos.net.sharing'
import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
......@@ -498,7 +498,7 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js
import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => {
sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => {
console.log(JSON.stringify(data));
}).catch(error => {
console.log(JSON.stringify(error));
......@@ -525,8 +525,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
**Example**
```js
import SharingIfaceState from '@ohos.net.sharing'
sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => {
import SharingIfaceType from '@ohos.net.sharing'
sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
......@@ -565,7 +565,7 @@ sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => {
});
```
## on('sharingStateChange')
## sharing.on('sharingStateChange')
on(type: 'sharingStateChange', callback: Callback\<boolean>): void
......@@ -591,7 +591,7 @@ sharing.on('sharingStateChange', (error, data) => {
});
```
## off('sharingStateChange')
## sharing.off('sharingStateChange')
off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
......@@ -617,7 +617,7 @@ sharing.off('sharingStateChange', (error, data) => {
});
```
## on('interfaceSharingStateChange')
## sharing.on('interfaceSharingStateChange')
on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void
......@@ -643,7 +643,7 @@ sharing.on('interfaceSharingStateChange', (error, data) => {
});
```
## off('interfaceSharingStateChange')
## sharing.off('interfaceSharingStateChange')
off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void
......@@ -669,7 +669,7 @@ sharing.off('interfaceSharingStateChange', (error, data) => {
});
```
## on('sharingUpstreamChange')
## sharing.on('sharingUpstreamChange')
on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
......@@ -695,7 +695,7 @@ sharing.on('sharingUpstreamChange', (error, data) => {
});
```
## off('sharingUpstreamChange')
## sharing.off('sharingUpstreamChange')
off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
......@@ -735,12 +735,12 @@ Enumerates the network sharing states of an NIC.
## SharingIfaceType
Enumerates the network sharing types of an NIC.
Enumerates the network sharing types of an NIC.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.|
| SHARING_USB | 1 | USB sharing.|
| SHARING_USB | 1 | USB sharing (not supported currently).|
| SHARING_BLUETOOTH | 2 | Bluetooth sharing.|
......@@ -531,8 +531,8 @@ Enumerates SIM card types and states.
**System capability**: SystemCapability.Telephony.StateRegistry
| Name | Type | Description |
| ----------------- | --------------------- | ------------------------------------------------------------ |
| type | [CardType](js-apis-sim.md#cardtype) | SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).|
| state | [SimState](js-apis-sim.md#simstate) | SIM card status. For details, see [SimState](js-apis-sim.md#simstate).|
| reason<sup>8+</sup> | [LockReason](#lockreason8) | SIM card lock type.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| type | [CardType](js-apis-sim.md#cardtype) | Yes| SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).|
| state | [SimState](js-apis-sim.md#simstate) | Yes| SIM card status. For details, see [SimState](js-apis-sim.md#simstate).|
| 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
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ------------------------------------- |
| 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**
......@@ -349,7 +349,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t
| ------------ | ------------------------------ | ---- | ----------------------------------- |
| windowId | number | Yes | Window ID. |
| pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. |
| callback | AysncCallback&lt;void&gt; | Yes | Callback used to return the result.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Example**
......
......@@ -1734,8 +1734,8 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci
**Example**
```js
radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1763,8 +1763,8 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec
**Example**
```js
radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => {
console.log(`callback: data->${JSON.stringify(data)}`);
});
```
......@@ -1797,10 +1797,10 @@ Defines the signal strength.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ----------- | --------------------------- | ------------------ |
| signalType | [NetworkType](#networktype) | Signal strength type.|
| signalLevel | number | Signal strength level.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| signalType | [NetworkType](#networktype) | Yes| Signal strength type.|
| signalLevel | number | Yes| Signal strength level.|
## NetworkType
......@@ -1825,17 +1825,17 @@ Defines the network status.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ----------------- | --------------------- | ------------------------------------------------------------ |
| longOperatorName | string | Long carrier name of the registered network.|
| shortOperatorName | string | Short carrier name of the registered network.|
| plmnNumeric | string | PLMN code of the registered network.|
| isRoaming | boolean | Whether the user is roaming.|
| regState | [RegState](#regstate) | Network registration status of the device.|
| cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | RAT of the device.|
| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.|
| isCaActive | boolean | CA status.|
| isEmergency | boolean | Whether only emergency calls are allowed.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| longOperatorName | string | Yes | Long carrier name of the registered network.|
| shortOperatorName | string | Yes | Short carrier name of the registered network.|
| plmnNumeric | string | Yes | PLMN code of the registered network.|
| isRoaming | boolean | Yes | Whether the user is roaming.|
| regState | [RegState](#regstate) | Yes | Network registration status of the device.|
| cfgTech<sup>8+</sup> | [RadioTechnology](#radiotechnology) | Yes | RAT of the device.|
| nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device.|
| isCaActive | boolean | Yes | CA status.|
| isEmergency | boolean | Yes | Whether only emergency calls are allowed.|
## RegState
......@@ -1933,13 +1933,13 @@ Defines the cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| networkType | [NetworkType](#networktype) | Network type of the cell. |
| isCamped | boolean | Status of the cell. |
| timeStamp | number | Timestamp when cell information is obtained. |
| signalInformation | [SignalInformation](#signalinformation) | Signal information. |
| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| networkType | [NetworkType](#networktype) | Yes | Network type of the cell. |
| isCamped | boolean | Yes | Status of the cell. |
| timeStamp | number | Yes | Timestamp when cell information is obtained. |
| signalInformation | [SignalInformation](#signalinformation) | Yes | Signal information. |
| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | Yes | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information|
## CdmaCellInformation<sup>8+</sup>
......@@ -1949,13 +1949,13 @@ Defines the CDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| --------- | ------ | ------------ |
| baseId | number | Base station ID. |
| latitude | number | Longitude. |
| longitude | number | Latitude. |
| nid | number | Network ID.|
| sid | number | System ID.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| baseId | number | Yes | Base station ID. |
| latitude | number | Yes | Longitude. |
| longitude | number | Yes | Latitude. |
| nid | number | Yes | Network ID.|
| sid | number | Yes | System ID.|
## GsmCellInformation<sup>8+</sup>
......@@ -1965,14 +1965,14 @@ Defines the GSM cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------ | ------ | -------------------- |
| lac | number | Location area code. |
| cellId | number | Cell ID. |
| arfcn | number | Absolute radio frequency channel number.|
| bsic | number | Base station ID. |
| mcc | string | Mobile country code. |
| mnc | string | Mobile network code. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| lac | number | Yes | Location area code. |
| cellId | number | Yes | Cell ID. |
| arfcn | number | Yes | Absolute radio frequency channel number.|
| bsic | number | Yes | Base station ID. |
| mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. |
## LteCellInformation<sup>8+</sup>
......@@ -1982,16 +1982,16 @@ Defines the LTE cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------------- | ------- | ----------------------- |
| cgi | number | Cell global identification. |
| pci | number | Physical cell ID. |
| tac | number | Tracking area code. |
| earfcn | number | Absolute radio frequency channel number. |
| bandwidth | number | Bandwidth. |
| mcc | string | Mobile country code. |
| mnc | string | Mobile network code. |
| isSupportEndc | boolean | Support New Radio_Dual Connectivity|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| cgi | number | Yes | Cell global identification. |
| pci | number | Yes | Physical cell ID. |
| tac | number | Yes | Tracking area code. |
| earfcn | number | Yes | Absolute radio frequency channel number. |
| bandwidth | number | Yes | Bandwidth. |
| mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. |
| isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity. |
## NrCellInformation<sup>8+</sup>
......@@ -2001,14 +2001,14 @@ Defines the NR cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------- | ------ | ---------------- |
| nrArfcn | number | 5G frequency number. |
| pci | number | Physical cell ID. |
| tac | number | Tracking area code. |
| nci | number | 5G network cell ID.|
| mcc | string | Mobile country code. |
| mnc | string | Mobile network code. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| nrArfcn | number | Yes | 5G frequency number. |
| pci | number | Yes | Physical cell ID. |
| tac | number | Yes | Tracking area code. |
| nci | number | Yes | 5G network cell ID.|
| mcc | string | Yes | Mobile country code. |
| mnc | string | Yes | Mobile network code. |
## TdscdmaCellInformation<sup>8+</sup>
......@@ -2018,14 +2018,14 @@ Defines the TD-SCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------ | ------ | ------------ |
| lac | number | Location area code.|
| cellId | number | Cell ID. |
| cpid | number | Cell parameter ID.|
| uarfcn | number | Absolute radio frequency number.|
| mcc | string | Mobile country code.|
| mnc | string | Mobile network code. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| lac | number | Yes | Location area code.|
| cellId | number | Yes | Cell ID. |
| cpid | number | Yes | Cell parameter ID.|
| uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Yes | Mobile country code.|
| mnc | string | Yes | Mobile network code. |
## WcdmaCellInformation<sup>8+</sup>
......@@ -2035,14 +2035,14 @@ Defines the WCDMA cell information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------ | ------ | ------------ |
| lac | number | Location area code.|
| cellId | number | Cell ID. |
| psc | number | Primary scrambling code. |
| uarfcn | number | Absolute radio frequency number.|
| mcc | string | Mobile country code.|
| mnc | string | Mobile network code. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| lac | number | Yes | Location area code.|
| cellId | number | Yes | Cell ID. |
| psc | number | Yes | Primary scrambling code. |
| uarfcn | number | Yes | Absolute radio frequency number.|
| mcc | string | Yes | Mobile country code.|
| mnc | string | Yes | Mobile network code. |
## NrOptionMode<sup>8+</sup>
......@@ -2067,10 +2067,10 @@ Defines the network search result.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ---------------------- | ------------------------------------------------- | -------------- |
| isNetworkSearchSuccess | boolean | Successful network search.|
| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| isNetworkSearchSuccess | boolean | Yes | Successful network search.|
| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.|
## NetworkInformation
......@@ -2080,12 +2080,12 @@ Defines the network information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| --------------- | ----------------------------------------- | -------------- |
| operatorName | string | Carrier name.|
| operatorNumeric | string | Carrier number. |
| state | [NetworkInformation](#networkinformationstate) | Network information status.|
| radioTech | string | Radio technology. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| operatorName | string | Yes | Carrier name.|
| operatorNumeric | string | Yes | Carrier number. |
| state | [NetworkInformation](#networkinformationstate) | Yes | Network information status.|
| radioTech | string | Yes | Radio technology. |
## NetworkInformationState
......@@ -2110,12 +2110,12 @@ Defines the network selection mode.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------------------ | --------------------------------------------- | -------------------------------------- |
| slotId | number | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. |
| networkInformation | [NetworkInformation](#networkinformation) | Network information. |
| resumeSelection | boolean | Whether to resume selection. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
| selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. |
| networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. |
| resumeSelection | boolean | Yes | Whether to resume selection. |
## ImsRegState<sup>9+</sup>
......@@ -2153,10 +2153,10 @@ Defines the IMS registration information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ----------- | ---------------------------- | ------------- |
| imsRegState | [ImsRegState](#imsregstate9) | IMS registration state.|
| imsRegTech | [ImsRegTech](#imsregtech9) | IMS registration technology.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.|
| imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.|
## ImsServiceType<sup>9+</sup>
......
......@@ -15,8 +15,10 @@ import resourceManager from '@ohos.resourceManager';
## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model.
For details about how to reference **context** in the stage model, see [Context in the Stage Model].
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object.
For details about how to reference **context** in the stage model, see Context in the Stage Model.
```ts
import Ability from '@ohos.application.Ability';
......@@ -97,6 +99,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ----------------- |
| Promise&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
| bundleName | string | Yes | Bundle name of the application.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------ |
| 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
**Example (stage)**
```ts
try {
this.context.getStringValue($r('app.string.test').id, (error, value) => {
this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
......@@ -333,6 +337,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Promise&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
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| --------------------- | ---------------- |
| 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
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------- |
| 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
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------------ |
| 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
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------------------------- | -------------- |
| 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
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------------------------- | ------------------- |
| 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.
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| 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
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| 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.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ---------------- |
| 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.
**System capability**: SystemCapability.Global.ResourceManager
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| 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
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| 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
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------------ |
| 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
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------------------------- | ----------- |
| 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
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| 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
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------------------- | ---- |
| 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
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------------------- | ---- |
| 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
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ---------- |
| 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
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------ |
| 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
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------------------------- | ------------- |
| 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
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| --------------------- | ------------------- |
| 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
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ---------------------- |
| 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
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | Promise used to return the result.|
......@@ -2045,6 +2071,7 @@ Obtains the string corresponding to the specified resource object. This API retu
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------ | ---------------- |
| string | Promise used to return the result.|
......@@ -2088,6 +2115,7 @@ Obtains the string corresponding to the specified resource name. This API return
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | String corresponding to the specified resource name.|
......@@ -2126,6 +2154,7 @@ Obtains the Boolean result corresponding to the specified resource ID. This API
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------- | ------------ |
| boolean | Boolean result corresponding to the specified resource ID.|
......@@ -2163,6 +2192,7 @@ Obtains the Boolean result corresponding to the specified resource object. This
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------- | ----------------- |
| boolean | Boolean result corresponding to the specified resource object.|
......@@ -2206,6 +2236,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------- | ----------- |
| boolean | Boolean result corresponding to the specified resource name.|
......@@ -2244,6 +2275,7 @@ Obtains the integer or float value corresponding to the specified resource ID. T
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------ | ---------- |
| number | Integer or float value corresponding to the specified resource ID.|
......@@ -2288,6 +2320,7 @@ Obtains the integer or float value corresponding to the specified resource objec
| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
| Type | Description |
| ------ | --------------- |
| number | Integer or float value corresponding to the specified resource object.|
......@@ -2331,6 +2364,7 @@ Obtains the integer or float value corresponding to the specified resource name.
| resName | string | Yes | Resource name.|
**Return value**
| Type | Description |
| ------ | --------- |
| number | Integer or float value corresponding to the specified resource name.|
......@@ -2409,6 +2443,7 @@ This API is deprecated since API version 9. You are advised to use [getStringVal
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| --------------------- | ----------- |
| Promise&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
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ---------------------------------- | ------------- |
| 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
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent) instead.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2526,7 +2562,7 @@ getMedia(resId: number): Promise&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.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent-1) instead.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2537,6 +2573,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| ------------------------- | -------------- |
| Promise&lt;Uint8Array&gt; | Promise used to return the result.|
......@@ -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.
This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64) instead.
This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2590,7 +2627,7 @@ getMediaBase64(resId: number): Promise&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.
This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64-1) instead.
This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649-1) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2601,6 +2638,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont
| resId | number | Yes | Resource ID.|
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
......@@ -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.
This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue) instead.
This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2635,6 +2673,7 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr
| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
| Promise&lt;string&gt; | Promise used to return the result.|
......@@ -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.
This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue-1) instead.
This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9-1) instead.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2731,6 +2770,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ------------------------- | ----------- |
| Promise&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
| path | string | Yes | Path of the raw file.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------- |
| Promise&lt;[RawFileDescriptor](#rawfiledescriptor8)&gt; | Promise used to return the result.|
......
......@@ -2847,10 +2847,10 @@ Defines the lock status response.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| --------------- | ------ | ------------------ |
| result | number | Operation result. |
| remain?: number | number | Remaining attempts (can be null).|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| result | number | Yes | Operation result. |
| remain?: number | number | Yes | Remaining attempts (can be null).|
## LockInfo<sup>8+</sup>
......@@ -2860,11 +2860,11 @@ Defines the lock information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| -------- | ------------------------ | ------ |
| lockType | [LockType](#locktype8) | Lock type.|
| password | string | Password. |
| state | [LockState](#lockstate8) | Lock state.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| lockType | [LockType](#locktype8) | Yes | Lock type.|
| password | string | Yes | Password. |
| state | [LockState](#lockstate8) | Yes | Lock state.|
## PersoLockInfo<sup>8+</sup>
......@@ -2874,10 +2874,10 @@ Defines the personalized lock information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| -------- | -------------------------------- | ------------ |
| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.|
| password | string | Password. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.|
| password | string | Yes | Password. |
## IccAccountInfo<sup>7+</sup>
......@@ -2887,15 +2887,15 @@ Defines the ICC account information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ---------- | ------- | ---------------- |
| simId | number | SIM card ID. |
| slotIndex | number | Card slot ID. |
| isEsim | boolean | Whether the SIM card is an eSim card.|
| isActive | boolean | Whether the card is activated. |
| iccId | string | ICCID number. |
| showName | string | SIM card display name. |
| showNumber | string | SIM card display number. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| simId | number | Yes | SIM card ID. |
| slotIndex | number | Yes | Card slot ID. |
| isEsim | boolean | Yes | Whether the SIM card is an eSim card.|
| isActive | boolean | Yes | Whether the card is activated. |
| iccId | string | Yes | ICCID number. |
| showName | string | Yes | SIM card display name. |
| showNumber | string | Yes | SIM card display number. |
## OperatorConfig<sup>8+</sup>
......@@ -2905,10 +2905,10 @@ Defines the carrier configuration.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description|
| ----- | ------ | ---- |
| field | string | Field|
| value | string | Value |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| field | string | Yes | Field. |
| value | string | Yes | Value. |
## DiallingNumbersInfo<sup>8+</sup>
......@@ -2918,12 +2918,12 @@ Defines the contact number information.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Type | Description |
| ------------ | ------ | -------- |
| alphaTag | string | Alpha tag. |
| number | string | Contact number. |
| recordNumber | number | Record number.|
| pin2 | string | PIN 2.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| alphaTag | string | Yes | Alpha tag. |
| number | string | Yes | Contact number. |
| recordNumber | number | Yes | Record number.|
| pin2 | string | Yes | PIN 2.|
## ContactType<sup>8+</sup>
......
......@@ -1116,19 +1116,19 @@ Defines an SMS message instance.
**System capability**: SystemCapability.Telephony.SmsMms
| Name | Type | Description |
| ------------------------ | --------------------------------------- | ------------------------------------------------------------ |
| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.<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**.|
| 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.|
| messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. |
| pdu | Array&lt;number&gt; | PDU in the SMS message. |
| protocolId | number | Protocol identifier used for delivering the SMS message. |
| scAddress | string | SMSC address. |
| scTimestamp | number | SMSC timestamp. |
| status | number | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.|
| visibleMessageBody | string | SMS message body. |
| visibleRawAddress | string | Sender address. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| hasReplyPath | boolean | Yes |Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.<br>**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.|
| isReplaceMessage | boolean | Yes |Whether the received SMS message is a **replace short message**. The default value is **false**.<br>For details, see section 9.2.3.9 in **3GPP TS 23.040**.|
| isSmsStatusReportMessage | boolean | Yes |Whether the received SMS message is an SMS delivery status report. The default value is **false**.<br>**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.|
| messageClass | [ShortMessageClass](#shortmessageclass) | Yes | SMS message type. |
| pdu | Array&lt;number&gt; | Yes | PDU in the SMS message. |
| protocolId | number | Yes | Protocol identifier used for delivering the SMS message. |
| scAddress | string | Yes | SMSC address. |
| scTimestamp | number | Yes | SMSC timestamp. |
| status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.|
| visibleMessageBody | string | Yes | SMS message body. |
| visibleRawAddress | string | Yes | Sender address. |
## ShortMessageClass
......
......@@ -70,7 +70,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput
| toolHeight | number | Yes| No| Height of the tool area.|
| rawX | number | Yes| No| X coordinate of the input device.|
| rawY | number | Yes| No| Y coordinate of the input device.|
| toolType | number | Yes| No| Tool type.|
| toolType | ToolType | Yes| No| Tool type.|
## TouchEvent
......
......@@ -638,16 +638,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ------------- | ------------------------------------------- | ------------- |
| address | number | Endpoint address. |
| attributes | number | Endpoint attributes. |
| interval | number | Endpoint interval. |
| maxPacketSize | number | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. |
| number | number | Endpoint number. |
| type | number | Endpoint type. |
| interfaceId | number | Unique ID of the interface to which the endpoint belongs.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| address | number | Yes | Endpoint address. |
| attributes | number | Yes | Endpoint attributes. |
| interval | number | Yes | Endpoint interval. |
| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. |
| number | number | Yes | Endpoint number. |
| type | number | Yes | Endpoint type. |
| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.|
## USBInterface
......@@ -655,15 +655,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------------- | ---------------------------------------- | --------------------- |
| id | number | Unique ID of the USB interface. |
| protocol | number | Interface protocol. |
| clazz | number | Device type. |
| subClass | number | Device subclass. |
| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.|
| name | string | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Endpoints that belong to the USB interface. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| id | number | Yes | Unique ID of the USB interface. |
| protocol | number | Yes | Interface protocol. |
| clazz | number | Yes | Device type. |
| subClass | number | Yes | Device subclass. |
| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. |
## USBConfig
......@@ -671,15 +671,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| -------------- | ------------------------------------------------ | --------------- |
| id | number | Unique ID of the USB configuration. |
| attributes | number | Configuration attributes. |
| maxPower | number | Maximum power consumption, in mA. |
| name | string | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Support for remote wakeup.|
| isSelfPowered | boolean | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Supported interface attributes. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| id | number | Yes | Unique ID of the USB configuration. |
| attributes | number | Yes | Configuration attributes. |
| maxPower | number | Yes | Maximum power consumption, in mA. |
| name | string | Yes | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes | Support for remote wakeup.|
| isSelfPowered | boolean | Yes | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. |
## USBDevice
......@@ -687,21 +687,21 @@ Represents the USB device information.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------------- | ------------------------------------ | ---------- |
| busNum | number | Bus address. |
| devAddress | number | Device address. |
| serial | string | Sequence number. |
| name | string | Device name. |
| manufacturerName | string | Device manufacturer. |
| productName | string | Product name. |
| version | string | Version number. |
| vendorId | number | Vendor ID. |
| productId | number | Product ID. |
| clazz | number | Device class. |
| subClass | number | Device subclass. |
| protocol | number | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Device configuration descriptor information.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| busNum | number | Yes | Bus address. |
| devAddress | number | Yes | Device address. |
| serial | string | Yes | Sequence number. |
| name | string | Yes | Device name. |
| manufacturerName | string | Yes | Device manufacturer. |
| productName | string | Yes | Product name. |
| version | string | Yes | Version number. |
| vendorId | number | Yes | Vendor ID. |
| productId | number | Yes | Product ID. |
| clazz | number | Yes | Device class. |
| subClass | number | Yes | Device subclass. |
| protocol | number | Yes | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.|
## USBDevicePipe
......@@ -709,10 +709,10 @@ Represents a USB device pipe, which is used to determine a USB device.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ---------- | ------ | ----- |
| busNum | number | Bus address.|
| devAddress | number | Device address.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| busNum | number | Yes | Bus address.|
| devAddress | number | Yes | Device address.|
## USBControlParams
......@@ -720,14 +720,14 @@ Represents control transfer parameters.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| ------- | ----------------------------------------------- | ---------------- |
| request | number | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. |
| value | number | Request parameter value. |
| index | number | Index of the request parameter value.|
| data | Uint8Array | Buffer for writing or reading data. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| request | number | Yes | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. |
| value | number | Yes | Request parameter value. |
| index | number | Yes | Index of the request parameter value.|
| data | Uint8Array | Yes | Buffer for writing or reading data. |
## USBPort<sup>9+</sup>
......@@ -737,11 +737,11 @@ Represents a USB port.
**System capability**: SystemCapability.USB.USBManager
| Name | Type | Description |
| -------------- | -------------------------------- | ----------------------------------- |
| id | number | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus9) | USB port role. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| id | number | Yes | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype9) | Yes | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus9) | Yes | USB port role. |
## USBPortStatus<sup>9+</sup>
......@@ -751,11 +751,11 @@ Enumerates USB port roles.
**System capability**: SystemCapability.USB.USBManager
| Name | Type| Description |
| ---------------- | -------- | ---------------------- |
| currentMode | number | Current USB mode. |
| currentPowerRole | number | Current power role. |
| currentDataRole | number | Current data role.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| currentMode | number | Yes | Current USB mode. |
| currentPowerRole | number | Yes | Current power role. |
| currentDataRole | number | Yes | Current data role. |
## USBRequestTargetType
......
......@@ -720,14 +720,14 @@ Represents the USB endpoint from which data is sent or received. You can obtain
| Name | Type | Mandatory |Description |
| ------------- | ------------------------------------------- | ------------- |------------- |
| address | number | Yes|Endpoint address. |
| attributes | number | Yes|Endpoint attributes. |
| interval | number | Yes|Endpoint interval. |
| maxPacketSize | number | Yes|Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes|Endpoint direction. |
| number | number | Yes|Endpoint number. |
| type | number | Yes|Endpoint type. |
| interfaceId | number | Yes|Unique ID of the interface to which the endpoint belongs.|
| address | number | Yes | Endpoint address. |
| attributes | number | Yes | Endpoint attributes. |
| interval | number | Yes | Endpoint interval. |
| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. |
| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. |
| number | number | Yes | Endpoint number. |
| type | number | Yes | Endpoint type. |
| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.|
## USBInterface
......@@ -737,13 +737,13 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U
| Name | Type | Mandatory |Description |
| ---------------- | ---------------------------------------- | ------------- |--------------------- |
| id | number | Yes|Unique ID of the USB interface. |
| protocol | number | Yes|Interface protocol. |
| clazz | number | Yes|Device type. |
| subClass | number | Yes|Device subclass. |
| alternateSetting | number | Yes|Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes|Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes|Endpoints that belong to the USB interface. |
| id | number | Yes | Unique ID of the USB interface. |
| protocol | number | Yes | Interface protocol. |
| clazz | number | Yes | Device type. |
| subClass | number | Yes | Device subclass. |
| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.|
| name | string | Yes | Interface name. |
| endpoints | Array&lt;[USBEndpoint](#usbendpoint)&gt; | Yes | Endpoints that belong to the USB interface. |
## USBConfig
......@@ -753,13 +753,13 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------------------------ | --------------- |--------------- |
| id | number | Yes|Unique ID of the USB configuration. |
| attributes | number | Yes|Configuration attributes. |
| maxPower | number | Yes|Maximum power consumption, in mA. |
| name | string | Yes|Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes|Support for remote wakeup.|
| isSelfPowered | boolean | Yes| Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes|Supported interface attributes. |
| id | number | Yes | Unique ID of the USB configuration. |
| attributes | number | Yes | Configuration attributes. |
| maxPower | number | Yes | Maximum power consumption, in mA. |
| name | string | Yes | Configuration name, which can be left empty. |
| isRemoteWakeup | boolean | Yes | Support for remote wakeup.|
| isSelfPowered | boolean | Yes | Support for independent power supplies.|
| interfaces | Array&nbsp;&lt;[USBInterface](#usbinterface)&gt; | Yes | Supported interface attributes. |
## USBDevice
......@@ -769,19 +769,19 @@ Represents the USB device information.
| Name | Type | Mandatory |Description |
| ---------------- | ------------------------------------ | ---------- |---------- |
| busNum | number | Yes|Bus address. |
| devAddress | number | Yes|Device address. |
| serial | string | Yes|Sequence number. |
| name | string | Yes|Device name. |
| manufacturerName | string | Yes| Device manufacturer. |
| productName | string | Yes|Product name. |
| version | string | Yes|Version number. |
| vendorId | number | Yes|Vendor ID. |
| productId | number | Yes|Product ID. |
| clazz | number | Yes|Device class. |
| subClass | number | Yes|Device subclass. |
| protocol | number | Yes|Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes|Device configuration descriptor information.|
| busNum | number | Yes | Bus address. |
| devAddress | number | Yes | Device address. |
| serial | string | Yes | Sequence number. |
| name | string | Yes | Device name. |
| manufacturerName | string | Yes | Device manufacturer. |
| productName | string | Yes | Product name. |
| version | string | Yes | Version number. |
| vendorId | number | Yes | Vendor ID. |
| productId | number | Yes | Product ID. |
| clazz | number | Yes | Device class. |
| subClass | number | Yes | Device subclass. |
| protocol | number | Yes | Device protocol code. |
| configs | Array&lt;[USBConfig](#usbconfig)&gt; | Yes | Device configuration descriptor information.|
## USBDevicePipe
......@@ -802,12 +802,12 @@ Represents control transfer parameters.
| Name | Type | Mandatory |Description |
| ------- | ----------------------------------------------- | ---------------- |---------------- |
| request | number | Yes |Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes |Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes |Control request type. |
| value | number | Yes |Request parameter value. |
| index | number | Yes |Index of the request parameter value.|
| data | Uint8Array | Yes |Buffer for writing or reading data. |
| request | number | Yes | Request type. |
| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. |
| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. |
| value | number | Yes | Request parameter value. |
| index | number | Yes | Index of the request parameter value.|
| data | Uint8Array | Yes | Buffer for writing or reading data. |
## USBPort
......@@ -819,9 +819,9 @@ Represents a USB port.
| Name | Type | Mandatory |Description |
| -------------- | ------------------------------- | ------------------- |------------------------ |
| id | number | Yes |Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes |Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes |USB port role. |
| id | number | Yes | Unique identifier of a USB port. |
| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.|
| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. |
## USBPortStatus
......@@ -833,9 +833,9 @@ Enumerates USB port roles.
| Name | Type| Mandatory |Description |
| ---------------- | -------- | ---------------- |---------------------- |
| currentMode | number | Yes|Current USB mode. |
| currentPowerRole | number | Yes |Current power role. |
| currentDataRole | number | Yes |Current data role.|
| currentMode | number | Yes | Current USB mode. |
| currentPowerRole | number | Yes | Current power role. |
| currentDataRole | number | Yes | Current data role.|
## USBRequestTargetType
......@@ -843,12 +843,12 @@ Enumerates request target types.
**System capability**: SystemCapability.USB.USBManager
| Name | Value | Description |
| ---------------------------- | ---- | ------ |
| USB_REQUEST_TARGET_DEVICE | 0 | Device|
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface|
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint|
| USB_REQUEST_TARGET_OTHER | 3 | Other|
| Name | Value | Description |
| ---------------------------- | ----- | ----------- |
| USB_REQUEST_TARGET_DEVICE | 0 | Device |
| USB_REQUEST_TARGET_INTERFACE | 1 | Interface |
| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint |
| USB_REQUEST_TARGET_OTHER | 3 | Other |
## USBControlRequestType
......
......@@ -4,11 +4,11 @@
### Function
The motion module provides motion recognition and control capabilities. Currently, OpenHarmony supports recognition of pick-up, flip, shake, and rotation.
The motion module provides motion recognition and control capabilities. OpenHarmony supports recognition of pick-up, flip, shake, and rotation.
The motion driver is developed based on the hardware driver foundation (HDF). It shields hardware differences and provides APIs for the Multimodal Sensor Data Platform (MSDP) to implement capabilities such as enabling or disabling motion recognition, and subscribing to or unsubscribing from motion recognition data.
The figure below shows the motion driver architecture. The framework layer provides MSDP services, and interacts with the Motion Stub through the Motion Proxy in the User Hardware Driver Foundation (UHDF). The Motion Stub calls the Motion HDI Impl APIs to provide motion recognition capabilities for upper-layer services.
The following figure shows the motion driver architecture. The framework layer provides MSDP services, and interacts with the Motion Stub through the Motion Proxy in the User Hardware Driver Foundation (UHDF). The Motion Stub calls the Motion HDI Impl APIs to provide motion recognition capabilities for upper-layer services.
**Figure 1** Motion driver architecture
......@@ -23,8 +23,8 @@ The figure below illustrates how a motion driver works.
![](figures/motion_driver_work.png)
1. MSDP: The MSDP service obtains a Motion HDI service instance from the Motion Proxy and calls the Motion HDI API.
2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor.
3. HDI Service: HDI Service consists of Motion Interface Driver, Motion Service, and Motion Impl. Motion Interface Driver provides the motion driver code. A **HdfDriverEntry** structure is defined to implement the **Init**, **Bind**, and **Release** functions. The **HDF_INIT** macro is used to load the driver in the functions. Motion Service provides the motion recognition service interface class. The specific implementation is described in Motion Impl. The code of HDI Service must be developed by the component vendor.
2. IDL: The IService Manager allocates a Motion HDI instance requested by the MSDP service, and the Motion Proxy forwards the instance to the MSDP service. After the MSDP service calls the HDI API provided by the Motion Proxy, Motion Stub is called through Inter-Process Communication (IPC) to invoke the Motion Service API. The code is automatically generated by a tool and does not need to be developed by the component vendor.
3. HDI Service: The HDI service consists of Motion Interface Driver, Motion Service, and Motion Impl. Motion Interface Driver provides the motion driver code. A **HdfDriverEntry** structure is defined to implement the **Init**, **Bind**, and **Release** functions. The **HDF_INIT** macro is used to load the driver in the functions. Motion Service provides the motion recognition service interface class. The specific implementation is described in Motion Impl. The code of HDI Service must be developed by the component vendor.
## Development Guidelines
......@@ -53,15 +53,15 @@ The development procedure is as follows:
The motion recognition directory structure is as follows:
```undefined
/drivers/peripheral/motion # Developed by the vendor.
├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer.
├── test # Test code for the motion recognition module.
│ └── unittest\hdi # HDI unit test code for the motion recognition module.
/drivers/peripheral/motion # Developed by the vendor.
├── hdi_service # Driver capabilities provided by the motion recognition module for the MSDP service layer.
├── test # Test code for the motion recognition module.
│ └── unittest\hdi # HDI unit test code for the motion recognition module.
```
The following describes how to develop a user-mode motion driver based on the HDF. For details, see [motion_interface_driver.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/motion/hdi_service/motion_interface_driver.cpp).
To develop the user-mode driver for motion recognition, implement the **Bind**, **Init**, **Release**, and **Dispatch** functions. The **Bind** function provides service capabilities. The **Init** function initializes the driver before the driver is loaded. The **Release** function releases resources when the **Init** function fails.
You need to implement the **Bind()**, **Init()**, **Release()**, and **Dispatch()** functions. The **Bind()** function binds the service capability with the driver; **Init()** implements the initialization required before the driver is loaded; **Release()** reclaims resources when **Init()** fails; **Dispatch()** implements the service, which is bound in **Bind()**.
```c++
// Custom HdfMotionInterfaceHost object
......@@ -153,7 +153,6 @@ struct HdfDriverEntry g_motioninterfaceDriverEntry = {
HDF_INIT(g_userAuthInterfaceDriverEntry);
```
### Verification
The procedure is as follows:
......
# Sensor
## Overview
### Introduction
### Function
The sensor driver model masks the sensor hardware differences and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor options. The model is developed on the Hardware Driver Foundation (HDF), Operating System Abstraction Layer (OSAL), and platform driver interfaces (such as the I2C, SPI, and UART buses). It provides functionalities such as cross-OS migration and differentiated device configurations. The figure below shows the architecture of the sensor driver model.
The sensor driver model shields the hardware difference and provides interfaces for the upper-layer sensor service to implement basic sensor capabilities, including querying the sensor list, enabling or disabling a sensor, subscribing to or unsubscribing from sensor data changes, and setting sensor attributes. Developed based on the Hardware Driver Foundation (HDF), the sensor driver model leverages the capabilities of the OS adaptation layer (OSAL) and platform driver interfaces (such as I2C, SPI, and UART buses) to shield the difference between OSs and platform bus resources, achieving "one-time development and multi-system deployment" of the sensor driver. The figure below shows the architecture of the sensor driver model.
**Figure 1** Sensor driver model
![Sensor driver model](figures/sensor_driver_model.png)
### Basic Concepts
Currently, sensors are classified into medical sensors and traditional sensors by sensor ID.
Sensors are classified into the following types by sensor ID:
- The IDs of medical sensors range from 128 to 160.
- Medical sensors: The sensor IDs range from 128 to 160.
- The IDs of traditional sensors are out of the range of 128 to 160.
- Traditional sensors: The sensor IDs are out of the range of 128 to 160.
### Working Principles
Based on the loading and running process (shown below) of the sensor driver model, the relationships between key modules in the model and associated modules are clearly defined.
The following figure shows how a sensor driver works.
**Figure 2** How sensor driver works
**Figure 2** How a sensor driver works
![How sensor driver works](figures/sensor_working.png)
The following uses the acceleration sensor driver on the Hi3516D V300 development board of the standard system as an example to describe the driver loading and running process.
1. The sensor host reads the sensor management configuration from the Sensor Host node of the device_info HCS (sensor device information HCS).
2. The sensor host parses the sensor management configuration from the HCB database and associates the corresponding sensor driver.
1. The sensor host reads the sensor device management configuration from **Sensor Host** in the **device_info.hcs** file.
2. The sensor host parses the sensor management configuration from the HCB database and associates the configuration with the sensor driver.
3. The sensor host loads and initializes the sensor manager driver.
4. The sensor manager driver publishes the sensor hardware device interfaces (HDIs).
5. The sensor host reads the acceleration sensor driver configuration from the Sensor Host node of the device_info HCS.
4. The sensor manager driver publishes the sensor APIs for the hardware driver interface (HDI).
5. The sensor host reads the acceleration sensor driver configuration information from **Sensor Host** in the **device_info.hcs** configuration file.
6. The sensor host loads the acceleration sensor abstract driver and calls the initialization interface to allocate the sensor driver resources and create the data processing queue.
7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the accel_xxx_config HCS (sensor private configuration HCS).
7. The sensor host reads the chipset driver configuration and private configuration of the acceleration sensor from the **accel_xxx_config.hcs** file.
8. The acceleration sensor chipset driver calls the common configuration parsing interface to parse the sensor attributes and registers.
9. The chipset driver detects sensors, allocates configuration resources to the acceleration sensor, and registers the acceleration sensor chipset interfaces.
10. Upon successful sensor detection, the chipset driver instructs the abstract driver to register the acceleration sensor to the sensor manager driver.
......@@ -54,34 +54,38 @@ The following uses the acceleration sensor driver on the Hi3516D V300 developmen
The sensor driver model offers the following APIs:
- Sensor HDIs, for easier sensor service development
- Sensor driver model capability interfaces
- Interfaces for registering, loading, and deregistering sensor drivers, and detecting sensors
- Driver normalization interface, register configuration parsing interface, bus access abstract interface, and platform abstract interface for the same type of sensors
- Interfaces to be implemented by developers: Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, developers need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development.
- Sensor HDI APIs, for easier sensor service development
- APIs for implementing sensor driver model capabilities
- APIs for loading, registering, and deregitering sensor drivers, and detecting sensors based on the HDF
- Unified driver API, register configuration parsing API, bus access abstract API, and platform abstract API for the same type of sensors
- APIs to be implemented by developers
Based on the HDF Configuration Source (HCS) and differentiated configuration for sensors of the same type, you need to implement serialized configuration of sensor device parameters and some sensor device operation interfaces to simplify sensor driver development.
The sensor driver model provides APIs for the hardware service to make sensor service development easier. See the table below.
**Table 1** APIs of the sensor driver model
| API| Description|
| API| Description|
| ----- | -------- |
| int32_t GetAllSensors(struct SensorInformation **sensorInfo, int32_t *count) | Obtains information about all registered sensors in the system. The sensor information includes the sensor name, sensor vendor, firmware version, hardware version, sensor type ID, sensor ID, maximum range, accuracy, and power consumption.|
| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.|
| int32_t Disable(int32_t sensorId) | Disables a sensor.|
| int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.|
| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.|
| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.|
| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.|
| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.|
| int32_t Enable(int32_t sensorId) | Enables a sensor. The subscriber can obtain sensor data only after the sensor is enabled.|
| int32_t Disable(int32_t sensorId) | Disables a sensor.|
| int32_t SetBatch(int32_t sensorId, int64_t samplingInterval, int64_t reportInterval) | Sets the sampling interval and data reporting interval for a sensor.|
| int32_t SetMode(int32_t sensorId, int32_t mode) | Sets the data reporting mode for a sensor.|
| int32_t SetOption(int32_t sensorId, uint32_t option) | Sets options for a sensor, including its range and accuracy.|
| int32_t Register(int32_t groupId, RecordDataCallback cb) | Registers a sensor data callback based on the group ID.|
| int32_t Unregister(int32_t groupId, RecordDataCallback cb) | Deregisters a sensor data callback based on the group ID.|
The sensor driver model provides driver development APIs that do not require further implementation. See the table below.
**Table 2** Sensor driver development APIs that do not need to be implemented by driver developers
**Table 2** Sensor driver development APIs
| API| Description|
| API| Description|
| ----- | -------- |
| int32_t AddSensorDevice(const struct SensorDeviceInfo *deviceInfo) | Adds a sensor of the current type to the sensor management module.|
| int32_t DeleteSensorDevice(const struct SensorBasicInfo *sensorBaseInfo) | Deletes a sensor from the sensor management module.|
......@@ -97,12 +101,11 @@ The sensor driver model provides driver development APIs that do not require fur
The sensor driver model also provides certain driver development APIs that need to be implemented by driver developers. See the table below.
**Table 3** APIs that need to be implemented by driver developers
**Table 3** APIs to be implemented by driver developers
| API| Description|
| API| Description|
| ----- | -------- |
| int32_t init(void) | Initializes the sensor device configuration after a sensor is detected.|
| int32_t Enable(void) | Enables the current sensor by delivering the register configuration in the enabling operation group based on the device information HCS configuration.|
......@@ -121,14 +124,14 @@ The sensor driver model also provides certain driver development APIs that need
```c
/* Register the entry structure object of the acceleration sensor. */
struct HdfDriverEntry g_sensorAccelDevEntry = {
.moduleVersion = 1, // Version of the acceleration sensor module.
.moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file.
.Bind = BindAccelDriver, // Function for binding an acceleration sensor.
.Init = InitAccelDriver, // Function for initializing an acceleration sensor.
.Release = ReleaseAccelDriver, // Function for releasing acceleration sensor resources.
.moduleVersion = 1, // Version of the acceleration sensor module.
.moduleName = "HDF_SENSOR_ACCEL", // Name of the acceleration sensor module. The value must be the same as that of moduleName in the device_info.hcs file.
.Bind = BindAccelDriver, // Function for binding an acceleration sensor.
.Init = InitAccelDriver, // Function for initializing an acceleration sensor.
.Release = ReleaseAccelDriver // Function for releasing acceleration sensor resources.
};
/* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls the Bind function first and then the Init function. If the Init function fails to be called, the HDF will call Release to release the driver resource and exit the sensor driver model. */
/* Call HDF_INIT to register the driver entry with the HDF. When loading the driver, the HDF calls Bind() and then Init() to load the driver. If Init() fails to be called, the HDF calls Release() to release resources and exit. */
HDF_INIT(g_sensorAccelDevEntry);
```
......@@ -228,7 +231,7 @@ The sensor driver model also provides certain driver development APIs that need
return drvData->accelCfg;
...
}
/* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a sensor data reporting timer, register the sensor normalization APIs, and register the sensor device. */
/* The entry function of the acceleration sensor driver is used to initialize the sensor private data structure object, allocate space for the sensor HCS data configuration object, call the entry function for initializing the sensor HCS data configuration, detect whether the sensor device is in position, create a timer for sensor data reporting, register the sensor normalization APIs, and register the sensor device. */
int32_t AccelInitDriver(struct HdfDeviceObject *device)
{
...
......@@ -271,16 +274,16 @@ The sensor driver model also provides certain driver development APIs that need
The acceleration sensor model uses the HCS as the configuration source code. For details about the HCS configuration fields, see [Driver Configuration Management](driver-hdf-manage.md).
```
```hcs
/* Device information HCS configuration of the acceleration sensor. */
device_sensor_accel :: device {
device0 :: deviceNode {
policy = 1; // Policy for publishing the driver service.
priority = 110; // Driver startup priority (0–200). A larger value indicates a lower priority. The default value 100 is recommended. The sequence for loading devices with the same priority is random.
preload = 0; // Field for specifying whether to load the driver. The value 0 means to load the driver, and 2 means the opposite.
permission = 0664; // Permission for the driver to create a device node.
moduleName = "HDF_SENSOR_ACCEL"; // Driver name. The value must be the same as that of moduleName in the driver entry structure.
serviceName = "sensor_accel"; // Name of the service provided by the driver. The name must be unique.
policy = 1; // Policy for the driver to publish services.
priority = 100; // Priority (0–200) for starting the driver. A larger value indicates a lower priority. The recommended value is 100. If the priorities are the same, the device loading sequence is not ensured.
preload = 0; // The value 0 means to load the driver by default during the startup of the system. The value 2 means the opposite.
permission = 0664; // Permission for the device node created.
moduleName = "HDF_SENSOR_ACCEL"; // Driver name. It must be the same as moduleName in the driver entry structure.
serviceName = "sensor_accel"; // Name of the service published by the driver. The name must be unique.
deviceMatchAttr = "hdf_sensor_accel_driver"; // Keyword matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver.
}
}
......@@ -466,7 +469,7 @@ The sensor driver model also provides certain driver development APIs that need
/* Release the resources allocated during driver initialization. */
void Bmi160ReleaseDriver(struct HdfDeviceObject *device)
{
......
...
if (drvData->sensorCfg != NULL) {
AccelReleaseCfgData(drvData->sensorCfg);
drvData->sensorCfg = NULL;
......@@ -511,18 +514,12 @@ The sensor driver model also provides certain driver development APIs that need
}
```
>![](../public_sys-resources/icon-note.gif) **NOTE**
>
>- The sensor driver model provides certain APIs to implement sensor driver capabilities, including the driver device management, abstract bus and platform operation, common configuration, and configuration parsing capabilities. For details about them, see Table 2.
>- You need to implement the following functions: certain sensor operation interfaces (listed in Table 3) and sensor chipset HCS configuration.
>- You also need to verify basic driver functions.
### Verification
### How to Verify
After the driver is developed, develop test cases in the sensor unit test to verify the basic functions of the driver. Use your test platform to set up the test environment.
After the driver is developed, you can develop self-test cases in the sensor unit test to verify the basic functions of the driver. Use the developer self-test platform as the test environment.
```
static int32_t g_sensorDataFlag = 0; // Indicates whether to report sensor data.
```c++
static int32_t g_sensorDataFlag = 0; // Whether to report sensor data.
static const struct SensorInterface *g_sensorDev = nullptr; // Retain the obtained sensor interface instance address.
/* Register the data reporting function. */
......@@ -558,9 +555,9 @@ void HdfSensorTest::TearDownTestCase()
/* Verify the sensor driver. */
HWTEST_F(HdfSensorTest,TestAccelDriver_001, TestSize.Level0)
{
int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds.
int32_t pollTime = 5; // Data sampling duration, in seconds.
int32_t accelSensorId = 1; // Acceleration sensor ID, which is 1.
int32_t sensorInterval = 1000000000; // Data sampling interval, in nanoseconds.
int32_t pollTime = 5; // Data sampling time, in seconds.
int32_t accelSensorId = 1; // Acceleration sensor ID, which specifies the sensor type.
int32_t count = 0;
int ret;
struct SensorInformation *sensorInfo = nullptr;
......
# 使用显式Want启动Ability
在应用使用场景中,当用户点击某个按钮时,应用经常需要拉起指定UIAbility组件来完成某些特定任务。下面介绍如何通过显式Want拉起应用内一个指定UIAbility组件。
## 开发步骤
1. Stage模型工程内,创建一个Ability(此示例内命名为callerAbility)与相应Page(此示例中名为Index.ets),并在callerAbility.ts文件内的onWindowStageCreate函数内通过windowStage.loadContent()方法将两者绑定。
```ts
// ...
// callerAbility.ts
onWindowStageCreate(windowStage) {
// Main window is created, set main page for this ability
console.info('[Demo] EntryAbility onWindowStageCreate')
// Bind callerAbility with a paged named Index
windowStage.loadContent('pages/Index')
}
// ...
```
2. 同上方法再创建一个Ability,此示例内命名为“calleeAbility”。
3. 在callerAbility的“Index.ets”页面内新增一个按钮。
```ts
// ...
build() {
Row() {
Column() {
Text('hello')
.fontSize(50)
.fontWeight(FontWeight.Bold)
// A new button with will call explicitStartAbility() when clicked.
Button("CLICKME")
.onClick(this.explicitStartAbility) // explicitStartAbility见下面示例代码
// ...
}
.width('100%')
}
.height('100%')
}
// ...
```
4. 补充相对应的onClick方法,并使用**显式Want**在方法内启动calleeAbility。bundleName字段可在工程AppScope&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%;" />
在应用使用场景中,当用户在应用内点击某个按钮时,经常需要拉起指定UIAbility组件来完成某些特定任务。在启动UIAbility时,指定了abilityName和bundleName参数,可以使用显示Want方式启动UIAbility。显示Want的使用请参见[启动应用内的UIAbility](uiability-intra-device-interaction.md#启动应用内的uiability)
......@@ -41,7 +41,7 @@
## 开发步骤
1. 在自定义函数implicitStartAbility内使用**隐式Want**启动Ability。
```ts
async implicitStartAbility() {
try {
......@@ -71,12 +71,12 @@
匹配过程如下:
1. want内action不为空,且被skills内action包括,匹配成功。
2. want内entities不为空,且被skills内entities包括,匹配成功。
3. skills内uris拼接为https://www.test.com:8080/query\* (\*为通配符)包含want内uri,匹配成功。
3. skills内uris拼接为`https://www.test.com:8080/query*` (\*为通配符)包含want内uri,匹配成功。
4. want内type不为空,且被skills内type包含,匹配成功。
2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
2. 当有多个匹配应用时,会被应用选择器展示给用户进行选择。
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
# 常见action与entities
**[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)**:表示调用方要执行的通用操作(如查看、分享、应用详情)。在隐式Want中,您可定义该字段,配合uri或parameters来表示对数据要执行的操作。如打开,查看该uri数据。例如,当uri为一段网址,action为ohos.want.action.viewData则表示匹配可查看该网址的Ability。在Want内声明action字段表示希望被调用方应用支持声明的操作。在被调用方应用配置文件skills字段内声明actions表示该应用支持声明操作。
......@@ -15,7 +14,6 @@
- ACTION_VIEW_MULTIPLE_DATA:发送多个数据记录的操作。
**[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)**:表示目标Ability的类别信息(如浏览器、视频播放器),在隐式Want中是对action的补充。在隐式Want中,开发者可定义该字段,来过滤匹配应用的类别,例如必须是浏览器。在Want内声明entities字段表示希望被调用方应用属于声明的类别。在被调用方应用配置文件skills字段内声明entites表示该应用支持的类别。
......
......@@ -64,7 +64,7 @@
- "ability.picker.fileSizes":应用选择器根据该字段展示文件大小。以字节为单位。
- "ability.picker.fileNames"与"ability.picker.fileSizes"为数组,其有一一对应关系。
例如:当"ability.picker.type"为“application/pdf”,"ability.picker.fileNames"为“["接口文档.pdf"]”,"ability.picker.fileSizes"为“[350 \* 1024]”时,应用选择器将以下形式展示。
例如:当"ability.picker.type"为“application/pdf”,"ability.picker.fileNames"为“["接口文档.pdf"]”,"ability.picker.fileSizes"为“[350 \* 1024]”时,应用选择器将以下形式展示。
<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将传递至所选应用。
......
......@@ -49,7 +49,7 @@
### want参数的action匹配规则
将调用方传入的want参数的action与待匹配Ability的skills配置中的actions进行匹配。
将调用方传入的want参数的[action](../reference/apis/js-apis-ability-wantConstant.md#wantconstantaction)与待匹配Ability的skills配置中的actions进行匹配。
- 调用方传入的want参数的action不为空,待匹配Ability的skills配置中的actions为空,则action匹配失败。
......@@ -64,7 +64,7 @@
### want参数的entities匹配规则
将调用方传入的want参数的entities与待匹配Ability的skills配置中的entities进行匹配。
将调用方传入的want参数的[entities](../reference/apis/js-apis-ability-wantConstant.md#wantconstantentity)与待匹配Ability的skills配置中的entities进行匹配。
- 调用方传入的want参数的entities为空,待匹配Ability的skills配置中的entities不为空,则entities匹配成功。
......@@ -84,7 +84,7 @@
调用方传入的want参数中设置uri和type参数发起组件启动请求,系统会遍历当前系统已安装的组件列表,并逐个匹配待匹配Ability的skills配置中的uris数组,如果待匹配Ability的skills配置中的uris数组中只要有一个可以匹配调用方传入的want参数中设置的uri和type即为匹配成功。
**图3** want参数中uri和type皆不为空时的匹配规则
**图3** want参数中uri和type皆不为空时的匹配规则
<img src="figures/want-uri-type1.png" alt="want-uri-type1" style="zoom: 80%;" />
实际应用中,uri和type共存在四种情况,下面将讲解四种情况的具体匹配规则:
......@@ -110,7 +110,7 @@
下图为了简化描述,称want中传入的uri为w_uri,称want中传入的type为w_type, 待匹配Ability的skills配置中uris为s_uris,其中每个元素为s_uri;按自上而下顺序匹配。
**图4** want参数中uri和type的具体匹配规则
**图4** want参数中uri和type的具体匹配规则
<img src="figures/want-uri-type2.png" alt="want-uri-type2" style="zoom:80%;" />
......@@ -133,24 +133,24 @@
> **说明:**
> 待匹配Ability的skills配置的uris中scheme、host、port、path、pathStartWith和pathRegex属性拼接,如果依次声明了path、pathStartWith和pathRegex属性时,uris将分别拼接为如下三种表达式:
>
> - **全路径表达式**:scheme://host:port/path
> - **全路径表达式**:`scheme://host:port/path`
>
> - **前缀表达式**:scheme://host:port/pathStartWith
> - **前缀表达式**:`scheme://host:port/pathStartWith`
>
> - **正则表达式**:scheme://host:port/pathRegex
> - **正则表达式**:`scheme://host:port/pathRegex`
### type匹配规则
> **说明:**
> 此小节所述的type匹配规则的适用性需建立在want参数内type不为空的基础上。当want参数内type为空时请参[want参数的uri和type匹配规则](#want参数的uri和type匹配规则)。
> 此小节所述的type匹配规则的适用性需建立在want参数内type不为空的基础上。当want参数内type为空时请参[want参数的uri和type匹配规则](#want参数的uri和type匹配规则)。
这里为了简化描述,称want中传入的uri为w_type,待匹配Ability的skills数组中uris的type数据为s_type,具体的匹配规则如下:
- 如果s_type为空,则匹配失败。
- 如果s_type或者w_type为通配符"\*/\*",则匹配成功。
- 如果s_type或者w_type为通配符`*/*`,则匹配成功。
- 如果s_type最后一个字符为通配符'\*',如"prefixType/\*",则当w_type包含"prefixType/"时匹配成功,否则匹配失败。
- 如果s_type最后一个字符为通配符`*`,如`prefixType/*`,则当w_type包含`prefixType/`时匹配成功,否则匹配失败。
- 如果w_type最后一个字符为通配符'\*',如"prefixType/\*",则当s_type包含"prefixType/"时匹配成功,否则匹配失败。
- 如果w_type最后一个字符为通配符`*`,如`prefixType/*`,则当s_type包含`prefixType/`时匹配成功,否则匹配失败。
......@@ -15,15 +15,14 @@ UIAbility的启动模式是指UIAbility实例在启动时的不同呈现状态
singleton启动模式为单实例模式,也是默认情况下的启动模式。
每次调用startAbility()方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。
每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,如果应用进程中该类型的UIAbility实例已经存在,则复用系统中的UIAbility实例。系统中只存在唯一一个该UIAbility实例,即在最近任务列表中只存在一个该类型的UIAbility实例。
**图1** 单实例模式演示效果
<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()方法启动该UIAbility实例,此时只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其onCreate()和onWindowStageCreate()生命周期回调。
> **说明**:应用的UIAbility实例已创建,该UIAbility配置为单实例模式,再次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其[onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。
如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的"launchType"字段配置为"singleton"即可。
如果需要使用singleton启动模式,在[module.json5配置文件](../quick-start/module-configuration-file.md)中的`launchType`字段配置为`singleton`即可。
```json
......@@ -43,12 +42,12 @@ singleton启动模式为单实例模式,也是默认情况下的启动模式
## standard启动模式
standard启动模式为标准实例模式,每次调用startAbility()方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。
standard启动模式为标准实例模式,每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,都会在应用进程中创建一个新的该类型UIAbility实例。即在最近任务列表中可以看到有多个该类型的UIAbility实例。这种情况下可以将UIAbility配置为standard(标准实例模式)。
**图2** 标准实例模式演示效果
<img src="figures/standard-mode.png" alt="standard-mode" style="zoom:50%;" />
**图2** 标准实例模式演示效果
<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
......@@ -70,19 +69,12 @@ standard启动模式的开发使用,在[module.json5配置文件](../quick-sta
specified启动模式为指定实例模式,针对一些特殊场景使用(例如文档应用中每次新建文档希望都能新建一个文档实例,重复打开一个已保存的文档希望打开的都是同一个文档实例)。
在UIAbility实例创建之前,允许开发者为该实例创建一个唯一的字符串Key,创建的UIAbility实例绑定Key之后,后续每次调用startAbility()方法时,都会询问应用使用哪个Key对应的UIAbility实例来响应startAbility()请求。运行时由UIAbility内部业务决定是否创建多实例,如果匹配有该UIAbility实例的Key,则直接拉起与之绑定的UIAbility实例,否则创建一个新的UIAbility实例。
**图3** 指定实例模式演示效果
**图3** 指定实例模式演示效果
<img src="figures/uiability-launch-type2.png" alt="uiability-launch-type2" style="zoom:50%;" />
> **说明:**
>
> 1. 应用的UIAbility实例已创建,该UIAbility配置为指定实例模式,再次调用startAbility()方法启动该UIAbility实例,且[AbilityStage](abilitystage.md)的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)回调匹配到一个已创建的UIAbility实例。此时,再次启动该UIAbility时,只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其onCreate()和onWindowStageCreate()生命周期回调。
> 2. DevEco Studio默认工程中未自动生成AbilityStage,AbilityStage文件的创建请参见[AbilityStage组件容器](abilitystage.md)。
例如有两个UIAbility:EntryAbility和FuncAbility,FuncAbility配置为specified启动模式,需要从EntryAbility的页面中启动FuncAbility。
例如有两个UIAbility:EntryAbility和SpecifiedAbility,SpecifiedAbility配置为specified启动模式,需要从EntryAbility的页面中启动SpecifiedAbility。
1.FuncAbility中,将[module.json5配置文件](../quick-start/module-configuration-file.md)的"launchType"字段配置为"specified"
1.SpecifiedAbility中,将[module.json5配置文件](../quick-start/module-configuration-file.md)`launchType`字段配置为`specified`
```json
{
......@@ -98,7 +90,8 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
}
```
2. 在EntryAbility中,调用startAbility()方法时,在want参数中,增加一个自定义参数来区别UIAbility实例,例如增加一个"instanceKey"自定义参数。
2. 在UIAbility实例创建之前,允许开发者为该实例创建一个唯一的字符串Key,创建的UIAbility实例绑定Key之后,后续每次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,都会询问应用使用哪个Key对应的UIAbility实例来响应[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)请求。
在EntryAbility中,调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法时,在want参数中,增加一个自定义参数来区别UIAbility实例,例如增加一个`instanceKey`自定义参数。
```ts
// 在启动指定实例模式的UIAbility时,给每一个UIAbility实例配置一个独立的Key标识
......@@ -110,7 +103,7 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
let want = {
deviceId: '', // deviceId为空表示本设备
bundleName: 'com.example.myapplication',
abilityName: 'FuncAbility',
abilityName: 'SpecifiedAbility',
moduleName: 'module1', // moduleName非必选
parameters: { // 自定义信息
instanceKey: getInstance(),
......@@ -123,8 +116,9 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
// ...
})
```
3. 由于FuncAbility的启动模式配置为了指定实例启动模式,在FuncAbility启动之前,会先进入其对应的AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调中,解析传入的want参数,获取"instanceKey"自定义参数。根据业务需要通过AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调返回一个字符串Key标识。[如果返回的Key对应一个已启动的UIAbility](mission-management-launch-type.md#fig14520125175314),则会将之前的UIAbility拉回前台并获焦,而不创建新的实例,否则创建新的实例并启动。
3. 运行时由UIAbility内部业务决定是否创建多实例,如果匹配有该UIAbility实例的Key,则直接拉起与之绑定的UIAbility实例,否则创建一个新的UIAbility实例。
由于SpecifiedAbility的启动模式配置为了指定实例启动模式,在SpecifiedAbility启动之前,会先进入其对应的AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调中,解析传入的want参数,获取`instanceKey`自定义参数。根据业务需要通过AbilityStage的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)生命周期回调返回一个字符串Key标识。[如果返回的Key对应一个已启动的UIAbility](mission-management-launch-type.md#fig14520125175314),则会将之前的UIAbility拉回前台并获焦,而不创建新的实例,否则创建新的实例并启动。
```ts
import AbilityStage from '@ohos.app.ability.AbilityStage';
......@@ -132,19 +126,24 @@ specified启动模式为指定实例模式,针对一些特殊场景使用(
export default class MyAbilityStage extends AbilityStage {
onAcceptWant(want): string {
// 在被调用方的AbilityStage中,针对启动模式为specified的UIAbility返回一个UIAbility实例对应的一个Key值
// 当前示例指的是module1 Module的FuncAbility
if (want.abilityName === 'FuncAbility') {
// 当前示例指的是module1 Module的SpecifiedAbility
if (want.abilityName === 'SpecifiedAbility') {
// 返回的字符串Key标识为自定义拼接的字符串内容
return `FuncAbilityInstance_${want.parameters.instanceKey}`;
return `SpecifiedAbilityInstance_${want.parameters.instanceKey}`;
}
return '';
}
}
```
> **说明:**
>
> 1. 应用的UIAbility实例已创建,该UIAbility配置为指定实例模式,再次调用[startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability)方法启动该UIAbility实例,且[AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md)的[onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant)回调匹配到一个已创建的UIAbility实例。由于启动的还是原来的UIAbility实例,并未重新创建一个新的UIAbility实例,此时再次启动该UIAbility时,只会进入该UIAbility的[onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant)回调,不会进入其[onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate)和[onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate)生命周期回调。
> 2. DevEco Studio默认工程中未自动生成AbilityStage,AbilityStage文件的创建请参见[AbilityStage组件容器](abilitystage.md)。
例如在文档应用中,可以对不同的文档实例内容绑定不同的Key值。当每次新建文档的时候,可以传入不同的新Key值(如可以将文件的路径作为一个Key标识),此时AbilityStage中启动UIAbility时都会创建一个新的UIAbility实例;当新建的文档保存之后,回到桌面,或者新打开一个已保存的文档,回到桌面,此时再次打开该已保存的文档,此时AbilityStage中再次启动该UIAbility时,打开的仍然是之前原来已保存的文档界面。
以如下步骤所示进行举例说明。
1. 打开文件A,对应启动一个新的UIAbility实例,例如启动“UIAbility实例1”。
......
......@@ -12,7 +12,7 @@
## Want的类型
- **显式Want**:在启动Ability时指定了abilityName和bundleName的Want称为显式Want。
当有明确处理请求的对象时,通过提供目标Ability所在应用的Bundle名称信息(bundleName),并在Want内指定abilityName便可启动目标Ability。显式Want通常用于在当前应用开发中启动某个已知的Ability。参数说明参见[Want参数说明](want-overview.md#Want参数说明)
当有明确处理请求的对象时,通过提供目标Ability所在应用的Bundle名称信息(bundleName),并在Want内指定abilityName便可启动目标Ability。显式Want通常用于在当前应用开发中启动某个已知的Ability。
```ts
let wantInfo = {
......@@ -22,7 +22,7 @@
}
```
- **隐式Want**:在启动UIAbility时未指定abilityName的Want称为隐式Want。
- **隐式Want**:在启动Ability时未指定abilityName的Want称为隐式Want。
当请求处理的对象不明确时,希望在当前应用中使用其他应用提供的某个能力(通过[skills标签](../quick-start/module-configuration-file.md#skills标签)定义),而不关心提供该能力的具体应用,可以使用隐式Want。例如使用隐式Want描述需要打开一个链接的请求,而不关心通过具体哪个应用打开,系统将匹配声明支持该请求的所有应用。
......@@ -47,18 +47,3 @@
> - 调用方传入的want参数中不带有abilityName和bundleName,则不允许通过隐式Want启动所有应用的ServiceExtensionAbility。
>
> - 调用方传入的want参数中带有bundleName,则允许使用startServiceExtensionAbility()方法隐式Want启动ServiceExtensionAbility,默认返回优先级最高的ServiceExtensionAbility,如果优先级相同,返回第一个。
## Want参数说明
| 名称 | 读写属性 | 类型 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | -------- |
| deviceId | 只读 | string | 否 | 表示目标Ability所在设备ID。如果未设置该字段,则表明本设备。 |
| bundleName | 只读 | string | 否 | 表示目标Ability所在应用名称。 |
| moduleName | 只读 | string | 否 | 表示目标Ability所属的模块名称。 |
| abilityName | 只读 | string | 否 | 表示目标Ability名称。如果未设置该字段,则该Want为隐式。如果在Want中同时指定了bundleName,moduleName和abilityName,则Want可以直接匹配到指定的Ability。 |
| uri | 只读 | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在Want中指定了uri,则Want将匹配指定的Uri信息,包括scheme,&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)所示。 |
......@@ -191,7 +191,7 @@ currentSession.on('playNext', () => {
});
console.log("调用AudioPlayer.play方法");
// 设置播放状态
let time = (new Data()).getTime();
let time = (new Date()).getTime();
currentSession.setAVPlaybackState({state: avSession.PlaybackState.PLAYBACK_STATE_PLAY, position: {elapsedTime: 0, updateTime: time}, bufferedTime:2000}).then(() => {
console.info('setAVPlaybackState successfully');
}).catch((err) => {
......@@ -286,7 +286,7 @@ currentSession.off('outputDeviceChange');
// 去激活session并销毁对象
currentSession.deactivate().then(() => {
currentSession.destory();
currentSession.destroy();
});
```
......
......@@ -91,7 +91,9 @@ struct MyComponent {
- 支持多个实例:一个组件中可以定义多个标有@Prop的属性;
- 创建自定义组件时将值传递给@Prop变量进行初始化:在创建组件的新实例时,必须初始化所有@Prop变量,不支持在组件内部进行初始化。
> **说明:** @Prop修饰的变量不能在组件内部进行初始化。
> **说明:**
>
> @Prop修饰的变量不能在组件内部进行初始化。
**示例:**
......@@ -158,7 +160,9 @@ struct CountDownComponent {
- 双向通信:子组件对@Link变量的更改将同步修改父组件中的@State变量;
- 创建自定义组件时需要将变量的引用传递给@Link变量,在创建组件的新实例时,必须使用命名参数初始化所有@Link变量。@Link变量可以使用@State变量或@Link变量的引用进行初始化,@State变量可以通过`'$'`操作符创建引用。
> **说明:** @Link修饰的变量不能在组件内部进行初始化。
> **说明:**
>
> @Link修饰的变量不能在组件内部进行初始化。
**简单类型示例:**
......@@ -395,7 +399,9 @@ struct ViewB {
@Provide作为数据的提供方,可以更新其子孙节点的数据,并触发页面渲染。@Consume在感知到@Provide数据的更新后,会触发当前自定义组件的重新渲染。
> **说明:** 使用@Provide和@Consume时应避免循环引用导致死循环。
> **说明:**
>
> 使用@Provide和@Consume时应避免循环引用导致死循环。
### @Provide
......
# 应用配置文件概述(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)
Want是对象间信息传递的载体, 可以用于应用组件间的信息传递。 Want的使用场景之一是作为startAbility的参数, 其包含了指定的启动目标, 以及启动时需携带的相关数据, 如bundleName和abilityName字段分别指明目标Ability所在应用的包名以及对应包内的Ability名称。当Ability A需要启动Ability B并传入一些数据时, 可使用Want作为载体将这些数据传递给Ability B。
Want是对象间信息传递的载体, 可以用于应用组件间的信息传递。 Want的使用场景之一是作为startAbility的参数, 其包含了指定的启动目标, 以及启动时需携带的相关数据, 如bundleName和abilityName字段分别指明目标Ability所在应用的包名以及对应包内的Ability名称。当UIAbilityA需要启动UIAbilityB并传入一些数据时, 可使用Want作为载体将这些数据传递给UIAbilityB。
> **说明:**
>
......@@ -19,25 +19,25 @@ import Want from '@ohos.app.ability.Want';
| 名称 | 类型 | 必填 | 说明 |
| ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| deviceId | string | 否 | 表示运行指定Ability的设备ID。如果未设置该字段,则表明指定本设备。 |
| bundleName | string | 否 | 表示Bundle名称。 |
| abilityName | string | 否 | 表示待启动的Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| uri | string | 否 | 表示Uri描述。如果在Want中指定了Uri,则Want将匹配指定的Uri信息,包括scheme, schemeSpecificPart, authority和path信息。 |
| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义参考:https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| flags | number | 否 | 表示处理Want的方式。默认传数字,具体参考:[flags说明](js-apis-app-ability-wantConstant.md#wantConstant.Flags)。 |
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-app-ability-wantConstant.md#wantConstant.Action)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<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。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantConstant.Entity) |
| moduleName | string | 否 | 表示待启动的Ability所属的模块(module)。 |
| bundleName | string | 否 | 表示待启动Ability所在的应用Bundle名称。 |
| moduleName | string | 否 | 表示待启动的Ability所属的模块名称。 |
| abilityName | string | 否 | 表示待启动Ability名称。如果在Want中该字段同时指定了BundleName和AbilityName,则Want可以直接匹配到指定的Ability。AbilityName需要在一个应用的范围内保证唯一。 |
| [action](js-apis-app-ability-wantConstant.md#wantConstant.Action) | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。隐式Want定义及匹配规则请参见[显式Want与隐式Want匹配规则](application-models/explicit-implicit-want-mappings.md) |
| [entities](js-apis-app-ability-wantConstant.md#wantConstant.Entity) | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器)。在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。 |
| uri | string | 否 | 表示携带的数据,一般配合type使用,指明待处理的数据类型。如果在Want中指定了uri,则Want将匹配指定的Uri信息,包括`scheme``schemeSpecificPart``authority``path`信息。 |
| type | string | 否 | 表示MIME type类型描述,打开文件的类型,主要用于文管打开文件。比如:"text/xml" 、 "image/*"等,MIME定义请参见https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com。 |
| parameters | {[key: string]: any} | 否 | 表示WantParams描述,由开发者自行决定传入的键值对。默认会携带以下key值:<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。 |
| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | 否 | 表示处理Want的方式。默认传数字。<br />例如通过wantConstant.Flags.FLAG_ABILITY_CONTINUATION表示是否以设备间迁移方式启动Ability。 |
**示例:**
- 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
- 基础用法(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。
```ts
let want = {
"deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"bundleName": "com.example.myapplication",
"abilityName": "FuncAbility",
"moduleName": "entry" // moduleName非必选
};
this.context.startAbility(want, (error) => {
......@@ -46,13 +46,13 @@ import Want from '@ohos.app.ability.Want';
})
```
- 通过自定字段传递数据, 以下为当前支持类型。(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)
- 通过自定字段传递数据, 以下为当前支持类型(在UIAbility对象中调用,其中示例中的context为UIAbility的上下文对象)。
* 字符串(String)
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForString: "str",
},
......@@ -61,8 +61,8 @@ import Want from '@ohos.app.ability.Want';
* 数字(Number)
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForInt: 100,
keyForDouble: 99.99,
......@@ -72,8 +72,8 @@ import Want from '@ohos.app.ability.Want';
* 布尔(Boolean)
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForBool: true,
},
......@@ -82,8 +82,8 @@ import Want from '@ohos.app.ability.Want';
* 对象(Object)
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForObject: {
keyForObjectString: "str",
......@@ -97,8 +97,8 @@ import Want from '@ohos.app.ability.Want';
* 数组(Array)
```ts
let want = {
bundleName: "com.example.demo",
abilityName: "com.example.demo.MainAbility",
bundleName: "com.example.myapplication",
abilityName: "FuncAbility",
parameters: {
keyForArrayString: ["str1", "str2", "str3"],
keyForArrayInt: [100, 200, 300, 400],
......@@ -109,30 +109,29 @@ import Want from '@ohos.app.ability.Want';
```
* 文件描述符(FD)
```ts
import fileio from '@ohos.fileio';
let fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
import fileio from '@ohos.fileio';
let fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
let want = {
"deviceId": "", // deviceId为空表示本设备
"bundleName": "com.example.myapplication",
"abilityName": "FuncAbility",
"moduleName": "entry", // moduleName非必选
"parameters": {
"keyFd":{"type":"FD", "value":fd}
}
let want = {
"deviceId": "", // deviceId为空表示本设备
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"moduleName": "entry", // moduleName非必选
"parameters": {
"keyFd":{"type":"FD", "value":fd}
}
};
this.context.startAbility(want, (error) => {
// 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability
console.log("error.code = " + error.code)
})
};
this.context.startAbility(want, (error) => {
// 显式拉起Ability,通过bundleName、abilityName和moduleName可以唯一确定一个Ability
console.log("error.code = " + error.code)
})
```
- 更多详细说明和示例请参见: [应用模型](../../application-models/Readme-CN.md)的信息传递载体Want
<!--no_check-->
......@@ -48,20 +48,17 @@ createFormBindingData(obj?: Object | string): FormBindingData
**示例:**
```ts
import featureAbility from '@ohos.ability.featureAbility';
import fileio from '@ohos.fileio';
let context=featureAbility.getContext();
context.getOrCreateLocalDir((err,data)=>{
let path=data+"/xxx.jpg";
let fd = fileio.openSync(path);
import fs from '@ohos.file.fs';
import formBindingData from '@ohos.app.form.formBindingData';
try {
let fd = fs.openSync('/path/to/form.png')
let obj = {
"temperature": "21°",
"formImages": {"image": fd}
"formImages": { "image": fd }
};
try {
formBindingData.createFormBindingData(obj);
} catch (error) {
console.log(`catch err->${JSON.stringify(err)}`);
}
})
formBindingData.createFormBindingData(obj);
} catch (error) {
console.log(`catch error, code: ${error.code}, message: ${error.message})`);
}
```
\ No newline at end of file
......@@ -33,7 +33,7 @@ onAddForm(want: Want): formBindingData.FormBindingData
| 参数名 | 类型 | 必填 | 说明 |
| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-application-want.md) | 是 | 当前ExtensionAbility相关的Want类型信息,包括卡片ID、卡片名称、卡片样式等。这些卡片信息必须作为持久数据进行管理,以便后续更新和删除卡片。 |
| want | [Want](js-apis-application-want.md) | 是 | 当前卡片相关的Want类型信息,包括卡片ID、卡片名称、卡片样式等。这些卡片信息必须作为持久数据进行管理,以便后续更新和删除卡片。 |
**返回值:**
......@@ -45,17 +45,19 @@ onAddForm(want: Want): formBindingData.FormBindingData
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm(want) {
console.log('FormExtensionAbility onAddForm, want:' + want.abilityName);
let dataObj1 = {
temperature:"11c",
"time":"11:00"
temperature: "11c",
"time": "11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
}
};
```
## onCastToNormalForm
......@@ -75,11 +77,13 @@ onCastToNormalForm(formId: string): void
**示例:**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onCastToNormalForm(formId) {
console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId);
}
}
};
```
## onUpdateForm
......@@ -99,17 +103,24 @@ onUpdateForm(formId: string): void
**示例:**
```ts
import formBindingData from '@ohos.app.form.formBindingData'
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onUpdateForm(formId) {
console.log('FormExtensionAbility onUpdateForm, formId:' + formId);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
this.context.updateForm(formId, obj2).then((data)=>{
let obj2 = formBindingData.createFormBindingData({
temperature: "22c",
time: "22:00"
});
formProvider.updateForm(formId, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
}
}
console.error('Operation updateForm failed. Cause: ' + error);
});
}
};
```
## onChangeFormVisibility
......@@ -129,21 +140,28 @@ onChangeFormVisibility(newStatus: { [key: string]: number }): void
**示例:**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData'
import formProvider from '@ohos.app.form.formProvider';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onChangeFormVisibility(newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
for (let key in newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]);
this.context.updateForm(key, obj2).then((data)=>{
console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus);
let obj2 = formBindingData.createFormBindingData({
temperature: "22c",
time: "22:00"
});
for (let key in newStatus) {
console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]);
formProvider.updateForm(key, obj2).then((data) => {
console.log('FormExtensionAbility context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);
});
}
}
}
};
```
## onFormEvent
......@@ -164,11 +182,13 @@ onFormEvent(formId: string, message: string): void
**示例:**
```ts
export default class MyFormExtension extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
}
}
};
```
## onRemoveForm
......@@ -188,11 +208,13 @@ onRemoveForm(formId: string): void
**示例:**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onRemoveForm(formId) {
console.log('FormExtensionAbility onRemoveForm, formId:' + formId);
}
}
};
```
## onConfigurationUpdate
......@@ -212,11 +234,13 @@ onConfigurationUpdate(newConfig: Configuration): void;
**示例:**
```ts
class MyFormExtensionAbility extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onConfigurationUpdate(config) {
console.log('onConfigurationUpdate, config:' + JSON.stringify(config));
}
}
};
```
## onAcquireFormState
......@@ -236,13 +260,15 @@ onAcquireFormState?(want: Want): formInfo.FormState;
**示例:**
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formInfo from '@ohos.app.form.formInfo';
class MyFormExtensionAbility extends FormExtensionAbility {
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAcquireFormState(want) {
console.log('FormExtensionAbility onAcquireFormState, want:' + want);
return formInfo.FormState.UNKNOWN;
}
}
};
```
## onShareForm
......@@ -270,14 +296,16 @@ onShareForm?(formId: string): { [key: string]: any }
**示例:**
```ts
class MyFormExtensionAbility extends FormExtensionAbility {
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onShareForm(formId) {
console.log('FormExtensionAbility onShareForm, formId:' + formId);
let wantParams = {
"temperature":"20",
"time":"2022-8-8 09:59",
"temperature": "20",
"time": "2022-8-8 09:59",
};
return wantParams;
}
}
};
```
\ No newline at end of file
# @ohos.app.form.formInfo (FormInfo)
# @ohos.app.form.formInfo (formInfo)
FormInfo模块提供对卡片的相关卡片信息和状态进行设置和查询的能力
formInfo模块提供了卡片信息和状态等相关类型和枚举
> **说明:**
>
......@@ -30,11 +30,11 @@ import formInfo from '@ohos.app.form.formInfo';
| colorMode | [ColorMode](#colormode) | 是 | 否 | 卡片颜色模式。 |
| isDefault | boolean | 是 | 否 | 卡片是否是默认卡片。 |
| updateEnabled | boolean | 是 | 否 | 卡片是否使能更新。 |
| formVisibleNotify | string | 是 | 否 | 卡片是否使能可见通知。 |
| formVisibleNotify | boolean | 是 | 否 | 卡片是否使能可见通知。 |
| relatedBundleName | string | 是 | 否 | 卡片所属的相关联Bundle名称。 |
| scheduledUpdateTime | string | 是 | 否 | 卡片更新时间。 |
| formConfigAbility | string | 是 | 否 | 卡片配置ability。指定长按卡片弹出的选择框内,编辑选项所对应的ability。 |
| updateDuration | string | 是 | 否 | 卡片更新周期。 |
| updateDuration | number | 是 | 否 | 卡片更新周期。 |
| defaultDimension | number | 是 | 否 | 表示卡片规格 |
| supportDimensions | Array&lt;number&gt; | 是 | 否 | 卡片支持的规格。具体可选规格参考[FormDimension](#formdimension) |
| customizeData | {[key: string]: [value: string]} | 是 | 否 | 卡片用户数据。 |
......@@ -100,8 +100,8 @@ import formInfo from '@ohos.app.form.formInfo';
| WIDTH_KEY | "ohos.extra.param.key.form_width" | 卡片宽度。 |
| HEIGHT_KEY | "ohos.extra.param.key.form_height" | 卡片高度。 |
| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | 临时卡片。 |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称 |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。<br/>**系统接口**: 此接口为系统接口。 |
| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | ability名称 |
| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | 设备标识。 |
| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | 指示指定要获取的捆绑Bundle名称的键。 |
## FormDimension
......@@ -127,7 +127,7 @@ import formInfo from '@ohos.app.form.formInfo';
| 名称 | 说明 |
| ----------- | ------------ |
| moduleName | 仅保留moduleName与提供值相符的卡片信息。 |
| moduleName | 选填。仅保留moduleName与提供值相符的卡片信息。未填写时则不通过moduleName进行过滤。 |
## VisibilityType
......
# FormExtensionContext
FormExtensionContext模块是FormExtension的上下文环境,继承自ExtensionContext。
FormExtensionContext模块是FormExtensionAbility的上下文环境,继承自ExtensionContext。
FormExtensionContext模块提供FormExtension具有的接口和能力。
FormExtensionContext模块提供FormExtensionAbility具有的接口和能力。
> **说明:**
>
......@@ -11,23 +11,24 @@ FormExtensionContext模块提供FormExtension具有的接口和能力。
## 使用说明
在使用FormExtensionContext的功能前,需要通过FormExtension获取。
在使用FormExtensionContext的功能前,需要通过FormExtensionAbility获取。
```ts
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
import formBindingData from '@ohos.app.form.formBindingData';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onAddForm() {
let formContext = this.context; // 获取FormExtensionContext
// ...
let dataObj1 = {
temperature:"11c",
"time":"11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
}
onAddForm(want) {
let formContext = this.context; // 获取FormExtensionContext
// ...
let dataObj1 = {
temperature: "11c",
"time": "11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
};
```
## startAbility
......@@ -50,23 +51,29 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void
**示例:**
```ts
var want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want, (error, data) => {
if (error) {
console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error));
} else {
console.log(`FormExtensionContext startAbility success`);
}
})
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
// 当触发卡片message事件时,执行startAbility
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
let want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
parameters: {
"message": message
}
};
this.context.startAbility(want, (error, data) => {
if (error) {
console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error));
} else {
console.log('FormExtensionContext startAbility success');
}
});
}
};
```
## startAbility
......@@ -89,24 +96,30 @@ startAbility(want: Want): Promise&lt;void&gt;
| 类型 | 说明 |
| ------------ | ---------------------------------- |
| Promise&lt;void&lt; | 无返回结果的Promise对象。 |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**示例:**
```ts
var want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
action: "action1",
entities: ["entity1"],
type: "MIMETYPE",
uri: "key={true,true,false}",
parameters: {}
}
this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
console.info("StartAbility failed");
});
import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility';
export default class MyFormExtensionAbility extends FormExtensionAbility {
onFormEvent(formId, message) {
// 当触发卡片message事件时,执行startAbility
console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message);
let want = {
deviceId: "",
bundleName: "com.example.formstartability",
abilityName: "MainAbility",
parameters: {
"message": message
}
};
this.context.startAbility(want).then(() => {
console.info("StartAbility Success");
}).catch((error) => {
console.info("StartAbility failed");
});
}
};
```
\ No newline at end of file
......@@ -70,7 +70,7 @@ Not found.
**可能原因**
在调用删除数据库、数据查询、数据删除等接口时未找到相关数据,可能原因如下。
在调用删除数据库、数据查询、数据同步等接口时未找到相关数据,可能原因如下。
1. 删除数据库操作时,数据库不存在或已删除。
2. 数据库数据查询操作时,相关数据不存在或已删除。
3. 数据库数据同步操作时,数据库不存在或已删除。
......
......@@ -18,6 +18,8 @@
进行权限校验的开发步骤为:
1. 获取调用者的身份标识:tokenId。
> **说明:**<br>
> 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。
2. 待校验的权限名:ohos.permission.PERMISSION。
3. 使用verifyAccessToken接口对当前调用者进行权限校验。
4. 根据权限校验结果采取对应的措施。
......@@ -42,5 +44,3 @@
}
```
> **说明:**
> 获取访问者身份标识tokenId的方法 getCallingTokenId 可参考[API参考](../reference/apis/js-apis-rpc.md)。
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册