提交 9b042a61 编写于 作者: S sienna1128

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

......@@ -22,15 +22,16 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **1000**.|
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(bundleName? : string): Promise<number>; | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses a promise to return the result.|
| function setBundleGroup(bundleName : string, newGroup: GroupType, callback: AsyncCallback>boolean>): void | Sets the group for the application specified by **bundleName**. This API uses an asynchronous callback to return the result.|
| function setBundleGroup(bundleName : string, newGroup : GroupType): Promise>boolean>; | Sets the group for the application specified by **bundleName**. This API uses a promise to return the result.|
| function registerGroupCallBack(callback: Callback>BundleActiveGroupCallbackInfo>, callback: AsyncCallback>boolean>): void | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.|
| function registerGroupCallBack(callback: Callback>BundleActiveGroupCallbackInfo>): Promise>boolean>; | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses a promise to return the result.|
| function registerGroupCallBack(groupCallback: Callback>BundleActiveGroupCallbackInfo>, callback: AsyncCallback>boolean>): void | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.|
| function registerGroupCallBack(groupCallback: Callback>BundleActiveGroupCallbackInfo>): Promise>boolean>; | Registers a callback for application group changes. When an application group of the user changes, the change is returned to all applications that have registered the callback. This API uses a promise to return the result.|
| function unRegisterGroupCallBack(callback: AsyncCallback>boolean>): void | Deregisters the callback for application group changes. This API uses an asynchronous callback to return the result.|
| function unRegisterGroupCallBack(): Promise>boolean>; | Deregisters the callback for application group changes. This API uses a promise to return the result.|
......
# USB Service Development
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
## When to Use
In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
## APIs
The USB service provides the following functions: query of USB device list, bulk data transfer, control transfer, and access permission management.
The following table lists the USB APIs currently available. For details, see the [API Reference](../reference/apis/js-apis-usb.md).
**Table 1** Open USB APIs
......@@ -16,12 +16,12 @@ The following table lists the USB APIs currently available. For details, see the
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| hasRight(deviceName: string): boolean | Checks whether the user, for example, the application or system, has the device access permissions. The value **true** is returned if the user has the device access permissions; the value **false** is returned otherwise. |
| requestRight(deviceName: string): Promise\<boolean> | Requests the temporary permission for a given application to access the USB device. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by **getDevices()**. |
| connectDevice(device: USBDevice): Readonly\<USBDevicePipe> | Connects to the USB device based on the device information returned by `getDevices()`. |
| getDevices(): Array<Readonly\<USBDevice>> | Obtains the USB device list. |
| setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | Sets the USB device configuration. |
| setInterface(pipe: USBDevicePipe, iface: USBInterface): number | Sets a USB interface. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number | Claims a USB interface. |
| bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise\<number> | Performs bulk transfer. |
| closePipe(pipe: USBDevicePipe): number | Closes a USB device pipe. |
| releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number | Releases a USB interface. |
| getFileDescriptor(pipe: USBDevicePipe): number | Obtains the file descriptor. |
......@@ -30,7 +30,7 @@ The following table lists the USB APIs currently available. For details, see the
## How to Develop
You can set a USB device as a host to connect to a device for data transfer. The development procedure is as follows:
You can set a USB device as the USB host to connect to other USB devices for data transfer. The development procedure is as follows:
1. Obtain the USB device list.
......@@ -113,7 +113,7 @@ You can set a USB device as a host to connect to a device for data transfer. The
Claim the corresponding interface from deviceList.
interface1 must be one present in the device configuration.
*/
usb.claimInterface(pipe , interface1, true);
usb.claimInterface(pipe, interface1, true);
```
4. Perform data transfer.
......
# FAQs
- [Ability Framework Development](faqs-ability.md)
- [Data Management Development](faqs-data-management.md)
- [File Management Development](faqs-file-management.md)
- [Graphics and Image Development](faqs-graphics.md)
- [hdc_std Command Usage](faqs-ide.md)
- [IDE Usage](faqs-hdc-std.md)
- [ArkUI (JavaScript) Development](faqs-ui-js.md)
- [ArkUI (eTS) Development](faqs-ui-ets.md)
- [Graphics and Image Development](faqs-graphics.md)
......@@ -8,6 +13,7 @@
- [Data Management Development](faqs-data-management.md)
- [Device Management Development](faqs-device-management.md)
- [Native API Usage](faqs-native.md)
- [Network and Connection Development](faqs-connectivity.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md)
- [Development Board](faqs-development-board.md)
# Network and Connection Development
## What are the data formats supported by extraData in an HTTP request?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
**extraData** indicates additional data in an HTTP request. It varies depending on the HTTP request method.
- If the HTTP request uses a POST or PUT method, **extraData** serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, **extraData** serves as a supplement to the HTTP request parameters and will be added to the URL when the request is sent.
- If you pass in a string object, **extraData** contains the string encoded on your own.
## What does error code 28 mean for an HTTP request?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a libcurl library operation timeout. For details, see any HTTP status code description available.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## What does error code 6 mean for the response of \@ohos.net.http.d.ts?
Applicable to: OpenHarmony SDK 3.2.3.5
Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
# hdc_std Command Usage
## What are the commands commonly used for log management?
Applicable to: OpenHarmony SDK 3.2.2.5
- Clearing logs: hdc_std shell hilog -r
- Increasing the buffer size to 20 MB: hdc_std shell hilog -G 20M
- Capturing logs: hdc_std shell hilog &gt; log.txt
## What should I do to avoid log flow control?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
- Disabling log flow control: hdc_std shell hilog -Q pidoff
- Disabling the privacy flag: hdc_std shell hilog -p off
- Increasing the log buffer to 200 MB: hdc_std shell hilog -G 200M
- Enabling the log function of the specific domain (that is, disabling the global log function): hdc_std shell hilog –b D –D 0xd0xxxxx
After performing the preceding operations, restart the DevEco Studio.
## Is HiLog or Console recommended for log printing? How do I set the domain if HiLog is used?
Applicable to: OpenHarmony SDK 3.2.2.5
[HiLog](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md) is recommended for an application to print logs. For details about domain setting, see [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-hilog.md#hilogisloggable).
## What is the maximum length of a log record when HiLog is used? Is it configurable?
Applicable to: OpenHarmony SDK 3.2.2.5
The maximum length of a log record is 1,024 characters, and it is not changeable.
## What should I do if a HAP package cannot be opened after being installed on the development board using the IDE?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Check whether the SDK version is consistent with the system version on the development board. You are advised to use the SDK version and system version that are released on the same day.
## How do I upload files using an hdc command?
Applicable to: OpenHarmony SDK 3.2.2.5
Run the **hdc_std file send** command.
## How do I prevent the screen of the RK3568 development board from turning off?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Run the **hdc_std shell "power-shell setmode 602"** command.
## How do I start an ability using an hdc command?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Run the **hdc_std shell aa start -a AbilityName -b bundleName -m moduleName** command.
# IDE Usage
## What should do if the error message "npm ERR! code SELF_SIGNED_CERT_IN_CHAIN" is displayed?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
1. Run **npm config set strict-ssl=false** on the DevEco Studio terminal.
2. Run the **npm install** on the DevEco Studio terminal.
## After manual updating of the DevEco Studio SDK, the error message "Cannot find module 'xxx\ets\x.x.x.x\build-tools\ets-loader\node_modules\webpack\bin\webpack.js'" is displayed during HAP building. What should I do?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
1. Run **npm install** in the **ets\x.x.x.x\build-tools\ets-loader** directory of the SDK.
2. Run **npm install** in the **js\x.x.x.x\build-tools\ace-loader** directory of the SDK.
3. Perform HAP building again.
......@@ -187,7 +187,7 @@
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -185,7 +185,7 @@
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -181,7 +181,7 @@
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
......
......@@ -146,6 +146,7 @@
- [@ohos.privacyManager](js-apis-privacyManager.md)
- [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md)
- [@system.cipher](js-apis-system-cipher.md)
- Data Management
......
......@@ -484,9 +484,9 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a
## bundleState.getRecentlyUsedModules<sup>9+</sup>
getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
getRecentlyUsedModules(callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
Obtains the number of FA usage records specified by **maxNum**. This API uses an asynchronous callback to return the records sorted by time (most recent first).
This API uses an asynchronous callback to return at most 1000 records sorted by time (most recent first).
**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO
......@@ -498,13 +498,12 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| maxNum | number | No | Maximum number of returned records. The maximum and default value is **1000**. If this parameter is not specified, **1000** is used. |
| callback | AsyncCallback&lt;Array&lt;[BundleActiveModuleInfo](#bundleactivemoduleinfo9)&gt;&gt; | Yes | Callback used to return the result.|
**Example**
```js
bundleState.getRecentlyUsedModules(1000,(err, res) => {
bundleState.getRecentlyUsedModules((err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -513,11 +512,33 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback result ' + JSON.stringify(res[i]));
}
}
}
});
```
// Invocation when maxNum is not passed
bundleState.getRecentlyUsedModules((err, res) => {
## bundleState.getRecentlyUsedModules<sup>9+</sup>
getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
Obtains the number of FA usage records specified by **maxNum**. This API uses an asynchronous callback to return the records sorted by time (most recent first).
**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO
**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| maxNum | number | Yes | Maximum number of returned records. The maximum and default value is **1000**.|
| callback | AsyncCallback&lt;Array&lt;[BundleActiveModuleInfo](#bundleactivemoduleinfo9)&gt;&gt; | Yes | Callback used to return the result.|
**Example**
```js
bundleState.getRecentlyUsedModules(1000,(err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -526,7 +547,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback result ' + JSON.stringify(res[i]));
}
}
}
});
```
......@@ -574,9 +595,9 @@ bundleState.queryAppUsagePriorityGroup().then( res => {
## bundleState.queryAppUsagePriorityGroup<sup>9+</sup>
queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void
queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void
Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.
Queries the priority group of the current application . This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO
......@@ -588,23 +609,44 @@ Queries the priority group of the application specified by **bundleName**. If **
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------------------------------------- |
| bundleName | string | No | Bundle name of the target application. If this parameter is not specified, the priority group of the current application is queried.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the result. |
**Example**
```javascript
// Callback with bundleName
let bundleName = "com.ohos.camera";
bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => {
bundleState.queryAppUsagePriorityGroup((err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
}
});
// Callback without bundleName
bundleState.queryAppUsagePriorityGroup((err, res) => {
```
## bundleState.queryAppUsagePriorityGroup<sup>9+</sup>
queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback&lt;number&gt;): void
Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO
**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------------------------------------- |
| bundleName | string | Yes | Bundle name of the target application.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback used to return the result. |
**Example**
```javascript
let bundleName = "com.ohos.camera";
bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
......@@ -688,7 +730,7 @@ bundleState.setBundleGroup(bundleName, newGroup, (err) => {
## bundleState.registerGroupCallBack<sup>9+</sup>
registerGroupCallBack(callback: Callback&lt;BundleActiveGroupCallbackInfo&gt;): Promise&lt;void&gt;
registerGroupCallBack(groupCallback: Callback&lt;BundleActiveGroupCallbackInfo&gt;): Promise&lt;void&gt;
Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses a promise to return the result.
......@@ -730,7 +772,7 @@ bundleState.registerGroupCallBack(onBundleGroupChanged).then( () => {
## bundleState.registerGroupCallBack<sup>9+</sup>
registerGroupCallBack(callback: Callback&lt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&lt;void&gt;): void
registerGroupCallBack(groupCallback: Callback&lt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&lt;void&gt;): void
Registers a callback for application group changes. When an application group of the user changes, a **[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)** instance is returned to all applications that have registered the callback. This API uses an asynchronous callback to return the result.
......@@ -1034,20 +1076,6 @@ Provides the usage duration information of applications.
| infosBeginTime | number | No | Time logged in the first application usage record in the **BundleActiveInfo** object.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
| infosEndTime | number | No | Time logged in the last application usage record in the **BundleActiveInfo** object.<br>This API is defined but not implemented in OpenHarmony 3.1 Release. It will be available for use in OpenHarmony 3.1 MR.|
### merge
merge(toMerge: BundleStateInfo): void
Merges the application usage information that has the same bundle name.
**System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | -------------- |
| toMerge | [BundleStateInfo](#bundlestateinfo) | Yes | Application usage information to merge.|
## BundleActiveState
Provides information about an application event.
......
......@@ -26,6 +26,7 @@ Obtains the localized script for the specified language.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------------ | ------- | ---- | ---------------- |
| language | string | Yes | Specified language. |
......@@ -33,6 +34,7 @@ Obtains the localized script for the specified language.
| sentenceCase | boolean | No | Whether to use sentence case for the localized script.|
**Return value**
| Type | Description |
| ------ | ------------- |
| string | Localized script for the specified language.|
......@@ -53,6 +55,7 @@ Obtains the localized script for the specified country.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------------ | ------- | ---- | ---------------- |
| country | string | Yes | Specified country. |
......@@ -60,6 +63,7 @@ Obtains the localized script for the specified country.
| sentenceCase | boolean | No | Whether to use sentence case for the localized script.|
**Return value**
| Type | Description |
| ------ | ------------- |
| string | Localized script for the specified country.|
......@@ -80,11 +84,13 @@ Checks whether the localized script for the specified language is displayed from
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Description |
| ------ | ------ | ------- |
| locale | string | Locale ID.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the localized script is displayed from right to left; returns **false** otherwise.|
......@@ -105,6 +111,7 @@ Obtains the system language.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------- |
| string | System language ID.|
......@@ -128,11 +135,13 @@ This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Description |
| -------- | ------ | ----- |
| language | string | Language ID.|
**Return value**
| Type | Description |
| ------- | ------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
......@@ -143,7 +152,7 @@ This is a system API.
```
## i18n.getSystemLanguages
## i18n.getSystemLanguages<sup>9+</sup>
getSystemLanguages(): Array&lt;string&gt;
......@@ -154,6 +163,7 @@ Obtains the list of system languages.
**System API**: This is a system API and cannot be called by third-party applications.
**Return value**
| Type | Description |
| ------------------- | ------------ |
| Array&lt;string&gt; | List of the IDs of system languages.|
......@@ -164,7 +174,7 @@ Obtains the list of system languages.
```
## i18n.getSystemCountries
## i18n.getSystemCountries<sup>9+</sup>
getSystemCountries(language: string): Array&lt;string&gt;
......@@ -175,11 +185,13 @@ Obtains the list of countries and regions supported for the specified language.
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Description |
| -------- | ------ | ----- |
| language | string | Language ID.|
**Return value**
| Type | Description |
| ------------------- | ------------ |
| Array&lt;string&gt; | List of the IDs of the countries and regions supported for the specified language.|
......@@ -199,6 +211,7 @@ Obtains the system region.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------- |
| string | System region ID.|
......@@ -222,11 +235,13 @@ This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Description |
| ------ | ------ | ----- |
| region | string | Region ID.|
**Return value**
| Type | Description |
| ------- | ------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
......@@ -246,6 +261,7 @@ Obtains the system locale.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------- |
| string | System locale ID.|
......@@ -269,11 +285,13 @@ This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Description |
| ------ | ------ | --------------- |
| locale | string | System locale ID, for example, **zh-CN**.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
......@@ -284,7 +302,7 @@ This is a system API.
```
## i18n.isSuggested
## i18n.isSuggested<sup>9+</sup>
isSuggested(language: string, region?: string): boolean
......@@ -295,12 +313,14 @@ Checks whether the system language matches the specified region.
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------- |
| language | string | Yes | Valid language ID, for example, **zh**.|
| region | string | No | Valid region ID, for example, **CN**. |
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the system language matches the specified region; returns **false** otherwise.|
......@@ -320,12 +340,14 @@ Obtains a **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------------------- |
| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. |
| type | string | No | Valid calendar type. Currently, the valid types are as follows: **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic\_civil**, **islamic\_tbla**, **islamic\_umalqura**, **japanese**, and **persian**. If this parameter is left unspecified, the default calendar type of the specified locale is used.|
**Return value**
| Type | Description |
| ---------------------- | ----- |
| [Calendar](#calendar8) | **Calendar** object.|
......@@ -348,6 +370,7 @@ Sets the date for this **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ----------------- |
| date | Date | Yes | Date to be set for the **Calendar** object.|
......@@ -369,6 +392,7 @@ Sets the date and time for this **Calendar** object. The value is represented by
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| time | number | Yes | Number of milliseconds that have elapsed since the Unix epoch.|
......@@ -389,6 +413,7 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------ |
| year | number | Yes | Year to set. |
......@@ -414,6 +439,7 @@ Sets the time zone of this **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------------------- |
| timezone | string | Yes | Time zone, for example, **Asia/Shanghai**.|
......@@ -434,6 +460,7 @@ Obtains the time zone of this **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ---------- |
| string | Time zone of the **Calendar** object.|
......@@ -455,6 +482,7 @@ Obtains the start day of a week for this **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | --------------------- |
| number | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
......@@ -475,6 +503,7 @@ Sets the start day of a week for this **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | --------------------- |
| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.|
......@@ -495,6 +524,7 @@ Obtains the minimum number of days in the first week of a year.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------------ |
| number | Minimum number of days in the first week of a year.|
......@@ -515,6 +545,7 @@ Sets the minimum number of days in the first week of a year.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ------------ |
| value | number | No | Minimum number of days in the first week of a year.|
......@@ -535,11 +566,13 @@ Obtains the value of the specified field in the **Calendar** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| field | string | Yes | Value of the specified field in the **Calendar** object. Currently, a valid field can be any of the following: **era**, **year**, **month**, **week\_of\_year**, **week\_of\_month**, **date**, **day\_of\_year**, **day\_of\_week**, **day\_of\_week\_in\_month**, **hour**, **hour\_of\_day**, **minute**, **second**, **millisecond**, **zone\_offset**, **dst\_offset**, **year\_woy**, **dow\_local**, **extended\_year**, **julian\_day**, **milliseconds\_in\_day**, **is\_leap\_month**.|
**Return value**
| Type | Description |
| ------ | ---------------------------------------- |
| number | Value of the specified field. For example, if the year in the internal date of this **Calendar** object is **1990**, the **get("year")** function will return **1990**.|
......@@ -561,11 +594,13 @@ Obtains the name of the **Calendar** object displayed for the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------------------- |
| locale | string | Yes | Locale for which the name of the **Calendar** object is displayed. For example, if **locale** is **en-US**, the name of the Buddhist calendar will be **Buddhist Calendar**.|
**Return value**
| Type | Description |
| ------ | ------------------- |
| string | Name of the **Calendar** object displayed for the specified locale.|
......@@ -586,11 +621,13 @@ Checks whether the specified date in this **Calendar** object is a weekend.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ---------------------------------------- |
| date | Date | No | Specified date in this **Calendar** object. If this parameter is left unspecified, the system checks whether the current date in the **Calendar** object is a weekend.|
**Return value**
| Type | Description |
| ------- | ----------------------------------- |
| boolean | Returns **true** if the date is a weekend; returns **false** if the date is a weekday.|
......@@ -620,7 +657,7 @@ Parameters
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------- |
| country | string | Yes | Country or region to which the phone number to be formatted belongs.|
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. |
| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. |
**Example**
```js
......@@ -637,11 +674,13 @@ Checks whether the format of the specified phone number is valid.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | --------- |
| number | string | Yes | Phone number to be checked.|
**Return value**
| Type | Description |
| ------- | ------------------------------------- |
| boolean | Returns **true** if the phone number format is valid; returns **false** otherwise.|
......@@ -662,11 +701,13 @@ Formats a phone number.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- |
| number | string | Yes | Phone number to be formatted.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | Formatted phone number.|
......@@ -686,12 +727,14 @@ Obtains the home location of a phone number.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- |
| number | string | Yes | Phone number.|
| locale | string | Yes | Locale ID.|
**Return value**
| Type | Description |
| ------ | ---------- |
| string | Home location of the phone number.|
......@@ -703,7 +746,7 @@ Obtains the home location of a phone number.
```
## PhoneNumberFormatOptions<sup>8+</sup>
## PhoneNumberFormatOptions<sup>9+</sup>
Defines the options for this PhoneNumberFormat object.
......@@ -726,18 +769,24 @@ Defines the measurement unit information.
| measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**,&nbsp;**US**, or&nbsp;**UK**.|
## Util<sup>8+</sup>
## Util<sup>(deprecated)</sup>
### unitConvert<sup>8+</sup>
### unitConvert<sup>(deprecated)</sup>
static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string
Converts one measurement unit into another and formats the unit based on the specified locale and style.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [unitConvert](#unitconvert9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------------------------------------- |
| fromUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted. |
......@@ -747,37 +796,10 @@ Converts one measurement unit into another and formats the unit based on the spe
| style | string | No | Style used for formatting. The value can be **long**, **short**, or **narrow**.|
**Return value**
| Type | Description |
| ------ | ----------------------- |
| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.|
**Example**
```js
i18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long");
```
### getDateOrder<sup>9+</sup>
static getDateOrder(locale: string): string
Obtains the sequence of the year, month, and day in the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------------------------------------- |
| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. |
**Return value**
| Type | Description |
| ------ | ----------------------- |
| string | Sequence of the year, month, and day.|
**Example**
```
i18n.Util.getDateOrder("zh-CN");
```
| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.|
## getInstance<sup>8+</sup>
......@@ -789,11 +811,13 @@ Creates an **IndexUtil** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------- |
| locale | string | No | A string containing locale information, including the language, optional script, and region.|
**Return value**
| Type | Description |
| ------------------------ | --------------------- |
| [IndexUtil](#indexutil8) | **IndexUtil** object mapping to the specified locale.|
......@@ -816,6 +840,7 @@ Obtains the index list for this **locale** object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------------------- | ------------------ |
| Array&lt;string&gt; | Index list for this **locale** object.|
......@@ -836,6 +861,7 @@ Adds the index of the new **locale** object to the index list.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region.|
......@@ -856,11 +882,13 @@ Obtains the index of a text object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ |
| text | string | Yes | **text** object whose index is to be obtained.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | Index of the **text** object.|
......@@ -872,223 +900,250 @@ Obtains the index of a text object.
```
## Character<sup>8+</sup>
## Character<sup>(deprecated)</sup>
### isDigit<sup>8+</sup>
### isDigit<sup>(deprecated)</sup>
static isDigit(char: string): boolean
Checks whether the input character string is composed of digits.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isDigit](#isdigit9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.|
**Example**
```js
var isdigit = i18n.Character.isDigit("1"); // Return true.
```
### isSpaceChar<sup>8+</sup>
### isSpaceChar<sup>(deprecated)</sup>
static isSpaceChar(char: string): boolean
Checks whether the input character is a space.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isSpaceChar](#isspacechar9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a space; returns **false** otherwise.|
**Example**
```js
var isspacechar = i18n.Character.isSpaceChar("a"); // Return false.
```
### isWhitespace<sup>8+</sup>
### isWhitespace<sup>(deprecated)</sup>
static isWhitespace(char: string): boolean
Checks whether the input character is a white space.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isWhitespace](#iswhitespace9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.|
**Example**
```js
var isspacechar = i18n.Character.isSpaceChar("a"); // Return false.
```
### isRTL<sup>8+</sup>
### isRTL<sup>(deprecated)</sup>
static isRTL(char: string): boolean
Checks whether the input character is of the right to left (RTL) language.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isRTL](#isrtl9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.|
**Example**
```js
var isrtl = i18n.Character.isRTL("a"); // Return false.
```
### isIdeograph<sup>8+</sup>
### isIdeograph<sup>(deprecated)</sup>
static isIdeograph(char: string): boolean
Checks whether the input character is an ideographic character.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isIdeograph](#isideograph9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.|
**Example**
```js
var isideograph = i18n.Character.isIdeograph("a"); // Return false.
```
### isLetter<sup>8+</sup>
### isLetter<sup>(deprecated)</sup>
static isLetter(char: string): boolean
Checks whether the input character is a letter.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isLetter](#isletter9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.|
**Example**
```js
var isletter = i18n.Character.isLetter("a"); // Return true.
```
### isLowerCase<sup>8+</sup>
### isLowerCase<sup>(deprecated)</sup>
static isLowerCase(char: string): boolean
Checks whether the input character is a lowercase letter.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isLowerCase](#islowercase9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.|
**Example**
```js
var islowercase = i18n.Character.isLowerCase("a"); // Return true.
```
### isUpperCase<sup>8+</sup>
### isUpperCase<sup>(deprecated)</sup>
static isUpperCase(char: string): boolean
Checks whether the input character is an uppercase letter.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [isUpperCase](#isuppercase9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.|
**Example**
```js
var isuppercase = i18n.Character.isUpperCase("a"); // Return false.
```
### getType<sup>8+</sup>
### getType<sup>(deprecated)</sup>
static getType(char: string): string
Obtains the type of the input character string.
> **NOTE**
> This API is deprecated since API version 9. You are advised to use [getType](#gettype9) instead.
>
> This API is supported since API version 8.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | Type of the input character.|
**Example**
```js
var type = i18n.Character.getType("a");
```
## i18n.getLineInstance<sup>8+</sup>
......@@ -1100,11 +1155,13 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------------------- |
| locale | string | Yes | Valid locale value, for example, **zh-Hans-CN**. The [BreakIterator](#breakiterator8) object segments text according to the rules of the specified locale.|
**Return value**
| Type | Description |
| -------------------------------- | ----------- |
| [BreakIterator](#breakiterator8) | [BreakIterator](#breakiterator8) object used for text segmentation.|
......@@ -1127,6 +1184,7 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----------------------- |
| text | string | Yes | Text to be processed by the **BreakIterator** object.|
......@@ -1147,6 +1205,7 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ---------------------- |
| string | Text being processed by the **BreakIterator** object.|
......@@ -1168,6 +1227,7 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | --------------------------- |
| number | Position of the **BreakIterator** object in the text being processed.|
......@@ -1189,6 +1249,7 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ----------------- |
| number | Offset to the first text boundary of the processed text.|
......@@ -1210,6 +1271,7 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Offset of the last text boundary of the processed text.|
......@@ -1231,11 +1293,13 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| index | number | No | Number of text boundaries by which the [BreakIterator](#breakiterator8) object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as **1**.|
**Return value**
| Type | Description |
| ------ | ---------------------------------------- |
| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved by the specified number of text boundaries. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.|
......@@ -1259,6 +1323,7 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ---------------------------------------- |
| number | Position of the [BreakIterator](#breakiterator8) object in the text after it is moved to the previous text boundary. The value **-1** is returned if the position of the [BreakIterator](#breakiterator8) object is outside of the processed text after it is moved by the specified number of text boundaries.|
......@@ -1282,11 +1347,13 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------------------------------------- |
| offset | number | Yes | Offset to the position before the text boundary to which the [BreakIterator](#breakiterator8) object is moved.|
**Return value**
| Type | Description |
| ------ | ---------------------------------------- |
| number | The value **-1** is returned if the text boundary to which the [BreakIterator](#breakiterator8) object is moved is outside of the processed text.|
......@@ -1310,11 +1377,13 @@ Checks whether the position specified by the offset is a text boundary. If **tru
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----------- |
| offset | number | Yes | Position to check.|
**Return value**
| Type | Description |
| ------- | ------------------------------- |
| boolean | Returns **true** if the position specified by the offset is a text boundary; returns **false** otherwise.|
......@@ -1337,6 +1406,7 @@ Checks whether the 24-hour clock is used.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the 24-hour clock is used; returns **false** otherwise.|
......@@ -1358,11 +1428,13 @@ Sets the 24-hour clock.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------- | ---- | ---------------------------------------- |
| option | boolean | Yes | Whether to enable the 24-hour clock. The value **true** means to enable the 24-hour clock, and the value **false** means the opposite.|
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the 24-hour clock is enabled; returns **false** otherwise.|
......@@ -1385,12 +1457,14 @@ Adds a preferred language to the specified position on the preferred language li
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ---------- |
| language | string | Yes | Preferred language to add. |
| index | number | No | Position to which the preferred language is added.|
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the preferred language is successfully added; returns **false** otherwise.|
......@@ -1415,11 +1489,13 @@ Deletes a preferred language from the specified position on the preferred langua
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | --------------------- |
| index | number | Yes | Position of the preferred language to delete.|
**Return value**
| Type | Description |
| ------- | ----------------------------- |
| boolean | Returns **true** if the preferred language is deleted; returns **false** otherwise.|
......@@ -1441,6 +1517,7 @@ Obtains the list of preferred languages.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------------------- | --------- |
| Array&lt;string&gt; | List of preferred languages.|
......@@ -1460,6 +1537,7 @@ Obtains the first language in the preferred language list.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | -------------- |
| string | First language in the preferred language list.|
......@@ -1479,6 +1557,7 @@ Obtains the preferred language of an application.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | -------------- |
| string | Preferred language of the application.|
......@@ -1498,11 +1577,13 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| zondID | string | No | Time zone ID.|
**Return value**
| Type | Description |
| -------- | ------------ |
| TimeZone | **TimeZone** object corresponding to the time zone ID.|
......@@ -1525,6 +1606,7 @@ Obtains the ID of the specified **TimeZone** object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Time zone ID corresponding to the **TimeZone** object.|
......@@ -1545,12 +1627,14 @@ Obtains the representation of a **TimeZone** object in the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------- |
| locale | string | No | System locale ID. |
| isDST | boolean | No | Whether to consider DST when obtaining the representation of the **TimeZone** object.|
**Return value**
| Type | Description |
| ------ | ------------- |
| string | Representation of the **TimeZone** object in the specified locale.|
......@@ -1571,6 +1655,7 @@ Obtains the offset between the time zone represented by a **TimeZone** object an
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------------------- |
| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone.|
......@@ -1591,6 +1676,7 @@ Obtains the offset between the time zone represented by a **TimeZone** object an
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ----------------------- |
| number | Offset between the time zone represented by the **TimeZone** object and the UTC time zone at a certain time point.|
......@@ -1610,6 +1696,7 @@ Obtains the list of time zone IDs supported by the system.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ----------------------- |
| Array&lt;string&gt; | List of time zone IDs supported by the system.|
......@@ -1629,6 +1716,7 @@ Obtains the list of time zone city IDs supported by the system.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ----------------------- |
| Array&lt;string&gt; | List of time zone city IDs supported by the system.|
......@@ -1648,12 +1736,14 @@ Obtains the localized display of a time zone city in the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| cityID | string | Yes | Time zone city ID.|
| locale | string | Yes | Locale ID.|
**Return value**
| Type | Description |
| ------ | ----------------------- |
| string | Localized display of the time zone city in the specified locale.|
......@@ -1673,11 +1763,13 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| cityID | string | Yes | Time zone city ID.|
**Return value**
| Type | Description |
| ------ | ----------------------- |
| TimeZone | **TimeZone** object corresponding to the specified time zone city ID.|
......@@ -1700,11 +1792,13 @@ This is a system API.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- |
| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.|
**Return value**
| Type | Description |
| -------- | ------------ |
| boolean | Result indicating whether the local digit switch is successfully set. The value **true** indicates that the local digit switch is successfully set, and the value **false** indicates the opposite.|
......@@ -1724,6 +1818,7 @@ Checks whether the local digit switch is turned on.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| -------- | ------------ |
| boolean | Result indicating whether the local digit switch is turned on. The value **true** indicates that the local digit switch is turned on, and the value **false** indicates the opposite.|
......@@ -1745,6 +1840,7 @@ Obtains a list of IDs supported by the **Transliterator** object.
**System capability**: SystemCapability.Global.I18n
**Return value**
| Type | Description |
| ------ | ------------ |
| string[] | List of IDs supported by the **Transliterator** object.|
......@@ -1764,11 +1860,13 @@ Creates a **Transliterator** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------- |
| id | string | Yes | ID supported by the **Transliterator** object. |
**Return value**
| Type | Description |
| ------ | ------------- |
| [Transliterator](#transliterator9) | **Transliterator** object.|
......@@ -1788,11 +1886,13 @@ Converts the input string from the source format to the target format.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------- |
| text | string | Yes | Input string. |
**Return value**
| Type | Description |
| ------ | ------------- |
| string | Target string.|
......@@ -1802,3 +1902,298 @@ Converts the input string from the source format to the target format.
var transliterator = i18n.Transliterator.getInstance("Any-Latn");
transliterator.transform ("China");
```
## Unicode<sup>9+</sup>
### isDigit<sup>9+</sup>
static isDigit(char: string): boolean
Checks whether the input character string is composed of digits.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a digit; returns **false** otherwise.|
**Example**
```js
var isdigit = i18n.Unicode.isDigit("1"); // Return true.
```
### isSpaceChar<sup>9+</sup>
static isSpaceChar(char: string): boolean
Checks whether the input character is a space.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a space; returns **false** otherwise.|
**Example**
```js
var isspacechar = i18n.Unicode.isSpaceChar("a"); // Return false.
```
### isWhitespace<sup>9+</sup>
static isWhitespace(char: string): boolean
Checks whether the input character is a white space.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Returns **true** if the input character is a white space; returns **false** otherwise.|
**Example**
```js
var iswhitespace = i18n.Unicode.isWhitespace("a"); // Return false.
```
### isRTL<sup>9+</sup>
static isRTL(char: string): boolean
Checks whether the input character is of the right to left (RTL) language.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is of the RTL language; returns **false** otherwise.|
**Example**
```js
var isrtl = i18n.Unicode.isRTL("a"); // Return false.
```
### isIdeograph<sup>9+</sup>
static isIdeograph(char: string): boolean
Checks whether the input character is an ideographic character.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an ideographic character; returns **false** otherwise.|
**Example**
```js
var isideograph = i18n.Unicode.isIdeograph("a"); // Return false.
```
### isLetter<sup>9+</sup>
static isLetter(char: string): boolean
Checks whether the input character is a letter.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| boolean | Returns **true** if the input character is a letter; returns **false** otherwise.|
**Example**
```js
var isletter = i18n.Unicode.isLetter("a"); // Return true.
```
### isLowerCase<sup>9+</sup>
static isLowerCase(char: string): boolean
Checks whether the input character is a lowercase letter.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is a lowercase letter; returns **false** otherwise.|
**Example**
```js
var islowercase = i18n.Unicode.isLowerCase("a"); // Return true.
```
### isUpperCase<sup>9+</sup>
static isUpperCase(char: string): boolean
Checks whether the input character is an uppercase letter.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the input character is an uppercase letter; returns **false** otherwise.|
**Example**
```js
var isuppercase = i18n.Unicode.isUpperCase("a"); // Return false.
```
### getType<sup>9+</sup>
static getType(char: string): string
Obtains the type of the input character string.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ----- |
| char | string | Yes | Input character.|
**Return value**
| Type | Description |
| ------ | ----------- |
| string | Type of the input character.|
**Example**
```js
var type = i18n.Unicode.getType("a");
```
## I18NUtil<sup>9+</sup>
### unitConvert<sup>9+</sup>
static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string
Converts one measurement unit into another and formats the unit based on the specified locale and style.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------------------------------------- |
| fromUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted. |
| toUnit | [UnitInfo](#unitinfo8) | Yes | Measurement unit to be converted to. |
| value | number | Yes | Value of the measurement unit to be converted. |
| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. |
| style | string | No | Style used for formatting. The value can be **long**, **short**, or **narrow**.|
**Return value**
| Type | Description |
| ------ | ----------------------- |
| string | Character string obtained after formatting based on the measurement unit specified by **toUnit**.|
**Example**
```js
i18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long");
```
### getDateOrder<sup>9+</sup>
static getDateOrder(locale: string): string
Obtains the sequence of the year, month, and day in the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------------------------- |
| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**.|
**Return value**
| Type | Description |
| ------ | ------------------- |
| string | Sequence of the year, month, and day.|
**Example**
```js
i18n.I18NUtil.getDateOrder("zh-CN");
```
......@@ -60,6 +60,7 @@ Creates a Locale object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------- | ---- | ---------------------------- |
| locale | string | Yes | A string containing locale information, including the language, optional script, and region.|
......@@ -80,6 +81,7 @@ Converts locale information to a string.
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ------ | ----------- |
| string | String containing locale information.|
......@@ -100,6 +102,7 @@ Maximizes information of the **Locale** object. If the script and locale informa
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ----------------- | ---------- |
| [Locale](#locale) | **Locale** object with the maximized information.|
......@@ -120,6 +123,7 @@ Minimizes information of the **Locale** object. If the script and locale informa
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ----------------- | ---------- |
| [Locale](#locale) | **Locale** object with the minimized information.|
......@@ -131,7 +135,7 @@ Minimizes information of the **Locale** object. If the script and locale informa
```
## LocaleOptions
## LocaleOptions<sup>9+</sup>
Represents the locale options.
......@@ -173,6 +177,7 @@ Creates a **DateTimeOptions** object for the specified locale.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
......@@ -199,11 +204,13 @@ Formats the specified date and time.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ---- | ---- | ------- |
| date | Date | Yes | Date and time to be formatted.|
**Return Value**
| Type | Description |
| ------ | ------------ |
| string | A string containing the formatted date and time.|
......@@ -225,12 +232,14 @@ Formats the specified date range.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---- | ---- | -------- |
| startDate | Date | Yes | Start date and time to be formatted.|
| endDate | Date | Yes | End date and time to be formatted.|
**Return Value**
| Type | Description |
| ------ | -------------- |
| string | A string containing the formatted date and time range.|
......@@ -253,6 +262,7 @@ Obtains the formatting options for **DateTimeFormat** object.
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ----------------------------------- | ----------------------------- |
| [DateTimeOptions](#datetimeoptions) | Formatting options for **DateTimeFormat** objects.|
......@@ -264,7 +274,7 @@ Obtains the formatting options for **DateTimeFormat** object.
```
## DateTimeOptions
## DateTimeOptions<sup>9+</sup>
Provides the options for the **DateTimeFormat** object.
......@@ -339,11 +349,13 @@ Formats a number.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---- |
| number | number | Yes | Number to be formatted.|
**Return Value**
| Type | Description |
| ------ | ---------- |
| string | Formatted number.|
......@@ -365,6 +377,7 @@ Obtains the options of the **NumberFormat** object.
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ------------------------------- | --------------------------- |
| [NumberOptions](#numberoptions) | Formatting options for **NumberFormat** objects.|
......@@ -377,7 +390,7 @@ Obtains the options of the **NumberFormat** object.
```
## NumberOptions
## NumberOptions<sup>9+</sup>
Provides the device capability.
......@@ -453,12 +466,14 @@ Compares two strings based on the sorting policy of the **Collator** object.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------------ |
| first | string | Yes | First string to compare. |
| second | string | Yes | Second string to compare.|
**Return Value**
| Type | Description |
| ------ | ---------------------------------------- |
| number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.|
......@@ -479,6 +494,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ----------------------------------- | ----------------- |
| [CollatorOptions](#collatoroptions) | Properties of the **Collator** object.|
......@@ -490,7 +506,7 @@ Returns properties reflecting the locale and collation options of a **Collator**
```
## CollatorOptions<sup>8+</sup><a name=collatoroptions></a>
## CollatorOptions<sup>9+</sup>
Represents the properties of a **Collator** object.
......@@ -553,11 +569,13 @@ Obtains a string that represents the singular-plural type of the specified numbe
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ |
| n | number | Yes | Number for which the singular-plural type is to be obtained.|
**Return Value**
| Type | Description |
| ------ | ---------------------------------------- |
| string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.|
......@@ -569,7 +587,7 @@ Obtains a string that represents the singular-plural type of the specified numbe
```
## PluralRulesOptions<sup>8+</sup><a name=pluralrulesoptions></a>
## PluralRulesOptions<sup>9+</sup>
Represents the properties of a **PluralRules** object.
......@@ -611,7 +629,8 @@ Creates a **RelativeTimeFormat** object.
**System capability**: SystemCapability.Global.I18n
Parameters
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------- |
| locale | string \| Array&lt;string&gt; | Yes | A string containing locale information, including the language, optional script, and region.|
......@@ -632,12 +651,14 @@ Formats the value and unit based on the specified locale and formatting options.
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| value | number | Yes | Value to format. |
| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.|
**Return Value**
| Type | Description |
| ------ | ---------- |
| string | Relative time after formatting.|
......@@ -658,12 +679,14 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt
**System capability**: SystemCapability.Global.I18n
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| value | number | Yes | Value to format. |
| unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.|
**Return Value**
| Type | Description |
| ------------------- | --------------------------- |
| Array&lt;object&gt; | An array of **RelativeTimeFormat** objects in parts.|
......@@ -684,6 +707,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
**System capability**: SystemCapability.Global.I18n
**Return Value**
| Type | Description |
| ---------------------------------------- | --------------------------------- |
| [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions) | Formatting options for **RelativeTimeFormat** objects.|
......@@ -695,7 +719,7 @@ Obtains the formatting options for **RelativeTimeFormat** objects.
```
## RelativeTimeFormatInputOptions<sup>8+</sup><a name=relativetimeformatinputoptions></a>
## RelativeTimeFormatInputOptions<sup>9+</sup>
Represents the properties of a **RelativeTimeFormat** object.
......
......@@ -7,7 +7,7 @@ There are two types of updates: SD card update and over the air (OTA) update.
- The SD card update depends on the update packages and SD cards.
- The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer.
> **Note:**
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
......@@ -239,7 +239,7 @@ var versionDigestInfo = {
// Options of the description file
var descriptionOptions = {
format: DescriptionFormat.STANDARD, // Standard format
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
}
......@@ -282,7 +282,7 @@ var versionDigestInfo = {
// Options of the description file
var descriptionOptions = {
format: DescriptionFormat.STANDARD, // Standard format
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
}
......@@ -369,7 +369,7 @@ Obtains the description file of the current version. This API uses an asynchrono
```ts
// Options of the description file
var descriptionOptions = {
format: DescriptionFormat.STANDARD, // Standard format
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
}
......@@ -406,7 +406,7 @@ Obtains the description file of the current version. This API uses a promise to
```ts
// Options of the description file
var descriptionOptions = {
format: DescriptionFormat.STANDARD, // Standard format
format: update.DescriptionFormat.STANDARD, // Standard format
language: "zh-cn" // Chinese
}
......@@ -1580,7 +1580,7 @@ Represents an update file.
## UpgradeTaskCallback
### (eventInfo: [EventInfo](#eventinfo)): void
(eventInfo: EventInfo): void
Represents an event callback.
......
......@@ -94,14 +94,16 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| device | [USBDevice](#usbdevice) | Yes| USB device information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| device | [USBDevice](#usbdevice) | Yes| USB device information.|
**Return value**
| Type| Description|
| -------- | -------- |
| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
| Type| Description|
| -------- | -------- |
| Readonly&lt;[USBDevicePipe](#usbdevicepipe)&gt; | USB device pipe for data transfer.|
**Example**
......@@ -119,14 +121,16 @@ Checks whether the application has the permission to access the device.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name to set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise.|
| Type| Description|
| -------- | -------- |
| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.|
**Example**
......@@ -140,19 +144,21 @@ console.log(bool);
requestRight(deviceName: string): Promise&lt;boolean&gt;
Requests the temporary permission for the application to access the USB device.
Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result.
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name to set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceName | string | Yes| Device name.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Returns **true** if the temporary device access permissions are granted; returns **false** otherwise.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted, and the value **false** indicates the opposite.|
**Example**
......@@ -174,16 +180,18 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.|
| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.|
| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise.|
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully claimed, and an error code indicates the opposite.|
**Example**
......@@ -203,15 +211,17 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise.|
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully released, and an error code indicates the opposite.|
**Example**
......@@ -231,15 +241,17 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| config | [USBConfig](#usbconfig) | Yes| USB configuration to set.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| config | [USBConfig](#usbconfig) | Yes| USB configuration to set.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise.|
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB configuration is successfully set, and an error code indicates the opposite.|
**Example**
......@@ -266,9 +278,10 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
| iface | [USBInterface](#usbinterface) | Yes | USB interface to set. |
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise.|
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB interface is successfully set, and an error code indicates the opposite.|
**Example**
......@@ -289,14 +302,15 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type| Description|
| -------- | -------- |
| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.|
| Uint8Array | The return value is the raw USB descriptor if the operation is successful, or **undefined** if the operation has failed.|
**Example**
......@@ -315,15 +329,16 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | Returns the file descriptor of the USB device if the operation is successful; returns **-1** otherwise.|
| number | The return value is the file descriptor of the USB device if the operation is successful, or **-1** if the operation has failed.|
**Example**
......@@ -342,16 +357,18 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs.|
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
......@@ -372,17 +389,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.|
| buffer | Uint8Array | Yes| Buffer for writing or reading data.|
| timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.|
| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.|
| buffer | Uint8Array | Yes| Buffer for writing or reading data.|
| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs.|
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.|
**Example**
......@@ -406,14 +425,16 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi
**System capability**: SystemCapability.USB.USBManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise.|
| Type| Description|
| -------- | -------- |
| number | The value **0** indicates that the USB device pipe is closed successfully, and an error code indicates the opposite.|
**Example**
......@@ -498,8 +519,8 @@ Sets the current USB function list in Device mode.
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------ |
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.|
**Example**
......@@ -601,8 +622,8 @@ Sets the role types supported by a specified port, which can be **powerRole** (f
**Return value**
| Type | Description |
| ------------------ | -------------- |
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.|
**Example**
......
# Facial Authentication
The **userIAM.faceAuth** module provides APIs for face enrollment.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs provided by this module are system APIs.
## Modules to Import
```js
import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
```
## FaceAuthManager
Provides APIs for facial authentication management.
### constructor
constructor()
A constructor used to create a **FaceAuthManager** object.
**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth
**Return value**
| Type | Description |
| ---------------------- | -------------------- |
| [FaceAuthManager](#faceauthmanager) | **FaceAuthManager** object.|
**Example**
```js
import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
let faceAuthManager = new userIAM_faceAuth.FaceAuthManager()
```
### setSurfaceId
setSurfaceId(surfaceId: string): ResultCode;
Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process.
**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------- | ---- | -------------------------- |
| surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).|
**Return value**
| Type | Description |
| ---------- | ------------------------------------------------------------ |
| [ResultCode](#resultcode) | Operation result code.|
**Example**
```js
import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
let faceAuthManager = new userIAM_faceAuth.FaceAuthManager()
faceAuthManager.setSurfaceId("0");
```
## ResultCode
Enumerates the operation result codes.
**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth
| Name | Default Value| Description |
| ----------------------- | ------ | -------------------- |
| SUCCESS | 0 | The operation is successful. |
| FAIL | 1 | The operation fails. |
......@@ -323,7 +323,7 @@ Then, run the build commands in command line (CLI) mode or hb mode.
--compact-mode compatible with standard build system set to false if we use build.sh as build entrance
--gn-args GN_ARGS specifies gn build arguments, eg: --gn-args="foo="bar" enable=true blah=7"
--keep-ninja-going keeps ninja going until 1000000 jobs fail
--build-only-gn only do gn parse, donot run ninja
--build-only-gn only do gn parse, do not run ninja
--log-level LOG_LEVEL
specifies the log level during compilationyou can select three levels: debug, info and error
--fast-rebuild it will skip prepare, preloader, gn_gen steps so we can enable it only when there is no change
......
......@@ -8,9 +8,9 @@ When adding a module, you must declare its dependencies in **BUILD.gn**. **deps*
![Dependency Types](figure/dependency_types.png)
The dependency between modules can be classified into **desp** (left in the figure above) and **external_deps** (right in the figure above).
The dependency between modules can be classified into **deps** (left in the figure above) and **external_deps** (right in the figure above).
- **desp**: The dependent module to be added belongs to the same part with the current module. For example, module 2 depends on module 1, and both modules 1 and 2 belong to the samp component.
- **deps**: The dependent module to be added belongs to the same part with the current module. For example, module 2 depends on module 1, and both modules 1 and 2 belong to the same component.
- **external_deps**: The dependent module to be added belongs to another component. For example, module 2 depends on module 1, and modules 1 and 2 belong to different components.
......
......@@ -15,27 +15,27 @@ HiSysEvent allows you to query system events by specifying search criteria. For
>
> For details about the **HiSysEventRecord** argument in the **OnQuery()** method of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
**Table 1** Description of the HiSysEvent query API
**Table 1** Description of the HiSysEvent query API
| API| Description|
| -------- | -------- |
| API | Description |
| --- | ----------- |
| int32_t HiSysEventManager::Query(struct QueryArg&amp; arg, std::vector&lt;QueryRule&gt;&amp; rules, std::shared_ptr&lt;HiSysEventQueryCallback&gt; callback) | Queries system events by specifying search criteria such as the time segment, event domain, and event name.<br>Input arguments:<br>- **arg**: event query parameter.<br>- **rules**: rules for event filtering.<br>- **callback**: callback object for event query.<br>Return value:<br>- **0**: Query is successful.<br>- A negative value: Query has failed.|
**Table 2** Description of QueryArg
**Table 2** Description of QueryArg
| Attribute| Description|
| -------- | -------- |
| Attribute | Description |
| --------- | ----------- |
| beginTime | Start time, in the **long long int** format.|
| endTime | End time, in the **long long int** format.|
| maxEvents | Maximum number of returned events, in the **int** format.|
**Table 3** Description of QueryRule
**Table 3** Description of QueryRule
| API| Description|
| -------- | -------- |
| QueryRule(const std::string&amp; domain, const std::vector&lt;std::string&gt;&amp; eventList) | Constructor used to create a **QueryRule** object.<br>Input arguments:<br>- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.<br>- **eventList**: event name list, in the **std::vector&lt;std::string&gt;** format. By default, an empty string indicates that the event names on the list are successfully matched.|
**Table 4** Description of HiSysEventQueryCallback
**Table 4** Description of HiSysEventQueryCallback
| API| Description|
| -------- | -------- |
......@@ -60,7 +60,7 @@ HiSysEvent allows you to query system events by specifying search criteria. For
void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total)
```
Invoke the query API in the corresponding service logic.
Call the query API in the corresponding service logic.
```
HiSysEventManager::Query(struct QueryArg& queryArg,
......@@ -93,7 +93,7 @@ HiSysEvent allows you to query system events by specifying search criteria. For
} // namespace HiviewDFX
} // namespace OHOS
// Invoke the query callback API to obtain system events.
// Call the query callback API to obtain system events.
auto queryCallBack = std::make_shared<HiSysEventToolQuery>();
struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents);
std::vector<QueryRule> rules;
......
......@@ -286,4 +286,4 @@ The following table describes APIs available for obtaining device location infor
Location subsystem
[base_location](https://gitee.com/openharmony/base_location)
[base_location](https://gitee.com/openharmony/base_location/blob/master/README.en.md)
......@@ -6,5 +6,5 @@ The table below lists the APIs changes of the multimodal input subsystem in Open
| Module| Class| Method/Attribute/Enumeration/Constant| Change Type|
|---|---|---|---|
| ohos.multimodalInput.inputMonitor | inputMonitor | off(type:"mouse", receiver?:Callback\<MouseEvent>):void; | Added|
| ohos.multimodalInput.inputMonitor | inputMonitor | on(type:"mouse", receiver:Callback\<MouseEvent>):void; | Added|
| ohos.multimodalInput.inputMonitor | inputMonitor | off(type: "mouse", receiver?: Callback\<MouseEvent>):void; | Added|
| ohos.multimodalInput.inputMonitor | inputMonitor | on(type: "mouse", receiver: Callback\<MouseEvent>):void; | Added|
# 法律声明
**版权所有 (c) 2020-2022 OpenHarmony项目,保留一切权利。**
## 版权许可
OpenHarmony文档的著作权由OpenHarmony项目拥有。
OpenHarmony文档根据知识共享署名4.0 (Creative Commons Attribution 4.0,简称CC BY 4.0)国际公共许可协议进行版权许可。为了方便用户理解,您可以通过访问https://creativecommons.org/licenses/by/4.0/了解CC BY 4.0的概要。CC BY 4.0的完整协议内容您可以访问如下网址获取:https://creativecommons.org/licenses/by/4.0/legalcode。
## 商标声明
OpenHarmony文档不涵盖任何关于开放原子基金会和OpenHarmony项目的商标、名称或标志的许可。未经开放原子开源基金会书面事先明示许可,任何第三方不得以任何形式使用开放原子基金会和OpenHarmony项目的商标、名称或标志。
## 免责声明
OpenHarmony项目会不定期对OpenHarmony文档内容进行更新。
OpenHarmony文档在提供时不附带任何明示或默示的担保。在任何情况下,开放原子开源基金会或版权所有者不对任何人因使用OpenHarmony文档内容而引发的任何直接或间接损失承担责任,不论因何种原因导致或者基于何种法律理论,即使其曾被建议有此种损失的可能性。
......@@ -50,18 +50,41 @@
这个权限还需要在应用首次启动的时候弹窗获取用户授权,可以通过如下代码实现:
```js
// FA模型
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => {
console.info('success: ${data}');
}).catch((error) => {
console.info('failed: ${error}');
})
}
grantPermission();
// Stage模型
import Ability from '@ohos.application.Ability';
let context = null;
function grantPermission() {
class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
let context = this.context;
}
}
let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success: ${data}');
}).catch((error) => {
console.log('failed: ${error}');
});
}
grantPermission();
```
......@@ -73,25 +96,39 @@
以下为创建分布式数据库管理器的代码示例:
```js
// FA模型获取context
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
// Stage模型获取context
import AbilityStage from '@ohos.application.Ability';
let context = null;
class MainAbility extends AbilityStage{
onWindowStageCreate(windowStage){
context = this.context;
}
}
let kvManager;
try {
const kvManagerConfig = {
bundleName: 'com.example.datamanagertest',
userInfo: {
context:context,
userId: '0',
userType: distributedData.UserType.SAME_USER_ID
}
}
distributedData.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
console.log("createKVManager err: " + JSON.stringify(err));
console.log('createKVManager err: ${error}');
return;
}
console.log("createKVManager success");
console.log('createKVManager success');
kvManager = manager;
});
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
console.log('An unexpected error occurred. Error: ${e}');
}
```
......@@ -115,14 +152,14 @@
};
kvManager.getKVStore('storeId', options, function (err, store) {
if (err) {
console.log("getKVStore err: " + JSON.stringify(err));
console.log('getKVStore err: ${err}');
return;
}
console.log("getKVStore success");
console.log('getKVStore success');
kvStore = store;
});
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
console.log('An unexpected error occurred. Error: ${e}');
}
```
......@@ -136,7 +173,7 @@
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
console.log("dataChange callback call data: ${data}");
});
```
......@@ -153,13 +190,13 @@
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) {
console.log("put err: " + JSON.stringify(err));
console.log('put err: ${error}');
return;
}
console.log("put success");
console.log('put success');
});
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
console.log('An unexpected error occurred. Error: ${e}');
}
```
......@@ -176,16 +213,16 @@
try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) {
console.log("put err: " + JSON.stringify(err));
console.log('put err: ${error}');
return;
}
console.log("put success");
console.log('put success');
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
console.log("get success data: " + data);
console.log('get success data: ${data}');
});
});
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
console.log('An unexpected error occurred. Error: ${e}');
}
```
......@@ -204,7 +241,7 @@
let devManager;
// create deviceManager
deviceManager.createDeviceManager("bundleName", (err, value) => {
deviceManager.createDeviceManager('bundleName', (err, value) => {
if (!err) {
devManager = value;
// deviceIds由deviceManager调用getTrustedDeviceListSync方法得到
......@@ -219,7 +256,7 @@
// 1000表示最大延迟时间为1000ms
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
} catch (e) {
console.log("An unexpected error occurred. Error: " + e);
console.log('An unexpected error occurred. Error: ${e}');
}
}
});
......
......@@ -22,15 +22,16 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | 查询当前应用的使用优先级群组。callback形式。 |
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | 查询当前应用的使用优先级群组。promise形式。 |
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | 判断指定Bundle Name的应用当前是否是空闲状态。 |
| function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | 根据maxNum,查询FA使用记录,返回不超过maxNum条FA使用记录,若不填写maxNum参数,则默认maxNum值为1000。 |
| function getRecentlyUsedModules(callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | 查询FA使用记录,返回不超过1000条FA使用记录。 |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | 根据maxNum,查询FA使用记录,返回不超过maxNum条FA使用记录。 maxNum不超过1000|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | 通过指定起始和结束时间查询所有应用的通知次数。 |
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | 通过指定起始和结束时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息。 |
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | 查询当前调用者应用或者指定应用的使用优先级群组。callback形式。 |
| function queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback&lt;number&gt;): void | 查询指定应用的使用优先级群组。callback形式。 |
| function queryAppUsagePriorityGroup(bundleName? : string): Promise&lt;number&gt;; | 查询当前调用者应用或者指定应用的使用优先级群组。promise形式。 |
| function setBundleGroup(bundleName : string, newGroup: GroupType, callback: AsyncCallback&gt;boolean&gt;): void | 给应用名是bundleName的应用分组设置成newGroup,返回设置结果是否成功,以callback形式返回。 |
| function setBundleGroup(bundleName : string, newGroup : GroupType): Promise&gt;boolean&gt;; | 给应用名是bundleName的应用分组设置成newGroup,返回设置结果是否成功,以promise形式返回。 |
| function registerGroupCallBack(callback: Callback&gt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&gt;boolean&gt;): void | 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息,以callback形式返回。 |
| function registerGroupCallBack(callback: Callback&gt;BundleActiveGroupCallbackInfo&gt;): Promise&gt;boolean&gt;; | 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息,以promise形式返回。 |
| function registerGroupCallBack(groupCallback: Callback&gt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&gt;boolean&gt;): void | 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息,以callback形式返回。 |
| function registerGroupCallBack(groupCallback: Callback&gt;BundleActiveGroupCallbackInfo&gt;): Promise&gt;boolean&gt;; | 注册应用分组变化监听回调,返回注册是否成功,当应用分组发生变化时,会给所有已注册的监听者返回回调信息,以promise形式返回。 |
| function unRegisterGroupCallBack(callback: AsyncCallback&gt;boolean&gt;): void | 解除应用分组监听回调,以callback形式返回。 |
| function unRegisterGroupCallBack(): Promise&gt;boolean&gt;; | 解除应用分组监听回调,以promise形式返回。 |
......@@ -325,14 +326,14 @@ import stats from '@ohos.bundleState';
```js
import stats from '@ohos.bundleState'
// 无异步方法promise方式
// 无bundleName异步方法promise方式
stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
});
// 无异步方法callback方式
// 无bundleName异步方法callback方式
stats.queryAppUsagePriorityGroup((err, res) => {
if (err) {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code);
......@@ -340,16 +341,16 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
}
});
// 有异步promise方式
stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
let bundleName = "com.ohos.camera";
// 有bundleName异步promise方式
stats.queryAppUsagePriorityGroup(bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
});
// 有异步方法callback方式
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
// 有bundleName异步方法callback方式
stats.queryAppUsagePriorityGroup(bundleName, (err, res) => {
if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
......
......@@ -12,12 +12,10 @@
**打点接口功能介绍:**
| 接口名 | 描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| write(string eventName, EventType type, object keyValues, AsyncCallback\<void> callback): void | 应用事件异步打点方法,使用callback方式作为异步回调。 |
| write(string eventName, EventType type, object keyValues): Promise\<void> | 应用事件异步打点方法,使用Promise方式作为异步回调。 |
| write(AppEventInfo info, AsyncCallback\<void> callback): void | 支持domain参数的应用事件异步打点方法,使用callback方式作为异步回调。 |
| write(AppEventInfo info): Promise\<void> | 支持domain参数的应用事件异步打点方法,使用Promise方式作为异步回调。 |
| 接口名 | 描述 |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| write(AppEventInfo info, AsyncCallback\<void> callback): void | 应用事件异步打点方法,使用callback方式作为异步回调。 |
| write(AppEventInfo info): Promise\<void> | 应用事件异步打点方法,使用Promise方式作为异步回调。 |
当采用callback作为异步回调时,可以在callback中进行下一步处理。
......@@ -35,7 +33,7 @@
| 接口名 | 描述 |
| -------------------------------------------------- | -------------------- |
| addWatcher(Watcher watcher): AppEventPackageHolder | 新增应用事件订阅者。 |
| addWatcher(Watcher watcher): AppEventPackageHolder | 添加应用事件订阅者。 |
| removeWatcher(Watcher watcher): void | 移除应用事件订阅者。 |
**清理接口功能介绍:**
......@@ -66,7 +64,7 @@
以一次应用事件打点订阅流程为例,说明开发步骤。
1. 新建一个ets应用工程,编辑工程中的“entry > src > main > ets > pages > index.ets” 文件,依次添加三个按钮,以对应用事件打点订阅流程进行模拟。其中,按钮1模拟了应用事件打点的调用,按钮2模拟了新增自动触发回调的事件订阅者的调用,按钮3模拟了移除事件订阅者的调用,完整示例代码如下:
1. 新建一个ets应用工程,编辑工程中的“entry > src > main > ets > pages > index.ets” 文件,依次添加三个按钮,以对应用事件打点订阅流程进行模拟。其中,按钮1模拟了应用事件打点的调用,按钮2模拟了添加自动触发回调的事件订阅者的调用,按钮3模拟了移除事件订阅者的调用,完整示例代码如下:
```ts
import hiAppEvent from '@ohos.hiAppEvent';
......@@ -84,6 +82,7 @@
.fontWeight(FontWeight.Bold)
Button("1 writeTest").onClick(()=>{
// 根据传入的事件参数执行一次应用事件打点
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
......@@ -100,6 +99,7 @@
})
Button("2 addWatcherTest").onClick(()=>{
// 根据传入的订阅参数添加一个应用事件订阅者
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [{ domain: "test_domain" }],
......@@ -109,17 +109,23 @@
timeOut: 2
},
onTrigger: function (curRow, curSize, holder) {
// 返回的holder对象为null表示订阅过程发生异常,因此在记录错误日志后直接返回
if (holder == null) {
console.error("HiAppEvent holder is null");
return;
}
// 设置每次获取的订阅事件包大小阈值为1000字节
holder.setSize(1000);
let eventPkg = null;
// 根据设置阈值大小去获取订阅事件包(返回的事件包对象为null,表示当前订阅数据被全部取出)
while ((eventPkg = holder.takeNext()) != null) {
console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId);
console.info("HiAppEvent eventPkg.row=" + eventPkg.row);
console.info("HiAppEvent eventPkg.size=" + eventPkg.size);
// 对获取的订阅事件包进行解析,并将解析结果打印在Log界面
console.info('HiAppEvent eventPkg.packageId=' + eventPkg.packageId);
console.info('HiAppEvent eventPkg.row=' + eventPkg.row);
console.info('HiAppEvent eventPkg.size=' + eventPkg.size);
// 对订阅事件包中的事件字符串数组进行遍历解析
for (const eventInfo of eventPkg.data) {
console.info("HiAppEvent eventPkg.data=" + eventInfo);
console.info('HiAppEvent eventPkg.data=' + eventInfo);
}
}
}
......@@ -127,6 +133,7 @@
})
Button("3 removeWatcherTest").onClick(()=>{
// 移除指定名称的应用事件订阅者
hiAppEvent.removeWatcher({
name: "watcher1"
})
......@@ -147,7 +154,7 @@
success to write event: 0
```
4. 在应用界面点击按钮2进行新增事件订阅者,再多次点击按钮1进行多次打点。在满足回调任一触发条件(事件数量、事件数据大小、定时时长)后,可以在Log窗口看到回调函数触发后获取到的订阅事件包的日志:
4. 在应用界面点击按钮2进行添加事件订阅者,再多次点击按钮1进行多次打点。在满足回调任一触发条件(事件数量、事件数据大小、定时时长)后,可以在Log窗口看到回调函数触发后获取到的订阅事件包的日志:
```
HiAppEvent eventPkg.packageId=0
......
......@@ -4,24 +4,24 @@
设计自检表详细列举出了在全场景设备设计和开发过程中应当注意的设计规则,这将帮助应用减少用户舆情且提升用户体验的一致性。
自检表的要求范围分为“必选”与“推荐”两类。必选类一般为已总结出的较优解决方案或效果,表示相关设计需要按照此原则统一执行;推荐类指可能受应用品牌风格或业务特殊性影响,可适量做出修改。
自检表的要求范围分为“必须”与“推荐”两个类别。必须类一般为已总结出的较优解决方案或效果,表示相关设计需要按照此原则统一执行;推荐类指可能受应用品牌风格或业务特殊性影响,可适量做出修改。
请参考以下表格范围内提出的要求对应用进行检查。
| **类型** | **条目** | **说明** |
| -------- | ------------------ | ------------------------------------------------------------ |
| 应用架构 | 导航结构 | 在各设备上页面导航结构保持一致(同时出多个设备的UX设计)。 |
| 布局 | 拉通设计 | 拉通各设备的布局设计,保证在不同尺寸和分辨率的设备上能够无错位/不截断/不变形/不过多空白(50%以上)/不过于拥挤(间距小于16vp,明显截断)/无大图大字体地正常显示。 |
| | 响应式设计 | 栅格布局只能占N列以及N列内部的Gutter,不包含N列两侧的Gutter。 |
| | 响应式设计 | 明确标注使用什么类型的栅格、给出在不同断点下栅格三要素取值。 |
| | 响应式设计 | 按容器去对齐栅格,而不是内部子元素对齐栅格。 |
| | 响应式设计 | 栅格除了页面布局设计外,在做局部栅格设计时,需要通过明显方式如颜色等进行标注区分,避免混淆。 |
| | 响应式设计 | 禁止出现标注了栅格但实际没有通过栅格进行布局设计,避免混淆。 |
| | 自适应设计 | 非栅格设计场景下,明确标注自适应布局能力。自适应布局能力有:拉伸、均分、占比、缩放、延伸、隐藏、折行。 |
| 人机交互 | 输入方式 | 需保证在各设备上完整支持触摸、鼠标、触控、键盘、遥控器、摇杆等交互方式,并符合标准定义。 |
| | 交互归一 | 应使用系统提供的控件以达到一致的交互体验。如有定制,需保证在各场景下,不同输入设备上的操作与指南要求一致。需特别注意鼠标行为。 |
| 视觉风格 | 单位 | 用于界面布局的单位应全部使用vp。只针对严格控制元素尺寸的场景使用px。 |
| | 色彩 | 用于色彩的赋值应使用分层参数。推荐支持深色模式,需保证界面在系统切换色彩模式时没有识别性问题。 |
| | 字体 | 使用fp为文字大小单位,需要响应系统大字体模式,确保系统调节字体大小后,界面字体能响应变化大小,并且界面布局没有出现布局错乱问题。 |
| 多态控件 | 支持常用的控件状态 | 确保控件不同状态下的视觉效果没有缺失。控件的常用状态有:正常态、不可用态、点击态、获焦态、激活态、悬停态。 |
\ No newline at end of file
| **类型** | **条目** | **说明** | **类别** |
| -------- | ------------------ | ------------------------------------------------------------ | ------ |
| 应用架构 | 导航结构 | 在各设备上页面导航结构保持一致(同时出多个设备的UX设计)。 | 推荐 |
| 布局 | 拉通设计 | 拉通各设备的布局设计,保证在不同尺寸和分辨率的设备上能够无错位/不截断/不变形/不过多空白(50%以上)/不过于拥挤(间距小于16vp,明显截断)/无大图大字体地正常显示。 | 必须 |
| | 响应式设计 | 栅格布局只能占N列以及N列内部的Gutter,不包含N列两侧的Gutter。 | 必须 |
| | 响应式设计 | 明确标注使用什么类型的栅格、给出在不同断点下栅格三要素取值。 | 推荐 |
| | 响应式设计 | 按容器去对齐栅格,而不是内部子元素对齐栅格。 | 必须 |
| | 响应式设计 | 栅格除了页面布局设计外,在做局部栅格设计时,需要通过明显方式如颜色等进行标注区分,避免混淆。 | 推荐 |
| | 响应式设计 | 禁止出现标注了栅格但实际没有通过栅格进行布局设计,避免混淆。 | 必须 |
| | 自适应设计 | 非栅格设计场景下,明确标注自适应布局能力。自适应布局能力有:拉伸、均分、占比、缩放、延伸、隐藏、折行。 | 推荐 |
| 人机交互 | 输入方式 | 需保证在各设备上完整支持触摸、鼠标、触控、键盘、遥控器、摇杆等交互方式,并符合标准定义。 | 推荐 |
| | 交互归一 | 应使用系统提供的控件以达到一致的交互体验。如有定制,需保证在各场景下,不同输入设备上的操作与指南要求一致。需特别注意鼠标行为。 | 推荐 |
| 视觉风格 | 单位 | 用于界面布局的单位应全部使用vp。只针对严格控制元素尺寸的场景使用px。 | 必须 |
| | 色彩 | 用于色彩的赋值应使用分层参数。推荐支持深色模式,需保证界面在系统切换色彩模式时没有识别性问题。 | 推荐 |
| | 字体 | 使用fp为文字大小单位,需要响应系统大字体模式,确保系统调节字体大小后,界面字体能响应变化大小,并且界面布局没有出现布局错乱问题。 | 必须 |
| 多态控件 | 支持常用的控件状态 | 确保控件不同状态下的视觉效果没有缺失。控件的常用状态有:正常态、不可用态、点击态、获焦态、激活态、悬停态。 | 推荐 |
\ No newline at end of file
......@@ -25,13 +25,4 @@
接下来将依次介绍自适应布局和响应式布局,同时结合实际,通过典型布局场景以及典型页面场景详细介绍两种布局能力的用法。
## 相关实例
针对一次开发,多端部署,有以下相关实例可供参考:
- [`MusicAlbum`:一多音乐专辑主页(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum)
- [`AppMarket`:一多应用市场首页(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket)
- [`AdaptiveCapabilities`:多设备自适应能力(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities)
- [`JsAdaptiveCapabilities`:多设备自适应能力(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/JsAdaptiveCapabilities)
- [一次开发多端部署(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/MultiDeploymentEts)
......@@ -19,6 +19,21 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 开发多设备上同一页面时,建议开发者多使用[自定义组件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ts-component-based-component.md),既可以增加代码的可读性和可维护性,同时也可以尽可能的实现代码复用。
>
> - 本章中涉及的示例代码均可以在[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev)中获取,感兴趣的开发者可以自行下载、运行及查看效果。
> 开发多设备上同一页面时,建议开发者多使用[自定义组件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ts-component-based-component.md),既可以增加代码的可读性和可维护性,同时也可以尽可能的实现代码复用。
## 相关示例
[OpenHarmony应用示例](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev)中提供了如下一多示例,感兴趣的开发者可以自行下载、运行及查看效果。
| 示例名称 | 开发范式 | 简介 |
| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ |
| [页面开发一多能力](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) | 声明式开发范式 | 本章配套的示例代码,包括自适应布局、响应式布局、典型布局场景以及资源文件使用等。 |
| [页面开发一多能力](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/JsAdaptiveCapabilities) | 类Web开发范式 | 本章配套的示例代码,包括自适应布局、响应式布局及资源文件使用等。 |
| [应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/AppMarket) | 声明式开发范式 | 本章配套的示例代码,以应用市场首页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 |
| [音乐专辑页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/MusicAlbum) | 声明式开发范式 | 本章配套的示例代码,以音乐专辑页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 |
| [蔬菜百科首页](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Vegetable) | 声明式开发范式 | 一多示例页面,以蔬菜百科首页为例,演示如何使用一多能力适配多设备(或多窗口尺寸)。 |
| [天气](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather) | 声明式开发范式 | 一多示例应用,以天气应用为例,演示如何使用一多能力实现包含多个页面的应用。 |
......@@ -254,8 +254,7 @@ struct MediaQuerySample {
## 栅格布局
## <sub>栅格</sub>
### 简介
栅格是多设备场景下通用的辅助定位工具,通过将空间分割为有规律的栅格。栅格可以显著降低适配不同屏幕尺寸的设计及开发成本,使得整体设计和开发流程更有秩序和节奏感,同时也保证多设备上应用显示的协调性和一致性,提升用户体验。
......@@ -270,9 +269,6 @@ struct MediaQuerySample {
单个Column的宽度是系统结合Margin、Gutter和Columns自动计算的,不需要也不允许开发者手动配置。
### 栅格布局
栅格布局就是栅格结合了断点,实现栅格布局能力的组件叫栅格组件。在实际使用场景中,可以根据需要配置不同断点下栅格组件中元素占据的列数,同时也可以调整Margin、Gutter、Columns的取值,从而实现不同的布局效果。
| sm断点 | md断点 |
......@@ -353,7 +349,7 @@ struct GridRowSample2 {
// 侧边栏,尺寸变化范围 [100vp, 600vp]
Column(){}.width('100%').backgroundColor('#19000000')
// 内容区,尺寸变化范围 [窗口宽度550vp, 窗口宽度50vp]
// 内容区,尺寸变化范围 [550vp, 50vp]
GridRow({breakpoints: {value: ['100vp', '200vp', '300vp', '400vp', '500vp'],
reference: BreakpointsReference.ComponentSize}}) {
GridCol({span:{xs: 12, sm: 12, md: 12, lg:12, xl: 12, xxl:12}}) {
......@@ -395,7 +391,6 @@ struct GridRowSample2 {
总的来讲,margin在组件外而padding在组件内,开发者可以根据实际需要进行选择及实现目标效果。
**示例3:**
......@@ -729,8 +724,3 @@ struct GridRowSample9 {
如前所述,栅格组件提供了丰富的自定义能力,功能异常灵活和强大。只需要明确栅格在不同断点下的Columns、Margin、Gutter及span等参数,即可确定最终布局,无需关心具体的设备类型及设备状态(如横竖屏)等。栅格可以节约设计团队与开发团队的沟通成本,提升整体开发效率。
## 相关实例
针对栅格断点系统开发,有以下相关实例可供参考:
- [`Weather`:一多天气(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Weather)
......@@ -182,7 +182,7 @@
## 实现页面间的跳转
页面间的导航可以通过页面路由router来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
页面间的导航可以通过[页面路由router](../reference/apis/js-apis-router.md#routerpush)来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
1. 第一个页面跳转到第二个页面。
......
......@@ -181,7 +181,7 @@
## 实现页面间的跳转
页面间的导航可以通过页面路由router来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
页面间的导航可以通过[页面路由router](../reference/apis/js-apis-router.md#routerpush)来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
1. 第一个页面跳转到第二个页面。
......
......@@ -175,7 +175,7 @@
## 实现页面间的跳转
页面间的导航可以通过[页面路由router](../ui/ui-js-building-ui-routes.md)来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
页面间的导航可以通过[页面路由router](../reference/apis/js-apis-router.md#routerpush)来实现。页面路由router根据页面url找到目标页面,从而实现跳转。使用页面路由请导入router模块。
1. 第一个页面跳转到第二个页面。
......
# 用户数据管理
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 该模块从API Version 9开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 导入模块
```js
import userFileManager from '@ohos.filemanagement.userfile_manager';
```
## userFileManager.getUserFileMgr
getUserFileMgr(context: Context): UserFileManager
获取用户数据管理模块的实例,用于访问和修改用户等用户公共媒体数据信息(如音频、视频、图片、文档等)。
**模型约束:** 此接口仅可在Stage模型下使用。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | -------------------------- |
| context | [Context](#../apis/js-apis-Context.md) | 是 | 传入Ability实例的Context。 |
**返回值:**
| 类型 | 说明 |
| ----------------------------- | :---- |
| [UserFileManager](#userfilemanager) | 媒体库实例 |
**示例:**
```ts
const context = getContext(this);
let userFileMgr = userfilemanager.getUserFileMgr(context);
```
## userFileManager.getUserFileMgr
getUserFileMgr(): UserFileManager
获取用户数据管理模块的实例,用于访问和修改用户等用户公共媒体数据信息(如音频、视频、图片、文档等)。
**模型约束:** 此接口仅可在FA模型下使用。
> **说明**: 推荐使用Stage模型接口[UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr)。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值:**
| 类型 | 说明 |
| ----------------------------- | :--------- |
| [UserFileManager](#userfilemanager) | 媒体库实例 |
**示例:**
```js
let userFileMgr = userfilemanager.getUserFileMgr();
```
## UserFileManager
### getPublicDirectory
getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string>): void;
获取系统预设的公共目录,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------ | ---- | ------------------------- |
| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 |
| callback | AsyncCallback&lt;string> | 是 | callback 返回公共目录路径 |
**示例:**
```ts
async function getPublicDirectoryDemoCallback() {
console.info('getPublicDirectoryDemo');
let DIR_CAMERA = directoryType.DIR_CAMERA;
console.info('DIR_CAMERA', DIR_CAMERA);
userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => {
if (dicResult == 'Camera/') {
console.info('mediaLibraryTest : getPublicDirectory passed');
} else {
console.info('mediaLibraryTest : getPublicDirectory failed');
}
});
}
```
### getPublicDirectory
getPublicDirectory(type: DirectoryType): Promise&lt;string>;
获取系统预设的公共目录,使用Promise方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------- | ---- | ------------ |
| type | [DirectoryType](#directorytype) | 是 | 公共目录类型 |
**返回值:**
| 类型 | 说明 |
| ---------------- | ---------------- |
| Promise\<string> | 返回公共目录路径 |
**示例:**
```ts
async function getPublicDirectoryDemoPromise() {
console.info('getPublicDirectoryDemo');
let DIR_CAMERA = directoryType.DIR_CAMERA;
try {
let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA);
console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult);
} catch (err) {
console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err);
}
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType>, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult>): void;
获取文件资源,使用callback方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------ | ---- | ------------------------- |
| type | Array&lt;[MediaType](#mediatype)> | 是 | 媒体类型检索范围 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 |
| callback | AsyncCallback&lt;string> | 是 | callback 返回文件检索结果 |
**示例:**
```ts
async function getFileAssetsDemoCallback() {
console.info('getFileAssets');
let fileKeyObj = userfile_manager.FileKey
let imageType = userfile_manager.MediaType.IMAGE
let fetchOp = {
selections: '',
selectionArgs: [],
};
userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => {
if (fetchFileResult != undefined) {
console.info('fetchFileResult success');
let fileAsset = await fetchFileResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
};
}
})
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions): Promise&lt;FetchFileResult>;
获取文件资源,使用Promise方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------- | ---- | ---------------- |
| type | Array&lt;[MediaType](#mediatype)> | 是 | 媒体类型检索范围 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 文件检索选项 |
**返回值**
| 类型 | 说明 |
| --------------------------- | -------------- |
| Promise&lt;[FetchFileResult](#fetchfileresult)> | 文件数据结果集 |
**示例:**
```ts
async function getFileAssetsDemoPromise() {
console.info('getFileAssets');
let fileKeyObj = userfile_manager.FileKey
let imageType = userfile_manager.MediaType.IMAGE
let fetchOp = {
selections: '',
selectionArgs: [],
};
try {
var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp)
} catch (err) {
console.info('getFileAssets failed, message = ', err);
}
if (fetchFileResult != undefined) {
console.info('fetchFileResult success');
let fileAsset = await fetchFileResult.getFirstObject();
if (fileAsset != undefined) {
console.info("fileAsset.displayName :" + fileAsset.displayName);
};
}
}
```
### on
on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback&lt;void&gt;): void
打开文件管理库变更通知,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| callback | Callback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
```ts
async function onDemo() {
console.info('onDemo')
userFileMgr.on('imageChange', () => {
// image file had changed, do something
});
}
```
### off
off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback&lt;void&gt;): void
关闭文件管理库变更通知,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 媒体类型 <br/>'deviceChange':&nbsp;注册设备变更 <br/>'albumChange':&nbsp;相册变更<br/>'imageChange':&nbsp;图片文件变更<br/>'audioChange': &nbsp;音频文件变更<br/>'videoChange': &nbsp;视频文件变更<br/>'fileChange': &nbsp;文件变更<br/>'remoteFileChange':&nbsp;注册设备上文件变更 |
| callback | Callback&lt;void&gt; | 否 | 回调返回空 |
**示例:**
```ts
async function offDemo() {
console.info('offDemo')
userFileMgr.off('imageChange', () => {
// stop listening success
});
}
```
### createAsset
createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback&lt;FileAsset&gt;): void
创建文件资源,使用callback方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | --------------------------- | ---- | ------------------------------------------------------------ |
| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 |
| displayName | string | 是 | 展示文件名 |
| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)> | 是 | 异步获取媒体数据FileAsset之后的回调 |
**示例:**
```ts
async function createAssetDemoCallback() {
console.info('createAssetDemo')
let mediaType = userfile_manager.MediaType.FILE;
let DIR_DOC = directoryType.DIR_DOCUMENTS;
const path = await userFileMgr.getPublicDirectory(DIR_DOC);
userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => {
if (err == undefined) {
console.info('createAsset successfully');
} else {
console.info('createAsset failed, message = ', err);
}
})
}
```
### createAsset
createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise&lt;FileAsset>;
创建文件资源,使用Promise方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | --------- | ---- | ------------------------------------------------------------ |
| mediaType | [MediaType](#mediatype) | 是 | 媒体类型 |
| displayName | string | 是 | 展示文件名 |
| relativePath | string | 是 | 文件保存路径,可以通过getPublicDirectory获取不同类型文件的保存路径 |
**返回值**
| 类型 | 说明 |
| --------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)> | 媒体数据FileAsset |
**示例:**
```ts
async function createAssetDemoPromise() {
console.info('createAssetDemo')
let mediaType = userfile_manager.MediaType.FILE;
let DIR_DOC = directoryType.DIR_DOCUMENTS;
const path = await userFileMgr.getPublicDirectory(DIR_DOC);
try {
let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/')
console.info('createAsset successfully');
} catch (err) {
console.info('createAsset failed, message = ', err);
}
}
```
### deleteAsset
deleteAsset(uri: string, callback: AsyncCallback&lt;void>): void;
删除文件资源,使用callback方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ---------------------- |
| uri | string | 是 | 文件URI |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)> | 是 | 异步删除文件之后的回调 |
**示例:**
```ts
async function deleteAssetDemoCallback() {
console.info('deleteAssetDemo')
let fileKeyObj = userfile_manager.FileKey
let fileType = userfile_manager.MediaType.FILE
let option = {
selections: '',
selectionArgs: [],
};
try {
const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option);
var asset = await fetchFileResult.getFirstObject();
} catch(err) {
console.info('fetch failed, message =', err)
}
if (asset == undefined) {
console.error('asset not exist')
return
}
userFileMgr.deleteAsset(asset.uri, (err) => {
if (err == undefined) {
console.info("deleteAsset successfully");
} else {
console.info("deleteAsset failed with error:"+ err);
}
});
}
```
### deleteAsset
deleteAsset(uri: string): Promise&lt;void>;
创建文件资源,使用Promise方式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- |
| uri | string | 是 | 文件URI |
**返回值**
| 类型 | 说明 |
| ---------------- | --------------------------------- |
| Promise&lt;void> | Promise实例,用于获取异步返回结果 |
**示例:**
```ts
async function deleteAssetDemoPromise() {
console.info('deleteAssetDemo')
let fileKeyObj = userfile_manager.FileKey
let fileType = userfile_manager.MediaType.FILE
let option = {
selections: '',
selectionArgs: [],
};
try {
const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option);
var asset = await fetchFileResult.getFirstObject();
} catch(err) {
console.info('fetch failed, message =', err)
}
if (asset == undefined) {
console.error('asset not exist')
return
}
try {
await userFileMgr.deleteAsset(asset.uri);
console.info("deleteAsset successfully");
} catch (err) {
console.info("deleteAsset failed with error:"+ err);
}
}
```
### getAlbums
getAlbums(type: Array&lt;MediaType>, options: MediaFetchOptions, callback: AsyncCallback<Array&lt;Album>>): void;
获取相册列表,使用callback 方式返回结果。
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------ | ---- | --------------------------- |
| type | Array&lt;[MediaType](#mediatype)> | 是 | 相册媒体类型检索范围 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 |
| callback | AsyncCallback&lt;Array&lt;[Album](#album)>&gt; | 是 | 异步获取Album列表之后的回调 |
**示例:**
```ts
async function getAlbumsDemoCallback() {
console.info('getAlbumsDemo')
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => {
if (albumList != undefined) {
const album = albumList[0];
console.info('first album.albumName = ' + album.albumName);
console.info('album.count = ' + albumList.length);
} else {
console.info('getAlbum fail, message = ' + err);
}
})
}
```
### getAlbums
getAlbums(type: Array&lt;MediaType>, options: MediaFetchOptions): Promise<Array&lt;Album>>;
获取相册列表,使用 promise 方式返回结果。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------- | ---- | -------------------- |
| type | Array&lt;[MediaType](#mediatype)> | 是 | 相册媒体类型检索范围 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 相册获取条件 |
**返回值:**
| 类型 | 说明 |
| ------------------------ | -------------------------- |
| Promise<Array&lt;[Album](#album)>> | Promise实例,返回Album列表 |
**示例:**
```ts
async function getAlbumsDemoPromise() {
console.info('getAlbumsDemo')
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
try {
let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp);
const album = albumList[0];
console.info('first album.albumName = ' + album.albumName);
console.info('album.count = ' + albumList.length);
} catch (err) {
console.info('getAlbum fail, message = ' + err);
}
}
```
### getPrivateAlbum
getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback<Array&lt;VirtualAlbum&gt;>): void
获取系统相册,使用 callback 方式返回系统相册的数组。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------- | ---- | ---------------------------------- |
| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 |
| callback | AsyncCallback<Array&lt;[VirtualAlbum](#virtualalbum)>> | 是 | 异步获取VirtualAlbum数组之后的回调 |
**示例:**
```ts
async function getPrivateAlbumDemoCallback() {
console.info('getPrivateAlbumDemo')
userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => {
if (err == undefined) {
console.info('getPrivateAlbum ok');
try {
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt);
} catch (err) {
console.info('getFileAssets failed. message = ', err);
}
// Get file count in trash album
let count = fetchResult.getCount();
console.info('fetchResult count = ', count)
// Get fileAssets in trash album
let trashAsset = await fetchResult.getFirstObject();
// Get file trashed date
let isTrash = trashAsset.isTrash();
console.info('is trashed', isTrash)
} else {
console.info('getPrivateAlbum failed. message = ', err);
}
});
}
```
### getPrivateAlbum
getPrivateAlbum(type: VirtualAlbumType): Promise<Array&lt;VirtualAlbum&gt;>
获取系统相册,使用 Promise 方式返回系统相册的数组。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENTS
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---------------- | ---- | ------------ |
| type | [VirtualAlbumType](#virtualalbumtype) | 是 | 系统相册类型 |
**返回值:**
| 类型 | 说明 |
| ------------------------------- | --------------------------------- |
| Promise<Array&lt;[VirtualAlbum](#virtualalbum)>> | Promise实例,返回VirtualAlbum数组 |
**示例:**
```ts
async function getPrivateAlbumDemoPromise() {
console.info('getPrivateAlbumDemo');
try {
var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH);
} catch(err) {
console.info('getPrivateAlbum failed. message = ', err);
}
try {
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt);
} catch (err) {
console.info('getFileAssets failed. message = ', err);
}
// Get file count in trash album
let count = fetchResult.getCount();
console.info('fetchResult count = ', count)
// Get fileAssets in trash album
let trashAsset = await fetchResult.getFirstObject();
// Get file trashed date
let isTrash = trashAsset.isTrash();
console.info('is trashed', isTrash)
}
```
### getActivePeers
getActivePeers(callback: AsyncCallback<Array&lt;PeerInfo>>): void;
获取在线对端设备的信息,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------- | ---- | ------------ |
| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | 是 | 系统相册类型 |
**示例:**
```ts
async function getActivePeersDemoCallback() {
console.info('getActivePeersDemo')
var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => {
if (err == undefined) {
console.log('getActivePeers succeed.')
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('getActivePeers failed. message = ', err)
}
});
}
```
### getActivePeers
getActivePeers(): Promise<Array&lt;PeerInfo>>;
获取在线对端设备的信息,使用promise方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore
**返回值:**
| 类型 | 说明 |
| --------------------------- | ----------------------------- |
| Promise<Array<[PeerInfo](#peerinfo)>> | Promise实例,返回在线设备列表 |
**示例:**
```ts
async function getActivePeersDemoPromise() {
console.info('getActivePeersDemo')
try {
var devicesInfo = await userFileMgr.getActivePeers();
} catch (err) {
console.info('getActivePeers failed. message = ', err)
}
if (devicesInfo != undefined) {
console.log('getActivePeers succeed.')
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed fail')
}
}
```
### getAllPeers
getAllPeers(callback: AsyncCallback<Array&lt;PeerInfo>>): void;
获取所有对端设备的信息,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------- | ---- | ------------ |
| callback | AsyncCallback<Array&lt;[PeerInfo](#peerinfo)>> | 是 | 系统相册类型 |
**示例:**
```ts
async function getAllPeersDemoCallback() {
console.info('getAllPeersDemo')
var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => {
if (err == undefined) {
console.log('getAllPeers succeed.')
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('getAllPeers failed. message = ', err)
}
});
}
```
### getAllPeers
getAllPeers(): Promise<Array&lt;PeerInfo>>;
获取所有对端设备的信息,使用promise方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.DistributedCore
**返回值:**
| 类型 | 说明 |
| --------------------------- | ----------------------------- |
| Promise<Array&lt;[PeerInfo](#peerinfo)>> | Promise实例,返回所有设备列表 |
**示例:**
```ts
async function getAllPeersDemoPromise() {
console.info('getAllPeersDemo')
try {
var devicesInfo = await userFileMgr.getAllPeers();
} catch (err) {
console.info('getAllPeers failed. message = ', err)
}
if (devicesInfo != undefined) {
console.log('getAllPeers succeed.')
for (let i = 0; i < devicesInfo.length; i++) {
console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId);
}
} else {
console.info('get distributed fail')
}
}
```
### release
release(callback: AsyncCallback&lt;void&gt;): void
释放UserFileManager实例。
当后续不需要使用UserFileManager实例中的方法时调用。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调表示成功还是失败 |
**示例:**
```ts
async function releaseDemoCallback() {
console.info('releaseDemo');
userFileMgr.release((err) => {
if (err != undefined) {
console.info('release failed. message = ', err);
} else {
console.info('release ok.');
}
})
}
```
### release
release(): Promise&lt;void&gt;
释放UserFileManager实例。
当后续不需要使用UserFileManager 实例中的方法时调用。
**系统能力**:SystemCapability.Multimedia.MediaLibrary.Core
**返回值:**
| 类型 | 说明 |
| ------------------- | --------------------------------- |
| Promise&lt;void&gt; | Promise实例,用于获取异步返回结果 |
**示例:**
```ts
async function releaseDemoPromise() {
console.info('releaseDemo');
try {
await userFileMgr.release();
console.info('release ok.');
} catch (err) {
console.info('release failed. message = ', err);
}
}
```
## FileAsset
提供封装文件属性的方法。
### 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ |
| id | number | 是 | 否 | 文件资源编号 |
| uri | string | 是 | 否 | 文件资源uri(如:dataability:///media/image/2) |
| mimeType | string | 是 | 否 | 文件扩展属性 |
| MediaType | [MediaType](#mediatype) | 是 | 否 | 媒体类型 |
| displayName | string | 是 | 是 | 显示文件名,包含后缀名 |
| title | string | 是 | 是 | 文件标题 |
| relativePath | string | 是 | 是 | 相对公共目录路径 |
| parent | number | 是 | 否 | 父目录id |
| [size](#size) | number | 是 | 否 | 文件大小(单位:字节) |
| dateAdded | number | 是 | 否 | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| dateModified | number | 是 | 否 | 修改日期(修改文件时间到1970年1月1日的秒数值) |
| dateTaken | number | 是 | 否 | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) |
| artist | string | 是 | 否 | 作者 |
| audioAlbum | string | 是 | 否 | 专辑 |
| width | number | 是 | 否 | 图片宽度(单位:像素) |
| height | number | 是 | 否 | 图片高度(单位:像素) |
| orientation | number | 是 | 是 | 图片显示方向(顺时针旋转角度,如0,90,180 单位:度) |
| duration | number | 是 | 否 | 持续时间(单位:毫秒) |
| albumId | number | 是 | 否 | 文件所归属的相册编号 |
| albumUri | string | 是 | 否 | 文件所归属相册uri |
| albumName | string | 是 | 否 | 文件所归属相册名称 |
### isDirectory
isDirectory(callback: AsyncCallback&lt;boolean&gt;): void
判断fileAsset是否为目录,使用callback方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | ------------------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 当前FileAsset是否是目录的回调 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isDirectory((err, isDirectory) => {
// do something
});
}
```
### isDirectory
isDirectory():Promise&lt;boolean&gt;
判断fileAsset是否为目录,使用Promise方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值:**
| 类型 | 说明 |
| ---------------------- | ---------------------------- |
| Promise&lt;boolean&gt; | Promise实例,返回当前FileAsset是否是目录 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isDirectory().then(function(isDirectory){
console.info("isDirectory result:"+ isDirectory);
}).catch(function(err){
console.info("isDirectory failed with error:"+ err);
});
}
```
### commitModify
commitModify(callback: AsyncCallback&lt;void&gt;): void
修改文件的元数据,使用callback方式返回异步结果。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ----- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
asset.commitModify(() => {
console.info('commitModify success');
});
}
```
### commitModify
commitModify(): Promise&lt;void&gt;
修改文件的元数据,使用promise方式返回异步结果。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------- | ---------- |
| Promise&lt;void&gt; | Promise返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.title = 'newtitle';
asset.commitModify();
}
```
### open
open(mode: string, callback: AsyncCallback&lt;number&gt;): void
打开当前文件,使用callback方式返回异步结果。
**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ----------------------------------- |
| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) |
| callback | AsyncCallback&lt;number&gt; | 是 | 回调返回文件句柄 |
**示例:**
```js
async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
let userFileMgr = userfile_manager.getUserFileMgr(context);
const path = await userFileMgr.getPublicDirectory(DIR_IMAGE);
const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path);
asset.open('rw', (openError, fd) => {
if(fd > 0){
asset.close(fd);
}else{
console.info('File Open Failed!' + openError);
}
});
}
```
### open
open(mode: string): Promise&lt;number&gt;
打开当前文件,使用promise方式返回异步结果。
**注意**:当前写操作是互斥的操作,写操作完成后需要调用close进行释放
**需要权限**:ohos.permission.READ_IMAGEVIDEO 或 ohos.permission.READ_AUDIO 或 ohos.permission.READ_DOCUMENT 或 ohos.permission.WRITE_MEDIA 或 ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | ----------------------------------- |
| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) |
**返回值:**
| 类型 | 说明 |
| --------------------- | ------------- |
| Promise&lt;number&gt; | Promise返回文件句柄 |
**示例:**
```js
async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
let userFileMgr = userfile_manager.getUserFileMgr(context);
const path = await userFileMgr.getPublicDirectory(DIR_IMAGE);
const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path);
asset.open('rw')
.then((fd) => {
console.info('File fd!' + fd);
})
.catch((err) => {
console.info('File err!' + err);
});
}
```
### close
close(fd: number, callback: AsyncCallback&lt;void&gt;): void
关闭当前文件,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ----- |
| fd | number | 是 | 文件描述符 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
console.info('File fd!' + fd);
asset.close(fd, (closeErr) => {
if (closeErr != undefined) {
console.info('mediaLibraryTest : close : FAIL ' + closeErr);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else {
console.info("=======asset.close success====>");
}
});
})
.catch((err) => {
console.info('File err!' + err);
});
}
```
### close
close(fd: number): Promise&lt;void&gt;
关闭当前文件,使用promise方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | ------ | ---- | ----- |
| fd | number | 是 | 文件描述符 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ---------- |
| Promise&lt;void&gt; | Promise返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.open('rw').then((fd) => {
console.info('File fd!' + fd);
asset.close(fd).then((closeErr) => {
if (closeErr != undefined) {
console.info('mediaLibraryTest : close : FAIL ' + closeErr);
console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL');
} else {
console.info("=======asset.close success====>");
}
});
})
.catch((err) => {
console.info('File err!' + err);
});
}
```
### getThumbnail
getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void
获取文件的缩略图,使用callback方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | 是 | 回调返回缩略图的PixelMap |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail((err, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap);
});
}
```
### getThumbnail
getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void
获取文件的缩略图,传入缩略图尺寸,使用callback方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------- | ---- | ---------------- |
| size | [Size](#size) | 是 | 缩略图尺寸 |
| callback | AsyncCallback&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | 是 | 回调返回缩略图的PixelMap |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let size = { width: 720, height: 720 };
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size, (err, pixelmap) => {
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap);
});
}
```
### getThumbnail
getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt;
获取文件的缩略图,传入缩略图尺寸,使用promise方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---- | -------------- | ---- | ----- |
| size | [Size](#size) | 否 | 缩略图尺寸 |
**返回值:**
| 类型 | 说明 |
| ----------------------------- | --------------------- |
| Promise&lt;[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)&gt; | Promise返回缩略图的PixelMap |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let size = { width: 720, height: 720 };
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.getThumbnail(size)
.then((pixelmap) => {
console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap);
})
.catch((err) => {
console.info('mediaLibraryTest : getThumbnail fail'+ err);
});
}
```
### favorite
favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void
将文件设置为收藏文件,使用callback方式返回异步结果。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------------------------- | ---- | ---------------------------------- |
| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.favorite(true,function(err){
// do something
});
}
```
### favorite
favorite(isFavorite: boolean): Promise&lt;void&gt;
将文件设置为收藏文件,使用promise方式返回异步结果。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------- | ---- | ---------------------------------- |
| isFavorite | boolean | 是 | 是否设置为收藏文件, true:设置为收藏文件,false:取消收藏 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ---------- |
| Promise&lt;void&gt; | Promise返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.favorite(true).then(function() {
console.info("favorite successfully");
}).catch(function(err){
console.info("favorite failed with error:"+ err);
});
}
```
### isFavorite
isFavorite(callback: AsyncCallback&lt;boolean&gt;): void
判断该文件是否为收藏文件,使用callback方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | ----------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调表示是否为收藏文件 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isFavorite((err, isFavorite) => {
if (isFavorite) {
console.info('FileAsset is favorite');
}else{
console.info('FileAsset is not favorite');
}
});
}
```
### isFavorite
isFavorite():Promise&lt;boolean&gt;
判断该文件是否为收藏文件,使用promise方式返回异步结果。
**需要权限**:ohos.permission.READ_MEDIA
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值:**
| 类型 | 说明 |
| ---------------------- | ------------------ |
| Promise&lt;boolean&gt; | Promise回调表示是否是收藏文件 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isFavorite().then(function(isFavorite){
console.info("isFavorite result:"+ isFavorite);
}).catch(function(err){
console.info("isFavorite failed with error:"+ err);
});
}
```
### trash
trash(isTrash: boolean, callback: AsyncCallback&lt;void&gt;): void
当文件被定位时,将文件放到垃圾文件夹,使用callback方式返回异步结果。
放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | --------- |
| isTrash | boolean | 是 | 是否设置为垃圾文件 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.trash(true, trashCallBack);
function trashCallBack(err, trash) {
console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash');
}
}
```
### trash
trash(isTrash: boolean): Promise&lt;void&gt;
当文件被定位时,将文件放到垃圾文件夹,使用promise方式返回异步结果。
放入垃圾文件夹的文件不会被真正删除,可以通过isTrash = false参数恢复成正常文件。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------- | ---- | --------- |
| isTrash | boolean | 是 | 是否设置为垃圾文件 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ---------- |
| Promise&lt;void&gt; | Promise返回空 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.trash(true).then(function() {
console.info("trash successfully");
}).catch(function(err){
console.info("trash failed with error:"+ err);
});
}
```
### isTrash
isTrash(callback: AsyncCallback&lt;boolean&gt;): void
当文件被定位,判断文件是否为垃圾文件,使用callback方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------- | ---- | --------------- |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调返回表示文件是否为垃圾文件 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isTrash((err, isTrash) => {
if (isTrash == undefined) {
console.error('Failed to get trash state: ' + err);
return;
}
console.info('Get trash state success: ' + isTrash);
});
}
```
### isTrash
isTrash():Promise&lt;boolean&gt;
当文件被定位,判断文件是否为垃圾文件,使用promise方式返回异步结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值:**
| 类型 | 说明 |
| ------------------- | -------------------- |
| Promise&lt;void&gt; | Promise回调表示文件是否为垃圾文件 |
**示例:**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
const fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const asset = await fetchFileResult.getFirstObject();
asset.isTrash().then(function(isTrash){
console.info("isTrash result: " + isTrash);
}).catch(function(err){
console.error("isTrash failed with error: " + err);
});
}
```
## FetchFileResult
文件检索结果集。
### getCount
getCount(): number
获取文件检索结果中的文件总数。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| ------ | -------- |
| number | 检索到的文件总数 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE;
let getFileCountOneOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp);
const fetchCount = fetchFileResult.getCount();
}
```
### isAfterLast
isAfterLast(): boolean
检查结果集是否指向最后一行。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| ------- | ---------------------------------- |
| boolean | 当读到最后一条记录后,后续没有记录返回true,否则返回false。 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount();
console.info('mediaLibraryTest : count:' + fetchCount);
let fileAsset = await fetchFileResult.getFirstObject();
for (var i = 1; i < fetchCount; i++) {
fileAsset = await fetchFileResult.getNextObject();
if(i == fetchCount - 1) {
console.info('mediaLibraryTest : isLast');
var result = fetchFileResult.isAfterLast();
console.info('mediaLibraryTest : isAfterLast:' + result);
console.info('mediaLibraryTest : isAfterLast end');
fetchFileResult.close();
}
}
}
```
### close
close(): void
释放 FetchFileResult 实例并使其失效。无法调用其他方法。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.close();
}
```
### getFirstObject
getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void
获取文件检索结果中的第一个文件资产。此方法使用回调返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------- | ---- | ------------------------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | 是 | 异步获取结果集中第一个FileAsset完成后的回调 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getFirstObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName : ' + fileAsset.displayName);
})
}
```
### getFirstObject
getFirstObject(): Promise&lt;FileAsset&gt;
获取文件检索结果中的第一个文件资产。此方法使用Promise方式返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| --------------------------------------- | -------------------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | Promise方式返回FileAsset。 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getFirstObject().then(function(fileAsset){
console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset));
}).catch(function(err){
console.info("getFirstObject failed with error:"+ err);
});
}
```
### getNextObject
getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
获取文件检索结果中的下一个文件资产。此方法使用callback形式返回结果。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | --------------------------------------------- | ---- | ----------------------------------------- |
| callbacke | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | 是 | 异步返回结果集中下一个FileAsset之后的回调 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getNextObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName : ' + fileAsset.displayName);
})
}
```
### getNextObject
getNextObject(): Promise&lt;FileAsset&gt;
获取文件检索结果中的下一个文件资产。此方法使用promise方式来异步返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | 返回FileAsset对象 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
const fetchCount = fetchFileResult.getCount();
console.info('mediaLibraryTest : count:' + fetchCount);
let fileAsset = await fetchFileResult.getNextObject();
}
```
### getLastObject
getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void
获取文件检索结果中的最后一个文件资产。此方法使用callback回调来返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | 是 | 异步返回FileAsset之后的回调 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getLastObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName : ' + fileAsset.displayName);
})
}
```
### getLastObject
getLastObject(): Promise&lt;FileAsset&gt;
获取文件检索结果中的最后一个文件资产。此方法使用Promise方式来返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | 返回FileAsset对象 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
let lastObject = await fetchFileResult.getLastObject();
}
```
### getPositionObject
getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void
获取文件检索结果中具有指定索引的文件资产。此方法使用回调来返回FileAsset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ------------------ |
| index | number | 是 | 要获取的文件的索引,从0开始 |
| callback | AsyncCallback&lt;[FileAsset](#fileasset)&gt; | 是 | 异步返回FileAsset之后的回调 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getPositionObject(0, (err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
console.log('fileAsset.displayName : ' + fileAsset.displayName);
})
}
```
### getPositionObject
getPositionObject(index: number): Promise&lt;FileAsset&gt;
获取文件检索结果中具有指定索引的文件资产。此方法使用Promise形式返回文件Asset。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ----- | ------ | ---- | -------------- |
| index | number | 是 | 要获取的文件的索引,从0开始 |
**返回值**
| 类型 | 说明 |
| --------------------------------------- | ----------------- |
| Promise&lt;[FileAsset](#fileasset)&gt; | 返回FileAsset对象 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getPositionObject(1) .then(function (fileAsset){
console.log('fileAsset.displayName : ' + fileAsset.displayName);
}).catch(function (err) {
console.info("getFileAssets failed with error:" + err);
});
}
```
### getAllObject
getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void
获取文件检索结果中的所有文件资产。此方法使用Callback回调来返回FileAsset结果集。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | -------------------- |
| callback | AsyncCallback<Array<[FileAsset](#fileasset)>> | 是 | 异步返回FileAsset列表之后的回调 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
fetchFileResult.getAllObject((err, fileAsset) => {
if (err) {
console.error('Failed ');
return;
}
for (let i = 0; i < fetchFileResult.getCount(); i++) {
console.log('fileAsset.displayName : ' + fileAsset[i].displayName);
}
})
}
```
### getAllObject
getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt;
获取文件检索结果中的所有文件资产。此方法使用Promise来返回FileAsset结果集。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| ---------------------------------------- | --------------------- |
| Promise<Array<[FileAsset](#fileasset)>> | 返回FileAsset对象列表 |
**示例**
```js
async function example() {
let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE;
let getImageOp = {
selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [imageType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let userFileMgr = userfile_manager.getUserFileMgr(context);
let fetchFileResult = await userFileMgr.getFileAssets(getImageOp);
var data = fetchFileResult.getAllObject();
}
```
## Album
实体相册
### 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------ | ------ | ---- | ---- | ------- |
| albumName | string | 是 | 是 | 相册名称 |
| albumUri | string | 是 | 否 | 相册Uri |
| dateModified | number | 是 | 否 | 修改日期 |
| count | number | 是 | 否 | 相册中文件数量 |
| relativePath | string | 是 | 否 | 相对路径 |
| coverUri | string | 是 | 否 | 封面文件Uri
### commitModify
commitModify(callback: AsyncCallback&lt;void&gt;): void;
更新相册属性修改到数据库中。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调返回空 |
**示例**
```ts
async function commitModifyDemoCallback() {
console.info('commitModifyDemo')
let fileKeyObj = userfile_manager.FileKey
let imageType = userfile_manager.MediaType.IMAGE;
let getImageOp = {
selections: '',
selectionArgs: [],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp);
let asset = await fetchFileResult.getFirstObject();
console.info('old displayName:', asset.displayName)
asset.displayName = 'newDisplayName';
console.info('new displayName:', asset.displayName)
asset.commitModify((err) => {
if (err == undefined) {
console.info('commitModify succeed.')
} else {
console.info('commitModify failed, message =', err);
}
});
}
```
### commitModify
commitModify(): Promise&lt;void&gt;;
更新相册属性修改到数据库中。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**返回值**
| 类型 | 说明 |
| ------------------- | ------------ |
| Promise&lt;void&gt; | Promise调用返回空 |
**示例**
```ts
async function commitModifyDemoPromise() {
console.info('commitModifyDemo')
let fileKeyObj = userfile_manager.FileKey
let imageType = userfile_manager.MediaType.IMAGE;
let getImageOp = {
selections: '',
selectionArgs: [],
order: fileKeyObj.DATE_ADDED + " DESC",
extendArgs: "",
};
let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp);
let asset = await fetchFileResult.getFirstObject();
console.info('old displayName:', asset.displayName)
asset.displayName = 'newDisplayName';
console.info('new displayName:', asset.displayName)
try {
await asset.commitModify();
console.info('commitModify succeed.')
} catch (err) {
console.info('commitModify failed, message =', err);
}
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, callback: AsyncCallback&lt;FetchFileResult&gt;): void;
按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | 是 | 媒体类型检索选项。 |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 |
**示例**
```ts
async function albumGetFileAssetsDemoCallback() {
console.info('albumGetFileAssetsDemoCallback2')
let imageType = userfile_manager.MediaType.IMAGE;
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp);
const album = albumList[0];
album.getFileAssets([imageType], (err, albumFetchFileResult) => {
if (err == undefined) {
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult));
} else {
console.info("getFileAssets failed with error:"+ err);
}
});
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void;
按照检索条件获取相册中的文件。此方法使用Callback回调来返回文件结果集。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | 是 | 媒体类型检索选项。 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 |
**示例**
```ts
async function albumGetFileAssetsDemoCallback() {
console.info('albumGetFileAssetsDemoCallback')
let imageType = userfile_manager.MediaType.IMAGE;
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
let fileNoArgsfetchOp = {
selections: '',
selectionArgs: [],
}
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp);
const album = albumList[0];
album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => {
if (err == undefined) {
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult));
} else {
console.info("getFileAssets failed with error:"+ err);
}
});
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;;
按照检索条件获取相册中的文件。此方法使用异步Promise来返回文件结果集。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | -------------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | 是 | 媒体类型检索选项。 |
|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 |
**返回值**
| 类型 | 说明 |
| --------------------------------------------- | ------------------------- |
| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 |
**示例**
```ts
async function albumGetFileAssetsDemoPromise() {
console.info('albumGetFileAssetsDemoPromise')
let imageType = userfile_manager.MediaType.IMAGE;
let AlbumNoArgsfetchOp = {
selections: '',
selectionArgs: [],
};
let fileNoArgsfetchOp = {
selections: '',
selectionArgs: [],
}
const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp);
const album = albumList[0];
album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){
console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult));
}).catch(function(err){
console.info("getFileAssets failed with error:"+ err);
});
}
```
## VirtualAlbum
虚拟相册
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void;
按照检索条件获取虚拟相册中的文件。此方法使用Callback回调来返回文件结果集。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
> 说明:
> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明)
>
> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------------------------------- | ---- | ----------------------------------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | 是 | 媒体类型检索选项。 |
| options | [MediaFetchOptions](#mediafetchoptions) | 是 | 媒体检索选项。 |
| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | 是 | 异步返回FetchFileResult之后的回调。 |
**示例**
```ts
async function virtualAlbumGetFileAssetsDemoCallback() {
console.info('virtualAlbumGetFileAssetsDemoCallback')
try {
var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH);
} catch (err) {
console.info('getPrivateAlbum failed, message = ', err);
}
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => {
if (err == undefined) {
let count = fetchResult.getCount();
console.info('fetchResult.count = ', count);
} else {
console.info('getFileAssets failed, message = ', err);
}
});
}
```
### getFileAssets
getFileAssets(type: Array&lt;MediaType&gt;, options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;;
按照检索条件获取虚拟相册中的文件。此方法使用异步Promise来返回文件结果集。
**需要权限**:ohos.permission.WRITE_IMAGEVIDEO 或 ohos.permission.WRITE_AUDIO 或 ohos.permission.WRITE_DOCUMENT
> 说明:
> 本接口所需申请的分类的权限APL等级为system_basic。APL等级为normal的应用需要通过ACL证书方式申请,申请方式请参考[ACL说明](../../security/accesstoken-overview.md#访问控制列表acl说明)
>
> 建议通过options参数显式地指定要访问的文件类型。若无法判断文件类型,则会根据应用实际申请的权限返回对应的文件资源结果集。
**系统能力**:SystemCapability.FileManagement.UserFileManager.Core
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ---------------------------------------- | ---- | -------------- |
| type | Array&lt;[MediaType](#mediatype)&gt; | 是 | 媒体类型检索选项。 |
|options | [MediaFetchOptions](#mediafetchoptions) | 否 | 媒体检索选项。 |
**返回值**
| 类型 | 说明 |
| --------------------------------------------- | ------------------------- |
| Promise<[FetchFileResult](#fetchfileresult)> | 返回FetchFileResult对象。 |
**示例**
```ts
async function virtualAlbumGetFileAssetsDemoPromise() {
console.info('virtualAlbumGetFileAssetsDemoPromise')
let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH);
let fetchOpt = {
selections: '',
selectionArgs: [],
};
let trashAlbum = albumArray[0];
let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt);
let count = fetchResult.getCount();
console.info('fetchResult.count = ', count);
}
```
## PeerInfo
注册设备的信息。
此接口为系统接口。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.DistributedCore
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---------- | -------------------------- | ---- | ---- | ---------------- |
| deviceName | string | 是 | 否 | 注册设备的名称 |
| networkId | string | 是 | 否 | 注册设备的网络ID |
| isOnline | boolean | 是 | 否 | 是否在线 |
## MediaType
枚举,媒体类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 说明 |
| ----- | ---- |
| FILE | 文件 |
| IMAGE | 图片 |
| VIDEO | 视频 |
| AUDIO | 音频 |
## FileKey
枚举,文件关键信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 默认值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | 文件uri |
| RELATIVE_PATH | relative_path | 相对公共目录路径 |
| DISPLAY_NAME | display_name | 显示名字 |
| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) |
| TITLE | title | 文件标题 |
## AudioKey
枚举,音频文件关键信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 默认值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | 文件uri |
| RELATIVE_PATH | relative_path | 相对公共目录路径 |
| DISPLAY_NAME | display_name | 显示名字 |
| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) |
| TITLE | title | 文件标题 |
| ARTIST | artist | 作者 |
| AUDIOALBUM | audio_album | 专辑 |
| DURATION | duration | 持续时间(单位:毫秒) |
## ImageVideoKey
枚举,图片和视频文件关键信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 默认值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | 文件uri |
| RELATIVE_PATH | relative_path | 相对公共目录路径 |
| DISPLAY_NAME | display_name | 显示名字 |
| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) |
| DURATION | duration | 持续时间(单位:毫秒) |
| WIDTH | width | 图片宽度(单位:像素) |
| HEIGHT | height | 图片高度(单位:像素) |
| DATE_TAKEN | date_taken | 拍摄日期(文件拍照时间到1970年1月1日的秒数值) |
## AlbumKey
枚举,相册关键信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 默认值 | 说明 |
| ------------- | ------------------- | ---------------------------------------------------------- |
| URI | uri | 相册uri |
| RELATIVE_PATH | relative_path | 相对公共目录路径 |
| DISPLAY_NAME | display_name | 显示名字 |
| DATE_ADDED | date_added | 添加日期(添加文件时间到1970年1月1日的秒数值) |
| DATE_MODIFIED | date_modified | 修改日期(修改文件时间到1970年1月1日的秒数值) |
## DirectoryType
枚举,目录类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 说明 |
| ------------- | ------------------ |
| DIR_CAMERA | 表示Camera文件路径 |
| DIR_VIDEO | 表示视频路径 |
| DIR_IMAGE | 表示图片路径 |
| DIR_AUDIO | 表示音频路径 |
| DIR_DOCUMENTS | 表示文档路径 |
| DIR_DOWNLOAD | 表示下载路径 |
## MediaFetchOptions
检索条件。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 类型 | 可读 | 可写 | 必填 | 说明 |
| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ |
| selections | string | 是 | 是 | 是 | 检索条件,使用[FileKey](#filekey)中的枚举值作为检索条件的列名。示例:<br />selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?‘, |
| selectionArgs | Array&lt;string&gt; | 是 | 是 | 是 | 检索条件的值,对应selections中检索条件列的值。<br />示例:<br />selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], |
| order | string | 是 | 是 | 否 | 检索结果排序方式,使用[FileKey](#filekey)中的枚举值作为检索结果排序的列,可以用升序或降序排列。示例:<br />升序排列:order: mediaLibrary.FileKey.DATE_ADDED + " AESC"<br />降序排列:order: mediaLibrary.FileKey.DATE_ADDED + " DESC" |
| uri | string | 是 | 是 | 否 | 文件URI |
| networkId | string | 是 | 是 | 否 | 注册设备网络ID |
| extendArgs | string | 是 | 是 | 否 | 扩展的检索参数,目前没有扩展检索参数 |
## Size
图片尺寸。
系统能力: 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | -------- |
| width | number | 是 | 是 | 宽(单位:像素) |
| height | number | 是 | 是 | 高(单位:像素) |
## VirtualAlbumType
枚举,系统相册或虚拟相册类型
**系统能力:** 以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileManager.Core
| 名称 | 说明 |
| ------------- | ------------------ |
| TYPE_FAVORITE | 系统相册:收藏夹相册 |
| TYPE_TRASH | 系统相册:回收站相册 |
......@@ -8,8 +8,8 @@ wantConstant模块提供want中操作want常数和解释Flags说明的能力。
## 导入模块
```
import wantConstant from '@ohos.ability.wantConstant'
```js
import wantConstant from '@ohos.ability.wantConstant';
```
## wantConstant.Action
......@@ -26,7 +26,7 @@ want操作的常数。
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | 指示启动提供无线网络设置的页面功能的操作,例如,Wi-Fi选项。 |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | 指示启动管理已安装应用程序的页面功能的操作。 |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | 指示启动显示指定应用程序详细信息的页面功能的操作。 |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | 指示启动页面功能以设置闹钟的操作。 |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | 指示启动页面功能以设置闹钟的操作。 |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | 指示启动显示所有警报的页面功能的操作时钟。 |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | 指示启动用于使闹钟睡眠的页面功能的操作。 |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | 指示启动删除闹钟的页面功能的操作。 |
......
......@@ -11,7 +11,7 @@ AbilityDelegatorArgs模块提供在应用程序启动期间,用于存储已注
通过AbilityDelegatorRegistry中getArguments方法获取。
```js
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry';
var args = AbilityDelegatorRegistry.getArguments();
```
......
......@@ -49,6 +49,8 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v
快速修复的补丁安装接口。
**需要权限**: ohos.permission.INSTALL_BUNDLE
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.QuickFix
**系统API**: 此接口为系统接口,三方应用不支持调用。
......@@ -77,10 +79,12 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v
## quickFixManager.applyQuickFix
applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise<void>;
applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
快速修复的补丁安装接口。
**需要权限**: ohos.permission.INSTALL_BUNDLE
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.QuickFix
**系统API**: 此接口为系统接口,三方应用不支持调用。
......@@ -116,6 +120,8 @@ getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\<Applicat
获取应用的快速修复信息。
**需要权限**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.QuickFix
**系统API**: 此接口为系统接口,三方应用不支持调用。
......@@ -148,6 +154,8 @@ getApplicationQuickFixInfo(bundleName: string): Promise\<ApplicationQuickFixInfo
获取应用的快速修复信息。
**需要权限**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.QuickFix
**系统API**: 此接口为系统接口,三方应用不支持调用。
......
......@@ -866,7 +866,7 @@ onProcessDied(processData: ProcessData): void;
| bundleName<sup>8+</sup> | string | 是 | 否 | 应用包名。 |
| uid<sup>8+</sup> | number | 是 | 否 | 用户ID。 |
| isContinuousTask<sup>9+</sup> | boolean | 是 | 否 | 判断过程是否为连续任务。 |
| isKeepAlive<sup>8+</sup> | boolean | 是 | 否 | 判断该过程是否保持活跃。 |
| isKeepAlive<sup>9+</sup> | boolean | 是 | 否 | 判断该过程是否保持活跃。 |
## ProcessRunningInfo
......
......@@ -7,7 +7,7 @@
ExtensionAbility信息,未做特殊说明的属性,均通过GET_BUNDLE_DEFAULT获取
ExtensionAbility信息,未做特殊说明的属性,均通过[getBundleInfo](js-apis-Bundle.md#bundlegetbundleinfo)获取,flag使用[GET_BUNDLE_DEFAULT](js-apis-Bundle.md#bundleflag)获取
## ExtensionAbilityInfo
......
......@@ -830,7 +830,7 @@ promise.then(data => {
## call.reject<sup>7+</sup>
reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback<void\>\): void
reject\(callId: number, options: RejectMessageOptions, callback: AsyncCallback<void\>\): void
拒绝来电。使用callback异步回调。
......
......@@ -812,7 +812,7 @@ getZoomRatioRange\(callback: AsyncCallback<Array<number\>\>\): void
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------------------------------ | ---- | ------------------------ |
| callback | AsyncCallback<Array<number\>\> | 是 | 回调函数,用于获取结果。 |
| callback | AsyncCallback<Array<number\>\> | 是 | 回调函数,用于获取可变焦距比范围,返回的数组包括其最小值和最大值。 |
**示例:**
......@@ -838,7 +838,7 @@ getZoomRatioRange\(\): Promise<Array<number\>\>
| 类型 | 说明 |
| ------------------------ | ------------------------------------------- |
| Promise<Array<number\>\> | 使用Promise的方式获取当前的可变焦距比范围。 |
| Promise<Array<number\>\> | 使用Promise的方式获取当前的可变焦距比范围,返回的数组包括其最小值和最大值。 |
**示例:**
......
# 标准NFC-cardEmulation
本模块主要用于操作及管理NFC卡模拟
本模块主要提供NFC卡模拟业务,包括判断支持哪种卡模拟类型,HCE卡模拟的业务实现等
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......@@ -12,30 +12,49 @@
import cardEmulation from '@ohos.nfc.cardEmulation';
```
## FeatureType
定义不同的NFC卡模拟类型。
**系统能力**:SystemCapability.Communication.NFC.Core
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| HCE | 0 | HCE 卡模拟。 |
| UICC | 1 | SIM 卡模拟。 |
| ESE | 2 | ESE卡模拟。 |
## cardEmulation.isSupported
isSupported(feature: number): boolean
是否支持某种类型的卡模拟
是否支持某种类型的卡模拟。
**需要权限**:ohos.permission.NFC_CARD_EMULATION
**系统能力**:SystemCapability.Communication.NFC.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------- | ---- | ----------------------- |
| feature | number | 是 | 卡模拟类型值,详细请见[FeatureType](#featuretype)枚举值。 |
**返回值:**
| **类型** | **说明** |
| -------- | -------- |
| boolean | true:支持该类型卡模拟,&nbsp;false:不支持该类型卡模拟。 |
| boolean | true: 支持该类型卡模拟,&nbsp;false: 不支持该类型卡模拟。 |
## HceService<sup>8+</sup>
管理HCE卡模拟。在调用HceService的接口前,需要先通过new cardEmulation.HceService()创建实例
提供HCE卡模拟的实现,主要包括接收对端读卡设备的APDU数据,并响应APDU数据到对端读卡设备。使用HCE相关接口前,必须先判断设备是否支持HCE卡模拟能力
### startHCE<sup>8+</sup>
startHCE(aidList: string[]): boolean
开始使用HCE能力
启动HCE业务功能。包括设置当前应用为前台优先,动态注册AID列表
**需要权限**:ohos.permission.NFC_CARD_EMULATION
......@@ -45,13 +64,13 @@ startHCE(aidList: string[]): boolean
| 参数名 | 类型 | 必填 | 说明 |
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | 是 | 注册进行卡模拟的aid列表 |
| aidList | string[] | 是 | 动态注册卡模拟的AID列表。 |
### stopHCE<sup>8+</sup>
stopHCE(): boolean
停止使用HCE能力
停止HCE业务功能。包括退出当前应用前台优先,释放动态注册的AID列表
**需要权限**:ohos.permission.NFC_CARD_EMULATION
......@@ -61,7 +80,7 @@ stopHCE(): boolean
on(type: "hceCmd", callback: AsyncCallback<number[]>): void;
在startHCE后,订阅对端设备消息
订阅回调,用于接收对端读卡设备发送的APDU数据
**需要权限**:ohos.permission.NFC_CARD_EMULATION
......@@ -71,14 +90,14 @@ on(type: "hceCmd", callback: AsyncCallback<number[]>): void;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | 是 | 固定填"hceCmd"字符串 |
| callback | AsyncCallback<number[]> | 是 | 订阅的事件回调,入参是符合APDU协议的数据数组 |
| type | string | 是 | 固定填"hceCmd"字符串 |
| callback | AsyncCallback<number[]> | 是 | 订阅的事件回调,入参是符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
### sendResponse<sup>8+</sup>
sendResponse(responseApdu: number[]): void;
发送数据到对端设备。
发送APDU数据到对端读卡设备。
**需要权限**:ohos.permission.NFC_CARD_EMULATION
......@@ -88,16 +107,25 @@ sendResponse(responseApdu: number[]): void;
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | -------- | ---- | -------------------------------------------------- |
| responseApdu | number[] | 是 | 准备发送到对端的数据,入参是符合APDU协议的数据数组 |
| responseApdu | number[] | 是 | 发送到对端读卡设备的符合APDU协议的数据,每个number十六进制表示,范围是0x00~0xFF。 |
**示例:**
```js
import cardEmulation from '@ohos.nfc.cardEmulation';
var isHceSupported = cardEmulation.isSupported(cardEmulation.FeatureType.HCE);
if (!isHceSupported) {
console.log('this device is not supported for HCE, ignore it.');
return;
}
// device supports HCE, transimit APDU with remote nfc reader.
var hceService = new cardEmulation.HceService();
hceService.startHCE([
"F0010203040506", "A0000000041010"
])
hceService.stopHCE();
]);
hceService.on("hceCmd", (err, res) => {
if(err.data === 0) {
console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res));
......@@ -108,16 +136,8 @@ hceService.on("hceCmd", (err, res) => {
console.log('callback => Operation hceCmd failed. Cause: ' + err.data);
}
})
```
## FeatureType
表示NFC支持的卡模拟类型枚举。
**系统能力**:SystemCapability.Communication.NFC.Core
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| HCE | 0 | 该常量用于检查是否支持 HCE 卡模拟。 |
| UICC | 1 | 该常量用于检查是否支持 SIM 卡模拟。 |
| ESE | 2 | 该常量用于检查是否支持ESE卡模拟。 |
// stop HCE when the application exit the nfc card emulation.
hceService.stopHCE();
```
......@@ -204,8 +204,8 @@ updateContact(contact: Contact, attrs: ContactAttributes, callback: AsyncCallbac
contact.updateContact({
name: {fullName: 'xxx'},
phoneNumbers: [{phoneNumber: '138xxxxxxxx'}]
},{
attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, {
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err) => {
if (err) {
console.log('updateContact callback: err->${JSON.stringify(err)}');
......@@ -433,7 +433,7 @@ queryMyCard(attrs: ContactAttributes, callback: AsyncCallback&lt;Contact&gt;): v
```js
contact.queryMyCard({
attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
}, (err, data) => {
if (err) {
console.log(`queryMyCard callback: err->${JSON.stringify(err)}`);
......@@ -469,7 +469,7 @@ queryMyCard(attrs?: ContactAttributes): Promise&lt;Contact&gt;
```js
let promise = contact.queryMyCard({
attributes:[contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
attributes: [contact.Attribute.ATTR_EMAIL, contact.Attribute.ATTR_NAME]
});
promise.then((data) => {
console.log(`queryMyCard success: data->${JSON.stringify(data)}`);
......@@ -487,7 +487,7 @@ selectContact(callback: AsyncCallback&lt;Array&lt;Contact&gt;&gt;): void
**需要权限**:ohos.permission.READ_CONTACTS
**系统能力**:SystemCapability.Applications.ContactsData
**系统能力**:SystemCapability.Applications.Contacts
**参数:**
......@@ -516,7 +516,7 @@ selectContact(): Promise&lt;Array&lt;Contact&gt;&gt;
**需要权限**:ohos.permission.READ_CONTACTS
**系统能力**:SystemCapability.Applications.Contacts、SystemCapability.Applications.ContactsData
**系统能力**:SystemCapability.Applications.Contacts
**返回值:**
......
......@@ -483,9 +483,9 @@ getRecentlyUsedModules(maxNum?: number): Promise&lt;Array&lt;BundleActiveModuleI
## bundleState.getRecentlyUsedModules<sup>9+</sup>
getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
getRecentlyUsedModules(callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
查询FA使用记录。使用CallBack形式返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000
查询FA使用记录。使用CallBack形式返回数量不超过1000条FA使用记录(FA记录按时间由近及远排序)
**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO
......@@ -497,13 +497,12 @@ getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback&lt;Array&lt;Bund
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| maxNum | number | 否 | 返回条目的最大数量,最多支持1000条。若不填写,则默认为1000。 |
| callback | AsyncCallback&lt;Array&lt;[BundleActiveModuleInfo](#bundleactivemoduleinfo9)&gt;&gt; | 是 | 指定的CallBack回调方法。返回不超过maxNum条FA使用记录。 |
**示例**
```js
bundleState.getRecentlyUsedModules(1000,(err, res) => {
bundleState.getRecentlyUsedModules((err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -512,11 +511,33 @@ getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback&lt;Array&lt;Bund
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback result ' + JSON.stringify(res[i]));
}
}
}
});
```
// 无maxNum参数调用方式
bundleState.getRecentlyUsedModules((err, res) => {
## bundleState.getRecentlyUsedModules<sup>9+</sup>
getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;Array&lt;BundleActiveModuleInfo&gt;&gt;): void
查询FA使用记录。使用CallBack形式返回数量最大不超过maxNum设置的值,FA使用记录由近及远排序,maxNum最大为1000。
**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.App
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| maxNum | number | 是 | 返回FA记录的最大数量,maxNum最大为1000。|
| callback | AsyncCallback&lt;Array&lt;[BundleActiveModuleInfo](#bundleactivemoduleinfo9)&gt;&gt; | 是 | 指定的CallBack回调方法。返回不超过maxNum条FA使用记录。 |
**示例**
```js
bundleState.getRecentlyUsedModules(1000,(err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else {
......@@ -525,7 +546,7 @@ getRecentlyUsedModules(maxNum?: number, callback: AsyncCallback&lt;Array&lt;Bund
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback result ' + JSON.stringify(res[i]));
}
}
}
});
```
......@@ -573,9 +594,9 @@ bundleState.queryAppUsagePriorityGroup().then( res => {
## bundleState.queryAppUsagePriorityGroup<sup>9+</sup>
queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void
queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void
可选参数。有参则查询指定bundleName对应应用的分组。无参数时查询当前应用的分组。使用callback形式返回其应用分组。
查询当前应用的分组。使用callback形式返回其应用分组。
**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO
......@@ -587,23 +608,44 @@ queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;numb
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | --------------------- | ---- | ---------------------------------------- |
| bundleName | string | 否 | 可选参数。有此参数则查询指定bundleName对应应用的分组。无此参数时查询当前应用的分组。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的CallBack回调方法。返回查询的应用分组。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的CallBack回调方法。返回当前应用的分组。 |
**示例**
```javascript
//有bundleName的callback
let bundleName = "com.ohos.camera";
bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => {
bundleState.queryAppUsagePriorityGroup((err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
}
});
//无bundleName的callback
bundleState.queryAppUsagePriorityGroup((err, res) => {
```
## bundleState.queryAppUsagePriorityGroup<sup>9+</sup>
queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback&lt;number&gt;): void
查询指定bundleName对应应用的分组。使用callback形式返回其应用分组。
**需要权限**:ohos.permission.BUNDLE_ACTIVE_INFO
**系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup
**系统API**:此接口为系统接口,三方应用不支持调用。
**参数**
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | --------------------- | ---- | ---------------------------------------- |
| bundleName | string | 是 | 查询指定bundleName对应应用的分组。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 指定的CallBack回调方法。返回制指定bundleName的应用分组。|
**示例**
```javascript
let bundleName = "com.ohos.camera";
bundleState.queryAppUsagePriorityGroup(bundleName, (err, res) => {
if(err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else {
......@@ -687,7 +729,7 @@ bundleState.setBundleGroup(bundleName, newGroup, (err) => {
## bundleState.registerGroupCallBack<sup>9+</sup>
registerGroupCallBack(callback: Callback&lt;BundleActiveGroupCallbackInfo&gt;): Promise&lt;void&gt;
registerGroupCallBack(groupCallback: Callback&lt;BundleActiveGroupCallbackInfo&gt;): Promise&lt;void&gt;
应用注册分组变化监听,待用户名下的某个应用分组发生变化时,通过callback形式向所有已注册分组变化监听的应用返回[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)信息。使用Promise形式返回注册是否成功。
......@@ -729,7 +771,7 @@ bundleState.registerGroupCallBack(onBundleGroupChanged).then( () => {
## bundleState.registerGroupCallBack<sup>9+</sup>
registerGroupCallBack(callback: Callback&lt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&lt;void&gt;): void
registerGroupCallBack(groupCallback: Callback&lt;BundleActiveGroupCallbackInfo&gt;, callback: AsyncCallback&lt;void&gt;): void
应用注册分组变化监听,待用户名下的某个应用分组发生变化时,通过callback形式向所有已注册分组变化监听的应用返回[BundleActiveGroupCallbackInfo](#bundleactivegroupcallbackinfo9)信息。使用异步callback形式返回注册监听是否成功。
......
......@@ -1008,7 +1008,7 @@ try {
}).catch((err) => {
console.log('getResultSet failed: ' + err);
});
const moved5 = resultSet.move();
const moved5 = resultSet.move(1);
console.log("move succeed:" + moved5);
} catch (e) {
console.log("move failed: " + e);
......@@ -1048,7 +1048,7 @@ try {
}).catch((err) => {
console.log('getResultSet failed: ' + err);
});
const moved6 = resultSet.moveToPosition();
const moved6 = resultSet.moveToPosition(1);
console.log("moveToPosition succeed: " + moved6);
} catch (e) {
console.log("moveToPosition failed: " + e);
......
......@@ -3,7 +3,7 @@
FormInfo模块提供对卡片的相关卡片信息和状态进行设置和查询的能力。
> **说明:**
>
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
......@@ -122,3 +122,12 @@ import formInfo from '@ohos.application.formInfo';
| Dimension_2_1<sup>9+</sup> | 5 | 2 x 1 form。 |
## FormInfoFilter
卡片信息过滤器,仅将符合过滤器内要求的卡片信息返回。
**系统能力**:SystemCapability.Ability.Form
| 名称 | 必选 | 说明 |
| ----------- | ---- | ------------ |
| moduleName<sup>9+</sup> | 否 | 可选字段,表示仅保留moduleName与提供值相符的卡片信息。 |
......@@ -3,7 +3,7 @@
FormProvider模块提供了卡片提供方相关接口的能力,包括更新卡片,设置卡片更新时间,获取卡片信息,请求发布卡片等。
> **说明:**
>
>
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
......@@ -183,7 +183,7 @@ getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback&lt;Array&l
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | 是 | 过滤卡片信息 |
| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md#forminfofilter) | 是 | 过滤卡片信息 |
| callback | AsyncCallback&lt;Array&lt;[FormInfo](./js-apis-formInfo.md#forminfo-1)&gt;&gt; | 是 | callback形式返回查询到的卡片信息。 |
**示例:**
......@@ -214,7 +214,7 @@ getFormsInfo(filter?: formInfo.FormInfoFilter): Promise&lt;Array&lt;formInfo.For
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------- |
| filter | formInfo.FormInfoFilter | 否 | 过滤卡片信息 |
| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md) | 否 | 过滤卡片信息 |
**返回值:**
......
......@@ -260,12 +260,7 @@ image.createPixelMap(color, opts)
}
pixelmap.writePixels(area).then(() => {
const readArea = { pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
// region.size.width + x < opts.width, region.size.height + y < opts.height
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
console.info('Succeeded to write pixelmap into the specified area.');
})
}).catch(error => {
console.log('error: ' + error);
......@@ -290,17 +285,20 @@ writePixels(area: PositionArea, callback: AsyncCallback\<void>): void
**示例:**
```js
const area = new ArrayBuffer(400);
const area = { pixels: new ArrayBuffer(8),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 }
}
let bufferArr = new Uint8Array(area.pixels);
for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writePixels(area, (error) => {
if (error != undefined) {
console.info('Failed to write pixelmap into the specified area.');
} else {
const readArea = {
pixels: new ArrayBuffer(20),
offset: 0,
stride: 8,
region: { size: { height: 1, width: 2 }, x: 0, y: 0 },
}
console.info('Succeeded to write pixelmap into the specified area.');
}
})
```
......@@ -329,9 +327,11 @@ writeBufferToPixels(src: ArrayBuffer): Promise\<void>
```js
const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color).then(() => {
for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color).then(() => {
console.log("Succeeded in writing data from a buffer to a PixelMap.");
}).catch((err) => {
console.error("Failed to write data from a buffer to a PixelMap.");
......@@ -357,9 +357,11 @@ writeBufferToPixels(src: ArrayBuffer, callback: AsyncCallback\<void>): void
```js
const color = new ArrayBuffer(96);
const pixelMap = new ArrayBuffer(400);
let bufferArr = new Uint8Array(color);
pixelMap.writeBufferToPixels(color, function(err) {
for (var i = 0; i < bufferArr.length; i++) {
bufferArr[i] = i + 1;
}
pixelmap.writeBufferToPixels(color, function(err) {
if (err) {
console.error("Failed to write data from a buffer to a PixelMap.");
return;
......@@ -386,12 +388,22 @@ getImageInfo(): Promise\<ImageInfo>
**示例:**
```js
const pixelMap = new ArrayBuffer(400);
pixelMap.getImageInfo().then(function(info) {
console.log("Succeeded in obtaining the image pixel map information.");
}).catch((err) => {
console.error("Failed to obtain the image pixel map information.");
});
const color = new ArrayBuffer(96);
let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } }
image.createPixelMap(color, opts).then(pixelmap => {
globalpixelmap = pixelmap;
if (pixelmap == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo().then(imageInfo => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
})
```
### getImageInfo<sup>7+</sup>
......@@ -411,8 +423,21 @@ getImageInfo(callback: AsyncCallback\<ImageInfo>): void
**示例:**
```js
pixelmap.getImageInfo((imageInfo) => {
console.log("Succeeded in obtaining the image pixel map information.");
const color = new ArrayBuffer(96);
let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }
image.createPixelMap(color, opts, (err, pixelmap) => {
if (pixelmap == undefined) {
globalpixelmap = pixelmap;
console.error("Failed to obtain the image pixel map information.");
}
pixelmap.getImageInfo((err, imageInfo) => {
if (imageInfo == undefined) {
console.error("Failed to obtain the image pixel map information.");
}
if (imageInfo.size.height == 4 && imageInfo.size.width == 6) {
console.log("Succeeded in obtaining the image pixel map information.");
}
})
})
```
......@@ -499,9 +524,15 @@ opacity(rate: number, callback: AsyncCallback\<void>): void
**示例:**
```js
async function () {
await pixelMap.opacity(0.5);
}
var rate = 0.5;
pixelmap.opacity(rate, (err) => {
if (err) {
console.error("Failed to set opacity.");
return;
} else {
console.log("Succeeded in setting opacity.");
}
})
```
### opacity<sup>9+</sup>
......@@ -528,7 +559,8 @@ opacity(rate: number): Promise\<void>
```js
async function () {
await pixelMap.opacity(0.5);
var rate = 0.5;
await pixelmap.opacity(rate);
}
```
......@@ -549,12 +581,8 @@ createAlphaPixelmap(): Promise\<PixelMap>
**示例:**
```js
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
if (alphaPixelMap == undefined) {
console.info('Failed to obtain new pixel map.');
} else {
console.info('Succeed in obtaining new pixel map.');
}
async function () {
await pixelmap.createAlphaPixelmap();
})
```
......@@ -575,14 +603,13 @@ createAlphaPixelmap(callback: AsyncCallback\<PixelMap>): void
**示例:**
```js
let pixelMap = await imageSource.createPixelMap();
if (pixelMap != undefined) {
pixelMap.createAlphaPixelmap(async (err, alphaPixelMap) => {
console.info('Failed to obtain new pixel map.');
})
} else {
console.info('Succeed in obtaining new pixel map.');
}
pixelmap.createAlphaPixelmap((err, alphaPixelMap) => {
if (alphaPixelMap == undefined) {
console.info('Failed to obtain new pixel map.');
} else {
console.info('Succeed in obtaining new pixel map.');
}
})
```
### scale<sup>9+</sup>
......@@ -605,7 +632,7 @@ scale(x: number, y: number, callback: AsyncCallback\<void>): void
```js
async function () {
await pixelMap.scale(2.0, 1.0);
await pixelmap.scale(2.0, 1.0);
}
```
......@@ -634,7 +661,7 @@ scale(x: number, y: number): Promise\<void>
```js
async function () {
await pixelMap.scale(2.0, 1.0);
await pixelmap.scale(2.0, 1.0);
}
```
......@@ -658,7 +685,7 @@ translate(x: number, y: number, callback: AsyncCallback\<void>): void
```js
async function () {
await pixelMap.translate(3.0, 1.0);
await pixelmap.translate(3.0, 1.0);
}
```
......@@ -687,7 +714,7 @@ translate(x: number, y: number): Promise\<void>
```js
async function () {
await pixelMap.translate(3.0, 1.0);
await pixelmap.translate(3.0, 1.0);
}
```
......@@ -710,7 +737,7 @@ rotate(angle: number, callback: AsyncCallback\<void>): void
```js
async function () {
await pixelMap.rotate(90.0);
await pixelmap.rotate(90.0);
}
```
......@@ -738,7 +765,7 @@ rotate(angle: number): Promise\<void>
```js
async function () {
await pixelMap.rotate(90.0);
await pixelmap.rotate(90.0);
}
```
......@@ -762,7 +789,7 @@ flip(horizontal: boolean, vertical: boolean, callback: AsyncCallback\<void>): vo
```js
async function () {
await pixelMap.flip(false, true);
await pixelmap.flip(false, true);
}
```
......@@ -791,7 +818,7 @@ flip(horizontal: boolean, vertical: boolean): Promise\<void>
```js
async function () {
await pixelMap.flip(false, true);
await pixelmap.flip(false, true);
}
```
......@@ -814,7 +841,7 @@ crop(region: Region, callback: AsyncCallback\<void>): void
```js
async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
}
```
......@@ -842,7 +869,7 @@ crop(region: Region): Promise\<void>
```js
async function () {
await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } });
}
```
......@@ -953,7 +980,8 @@ createImageSource(uri: string, options: SourceOptions): ImageSource
**示例:**
```js
const imageSourceApi = image.createImageSource('/sdcard/test.jpg');
var sourceOptions = { sourceDensity: 120 };
let imageSource = image.createImageSource('test.png', sourceOptions);
```
## image.createImageSource<sup>7+</sup>
......@@ -1006,7 +1034,8 @@ createImageSource(fd: number, options: SourceOptions): ImageSource
**示例:**
```js
const imageSourceApi = image.createImageSource(fd);
var sourceOptions = { sourceDensity: 120 };
const imageSourceApi = image.createImageSource(0, sourceOptions);
```
## image.createImageSource<sup>9+</sup>
......@@ -1058,9 +1087,9 @@ const data = new ArrayBuffer(112);
const imageSourceApi = image.createImageSource(data);
```
## image.CreateIncrementalSource<sup>9+</sup>
## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer): ImageSource
createIncrementalSource(buf: ArrayBuffer): ImageSource
通过缓冲区以增量的方式创建图片源实例。
......@@ -1082,12 +1111,12 @@ CreateIncrementalSource(buf: ArrayBuffer): ImageSource
```js
const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf);
const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
```
## image.CreateIncrementalSource<sup>9+</sup>
## image.createIncrementalSource<sup>9+</sup>
CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
通过缓冲区以增量的方式创建图片源实例。
......@@ -1110,7 +1139,7 @@ CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource
```js
const buf = new ArrayBuffer(96);
const imageSourceApi = image.CreateIncrementalSource(buf);
const imageSourceIncrementalSApi = image.createIncrementalSource(buf);
```
## ImageSource
......@@ -1123,7 +1152,7 @@ const imageSourceApi = image.CreateIncrementalSource(buf);
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---------------- | -------------- | ---- | ---- | ------------------------------------------------------------ |
| supportedFormats | Array\<string> | 是 | 否 | 支持的图片格式,包括:png,jpeg,wbmp,bmp,gif,webp,heif等。 |
| supportedFormats | Array\<string> | 是 | 否 | 支持的图片格式,包括:png,jpeg,bmp,gif,webp,RAW。 |
### getImageInfo
......@@ -1281,7 +1310,7 @@ getImageProperty(key:string, options: GetImagePropertyOptions, callback: AsyncCa
**示例:**
```js
const property = new ArrayBuffer(400);
let property = { index: 0, defaultValue: '9999' }
imageSourceApi.getImageProperty("BitsPerSample",property,(error,data) => {
if(error) {
console.log('Failed to get the value of the specified attribute key of the image.');
......@@ -1476,7 +1505,15 @@ createPixelMap(options: DecodingOptions, callback: AsyncCallback\<PixelMap>): vo
**示例:**
```js
const decodingOptions = new ArrayBuffer(400);
let decodingOptions = {
sampleSize: 1,
editable: true,
desiredSize: { width: 1, height: 2 },
rotate: 10,
desiredPixelFormat: 3,
desiredRegion: { size: { height: 1, width: 2 }, x: 0, y: 0 },
index: 0
};
imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
console.log('Succeeded in creating pixelmap object.');
})
......@@ -1550,7 +1587,7 @@ const imagePackerApi = image.createImagePacker();
## ImagePacker
图片打包器类,用于图片压缩和打包。在调用ImagePacker的方法前,需要先通过createImagePacker构建一个ImagePacker实例。
图片打包器类,用于图片压缩和打包。在调用ImagePacker的方法前,需要先通过createImagePacker构建一个ImagePacker实例,当前支持格式有:jpeg webp
### 属性
......@@ -1580,7 +1617,6 @@ packing(source: ImageSource, option: PackingOption, callback: AsyncCallback\<Arr
```js
let packOpts = { format:"image/jpeg", quality:98 };
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts, data => {})
```
......@@ -1609,7 +1645,6 @@ packing(source: ImageSource, option: PackingOption): Promise\<ArrayBuffer>
```js
let packOpts = { format:"image/jpeg", quality:98 }
const imageSourceApi = new ArrayBuffer(400);
imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => {
console.log('packing succeeded.');
......@@ -1761,7 +1796,7 @@ var receiver = image.createImageReceiver(8192, 8, 4, 8);
### 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.ImageReceiver
**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | ---------------------------- | ---- | ---- | ------------------ |
......@@ -1990,7 +2025,7 @@ receiver.release().then(() => {
### 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | ------------------ | ---- | ---- | -------------------------------------------------- |
......@@ -2105,20 +2140,20 @@ img.release().then(() =>{
表示图片指定区域内的数据。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ |
| pixels | ArrayBuffer | 是 | 否 | 像素。 |
| offset | number | 是 | 否 | 偏移量。 |
| stride | number | 是 | 否 | 像素间距,stride >= region.size.width*4 |
| stride | number | 是 | 否 | 像素间距,stride >= region.size.width*4 |
| region | [Region](#region7) | 是 | 否 | 区域,按照区域读写。写入的区域宽度加X坐标不能大于原图的宽度,写入的区域高度加Y坐标不能大于原图的高度。 |
## ImageInfo
表示图片信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---- | ------------- | ---- | ---- | ---------- |
......@@ -2128,7 +2163,7 @@ img.release().then(() =>{
表示图片尺寸。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------ | ------ | ---- | ---- | -------------- |
......@@ -2139,33 +2174,33 @@ img.release().then(() =>{
枚举,图片像素格式。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 默认值 | 描述 |
| ---------------------- | ------ | ----------------- |
| UNKNOWN | 0 | 未知格式。 |
| RGB_565 | 2 | 格式为RGB_565 |
| RGBA_8888 | 3 | 格式为RGBA_8888 |
| BGRA_8888<sup>9+</sup> | 4 | 格式为BGRA_8888 |
| RGBA_8888 | 3 | 格式为RGBA_8888 |
| BGRA_8888<sup>9+</sup> | 4 | 格式为BGRA_8888 |
## AlphaType<sup>9+</sup>
枚举,图像的透明度类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 默认值 | 描述 |
| -------- | ------ | ----------------------- |
| UNKNOWN | 0 | 未知透明度。 |
| OPAQUE | 1 | 没有alpha或图片全透明。 |
| PREMUL | 2 | RGB前乘alpha |
| UNPREMUL | 3 | RGB不前乘alpha |
| PREMUL | 2 | RGB前乘alpha |
| UNPREMUL | 3 | RGB不前乘alpha |
## ScaleMode<sup>9+</sup>
枚举,图像的缩放模式。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 默认值 | 描述 |
| --------------- | ------ | -------------------------------------------------- |
......@@ -2176,7 +2211,7 @@ img.release().then(() =>{
ImageSource的初始化选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------- | ---------------------------------- | ---- | ---- | ------------------ |
......@@ -2189,7 +2224,7 @@ ImageSource的初始化选项。
PixelMap的初始化选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------------ | ---------------------------------- | ---- | ---- | -------------- |
......@@ -2203,7 +2238,7 @@ PixelMap的初始化选项。
图像解码设置选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.ImageSource
**系统能力:** SystemCapability.Multimedia.Image.ImageSource
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------------ | ---------------------------------- | ---- | ---- | ---------------- |
......@@ -2219,7 +2254,7 @@ PixelMap的初始化选项。
表示区域信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ---- | ------------- | ---- | ---- | ------------ |
......@@ -2231,18 +2266,18 @@ PixelMap的初始化选项。
表示图片打包选项。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.ImagePacker
**系统能力:** SystemCapability.Multimedia.Image.ImagePacker
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------- | ------ | ---- | ---- | --------------------------------------------------- |
| format | string | 是 | 是 | 目标格式。</br>当前支持格式有:.jpg .png .gif .bmp .webp RAW。 |
| quality | number | 是 | 是 | JPEG编码中设定输出图片质量的参数,取值范围为1-100 |
| format | string | 是 | 是 | 目标格式。</br>当前支持格式有:jpeg webp |
| quality | number | 是 | 是 | JPEG编码中设定输出图片质量的参数,取值范围为1-100 |
## GetImagePropertyOptions<sup>7+</sup>
表示查询图片属性的索引。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.ImageSource
**系统能力:** SystemCapability.Multimedia.Image.ImageSource
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------ | ------ | ---- | ---- | ------------ |
......@@ -2253,7 +2288,7 @@ PixelMap的初始化选项。
枚举,Exif(Exchangeable image file format)图片信息。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 默认值 | 说明 |
| ----------------- | ----------------------- | ------------------------ |
......@@ -2270,7 +2305,7 @@ PixelMap的初始化选项。
枚举,图片格式。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 默认值 | 描述 |
| ------------ | ------ | -------------------- |
......@@ -2281,20 +2316,20 @@ PixelMap的初始化选项。
枚举,图像的组件类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.ImageReceiver
**系统能力:** SystemCapability.Multimedia.Image.ImageReceiver
| 名称 | 默认值 | 描述 |
| ----- | ------ | ----------- |
| YUV_Y | 1 | 亮度信息。 |
| YUV_U | 2 | 色度信息。 |
| YUV_V | 3 | 色度信息。 |
| JPEG | 4 | Jpeg 类型。 |
| JPEG | 4 | JPEG 类型。 |
## Component<sup>9+</sup>
描述图像颜色分量。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Image.Core
**系统能力:** SystemCapability.Multimedia.Image.Core
| 名称 | 类型 | 可读 | 可写 | 说明 |
| ------------- | -------------------------------- | ---- | ---- | ------------ |
......
......@@ -47,8 +47,8 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"};
'bundleName': 'com.example.myapp',
'abilityName': 'MyAbility'};
this.context.startAbility(want, (err) => {
console.log('startAbility result:' + JSON.stringify(err));
});
......@@ -79,8 +79,8 @@ startAbility(want: Want, options?: StartOptions): Promise\<void>;
```js
let want = {
"bundleName": "com.example.myapp",
"abilityName": "MyAbility"
'bundleName': 'com.example.myapp',
'abilityName': 'MyAbility'
};
this.context.startAbility(want).then((data) => {
console.log('success:' + JSON.stringify(data));
......@@ -110,15 +110,15 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
```js
var want = {
"deviceId": "",
"bundleName": "com.extreme.test",
"abilityName": "MainAbility"
'deviceId': '',
'bundleName': 'com.extreme.test',
'abilityName': 'MainAbility'
};
var options = {
windowMode: 0,
};
this.context.startAbility(want, options, (error) => {
console.log("error.code = " + error.code)
console.log('error.code = ' + error.code)
})
```
......
......@@ -94,15 +94,15 @@ switchInputMethod(target: InputMethodProperty, callback: AsyncCallback&lt;boolea
**示例:**
```js
inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"} ,(err,result) => {
inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'} ,(err,result) => {
if (err) {
console.error("switchInputMethod err: " + JSON.stringify(err));
console.error('switchInputMethod err: ' + JSON.stringify(err));
return;
}
if (result) {
console.info("Success to switchInputMethod.(callback)");
console.info('Success to switchInputMethod.(callback)');
} else {
console.error("Failed to switchInputMethod.(callback)");
console.error('Failed to switchInputMethod.(callback)');
}
});
```
......@@ -129,14 +129,14 @@ switchInputMethod(target: InputMethodProperty): Promise&lt;boolean&gt;
```js
inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"}).then((result) => {
inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => {
if (result) {
console.info("Success to switchInputMethod.(promise)");
console.info('Success to switchInputMethod.(promise)');
} else {
console.error("Failed to switchInputMethod.(promise)");
console.error('Failed to switchInputMethod.(promise)');
}
}).catch((err) => {
console.error("switchInputMethod promise err: " + err);
console.error('switchInputMethod promise err: ' + err);
})
```
## inputMethod.getCurrentInputMethod<sup>9+</sup>
......@@ -183,13 +183,13 @@ stopInput(callback: AsyncCallback&lt;boolean&gt;): void
```js
InputMethodController.stopInput((error, result) => {
if (error) {
console.error("failed to stopInput because: " + JSON.stringify(error));
console.error('failed to stopInput because: ' + JSON.stringify(error));
return;
}
if (result) {
console.info("Success to stopInput.(callback)");
console.info('Success to stopInput.(callback)');
} else {
console.error("Failed to stopInput.(callback)");
console.error('Failed to stopInput.(callback)');
}
});
```
......@@ -214,12 +214,12 @@ stopInput(): Promise&lt;boolean&gt;
```js
InputMethodController.stopInput().then((result) => {
if (result) {
console.info("Success to stopInput.(promise)");
console.info('Success to stopInput.(promise)');
} else {
console.error("Failed to stopInput.(promise)");
console.error('Failed to stopInput.(promise)');
}
}).catch((err) => {
console.error("stopInput promise err: " + err);
console.error('stopInput promise err: ' + err);
})
```
......@@ -241,7 +241,7 @@ showSoftKeyboard(callback: AsyncCallback&lt;void&gt;): void
```js
InputMethodController.showSoftKeyboard((err) => {
if (err == undefined) {
if (err === undefined) {
console.info('showSoftKeyboard success');
} else {
console.error('showSoftKeyboard failed because : ' + JSON.stringify(err));
......@@ -292,7 +292,7 @@ hideSoftKeyboard(callback: AsyncCallback&lt;void&gt;): void
```js
InputMethodController.hideSoftKeyboard((err) => {
if (err == undefined) {
if (err === undefined) {
console.info('hideSoftKeyboard success');
} else {
console.error('hideSoftKeyboard failed because : ' + JSON.stringify(err));
......@@ -347,14 +347,12 @@ listInputMethod(enable: boolean, callback: AsyncCallback&lt;Array&lt;InputMethod
**示例:**
```js
imeList: Array<inputMethod.InputMethodProperty> = null
InputMethodSetting.listInputMethod(true, (err,data) => {
if (err) {
console.error("listInputMethod failed because: " + JSON.stringify(err));
console.error('listInputMethod failed because: ' + JSON.stringify(err));
return;
}
console.log("listInputMethod success");
this.imeList = data;
console.log('listInputMethod success');
});
```
......@@ -381,12 +379,10 @@ listInputMethod(enable: boolean): Promise&lt;Array&lt;InputMethodProperty&gt;&gt
**示例:**
```js
imeList: Array<inputMethod.InputMethodProperty> = null
InputMethodSetting.listInputMethod(true).then((data) => {
console.info("listInputMethod success");
this.imeList = data;
console.info('listInputMethod success');
}).catch((err) => {
console.error("listInputMethod promise err: " + err);
console.error('listInputMethod promise err: ' + err);
})
```
......@@ -407,14 +403,12 @@ listInputMethod(callback: AsyncCallback&lt;Array&lt;InputMethodProperty&gt;&gt;)
**示例:**
```js
imeList: Array<inputMethod.InputMethodProperty> = null
InputMethodSetting.listInputMethod((err,data) => {
if (err) {
console.error("listInputMethod failed because: " + JSON.stringify(err));
console.error('listInputMethod failed because: ' + JSON.stringify(err));
return;
}
console.log("listInputMethod success");
this.imeList = data;
console.log('listInputMethod success');
});
```
......@@ -435,12 +429,10 @@ listInputMethod(): Promise&lt;Array&lt;InputMethodProperty&gt;&gt;
**示例:**
```js
imeList: Array<inputMethod.InputMethodProperty> = null
InputMethodSetting.listInputMethod().then((data) => {
console.info("listInputMethod success");
this.imeList = data;
console.info('listInputMethod success');
}).catch((err) => {
console.error("listInputMethod promise err: " + err);
console.error('listInputMethod promise err: ' + err);
})
```
......@@ -463,10 +455,10 @@ displayOptionalInputMethod(callback: AsyncCallback&lt;void&gt;): void
```js
InputMethodSetting.displayOptionalInputMethod((err) => {
if (err) {
console.error("displayOptionalInputMethod failed because: " + JSON.stringify(err));
console.error('displayOptionalInputMethod failed because: ' + JSON.stringify(err));
return;
}
console.info("displayOptionalInputMethod success");
console.info('displayOptionalInputMethod success');
});
```
......@@ -488,8 +480,8 @@ InputMethodSetting.displayOptionalInputMethod((err) => {
```js
InputMethodSetting.displayOptionalInputMethod().then(() => {
console.info("displayOptionalInputMethod success.(promise)");
console.info('displayOptionalInputMethod success.(promise)');
}).catch((err) => {
console.error("displayOptionalInputMethod promise err: " + err);
console.error('displayOptionalInputMethod promise err: ' + err);
})
```
\ No newline at end of file
......@@ -140,7 +140,7 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC
```js
InputMethodEngine.off('inputStart', (kbController, textInputClient) => {
console.log("delete inputStart notification.");
console.log('delete inputStart notification.');
});
```
......@@ -163,7 +163,7 @@ on(type: 'inputStop', callback: () => void): void
```js
InputMethodEngine.getInputMethodEngine().on('inputStop', () => {
console.log("inputMethodEngine inputStop");
console.log('inputMethodEngine inputStop');
});
```
......@@ -186,7 +186,7 @@ off(type: 'inputStop', callback: () => void): void
```js
InputMethodEngine.getInputMethodEngine().off('inputStop', () => {
console.log("inputMethodEngine delete inputStop notification.");
console.log('inputMethodEngine delete inputStop notification.');
});
```
......@@ -209,7 +209,7 @@ on(type: 'setCallingWindow', callback: (wid:number) => void): void
```js
InputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => {
console.log("inputMethodEngine setCallingWindow");
console.log('inputMethodEngine setCallingWindow');
});
```
......@@ -232,7 +232,7 @@ off(type: 'setCallingWindow', callback: (wid:number) => void): void
```js
InputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => {
console.log("inputMethodEngine delete setCallingWindow notification.");
console.log('inputMethodEngine delete setCallingWindow notification.');
});
```
......@@ -255,10 +255,10 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void
```js
InputMethodEngine.on('keyboardShow', () => {
console.log("inputMethodEngine keyboardShow.");
console.log('inputMethodEngine keyboardShow.');
});
InputMethodEngine.on('keyboardHide', () => {
console.log("inputMethodEngine keyboardHide.");
console.log('inputMethodEngine keyboardHide.');
});
```
......@@ -281,10 +281,10 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void
```js
InputMethodEngine.off('keyboardShow', () => {
console.log("inputMethodEngine delete keyboardShow notification.");
console.log('inputMethodEngine delete keyboardShow notification.');
});
InputMethodEngine.off('keyboardHide', () => {
console.log("inputMethodEngine delete keyboardHide notification.");
console.log('inputMethodEngine delete keyboardHide notification.');
});
```
......@@ -314,13 +314,13 @@ on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void
```js
KeyboardDelegate.on('keyUp', (keyEvent) => {
console.info("inputMethodEngine keyCode.(keyUp):" + JSON.stringify(keyEvent.keyCode));
console.info("inputMethodEngine keyAction.(keyUp):" + JSON.stringify(keyEvent.keyAction));
console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode));
console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction));
return true;
});
KeyboardDelegate.on('keyDown', (keyEvent) => {
console.info("inputMethodEngine keyCode.(keyDown):" + JSON.stringify(keyEvent.keyCode));
console.info("inputMethodEngine keyAction.(keyDown):" + JSON.stringify(keyEvent.keyAction));
console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode));
console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction));
return true;
});
```
......@@ -344,11 +344,11 @@ off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void
```js
KeyboardDelegate.off('keyUp', (keyEvent) => {
console.log("delete keyUp notification.");
console.log('delete keyUp notification.');
return true;
});
KeyboardDelegate.off('keyDown', (keyEvent) => {
console.log("delete keyDown notification.");
console.log('delete keyDown notification.');
return true;
});
```
......@@ -374,9 +374,9 @@ on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) =
```js
KeyboardDelegate.on('cursorContextChange', (x, y, height) => {
console.log("inputMethodEngine cursorContextChange x:" + x);
console.log("inputMethodEngine cursorContextChange y:" + y);
console.log("inputMethodEngine cursorContextChange height:" + height);
console.log('inputMethodEngine cursorContextChange x:' + x);
console.log('inputMethodEngine cursorContextChange y:' + y);
console.log('inputMethodEngine cursorContextChange height:' + height);
});
```
......@@ -400,7 +400,7 @@ off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number)
```js
KeyboardDelegate.off('cursorContextChange', (x, y, height) => {
console.log("delete cursorContextChange notification.");
console.log('delete cursorContextChange notification.');
});
```
### on('selectionChange')
......@@ -422,10 +422,10 @@ on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegi
```js
KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => {
console.log("inputMethodEngine beforeEach selectionChange oldBegin:" + oldBegin);
console.log("inputMethodEngine beforeEach selectionChange oldEnd:" + oldEnd);
console.log("inputMethodEngine beforeEach selectionChange newBegin:" + newBegin);
console.log("inputMethodEngine beforeEach selectionChange newEnd:" + newEnd);
console.log('inputMethodEngine beforeEach selectionChange oldBegin:' + oldBegin);
console.log('inputMethodEngine beforeEach selectionChange oldEnd:' + oldEnd);
console.log('inputMethodEngine beforeEach selectionChange newBegin:' + newBegin);
console.log('inputMethodEngine beforeEach selectionChange newEnd:' + newEnd);
});
```
......@@ -448,7 +448,7 @@ off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBe
```js
KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => {
console.log("delete selectionChange notification.");
console.log('delete selectionChange notification.');
});
```
......@@ -472,7 +472,7 @@ on(type: 'textChange', callback: (text: string) => void): void
```js
KeyboardDelegate.on('textChange', (text) => {
console.log("inputMethodEngine textChange. text:" + text);
console.log('inputMethodEngine textChange. text:' + text);
});
```
......@@ -495,7 +495,7 @@ off(type: 'textChange', callback?: (text: string) => void): void
```js
keyboardDelegate.off('textChange', (text) => {
console.log("delete textChange notification. text:" + text);
console.log('delete textChange notification. text:' + text);
});
```
......@@ -522,11 +522,11 @@ hideKeyboard(callback: AsyncCallback&lt;void&gt;): void
```js
KeyboardController.hideKeyboard((err) => {
if (err == undefined) {
console.error("hideKeyboard callback result---err: " + err.msg);
if (err === undefined) {
console.error('hideKeyboard callback result---err: ' + err.msg);
return;
}
console.log("hideKeyboard callback.");
console.log('hideKeyboard callback.');
});
```
......@@ -549,9 +549,9 @@ hideKeyboard(): Promise&lt;void&gt;
```js
async function InputMethodEngine() {
await KeyboardController.hideKeyboard().then(() => {
console.info("hideKeyboard promise.");
console.info('hideKeyboard promise.');
}).catch((err) => {
console.info("hideKeyboard promise err: " + err.msg);
console.info('hideKeyboard promise err: ' + err.msg);
});
}
```
......@@ -580,11 +580,11 @@ getForward(length:number, callback: AsyncCallback&lt;string&gt;): void
```js
var length = 1;
TextInputClient.getForward(length, (err, text) => {
if (err == undefined) {
console.error("getForward callback result---err: " + err.msg);
if (err === undefined) {
console.error('getForward callback result---err: ' + err.msg);
return;
}
console.log("getForward callback result---text: " + text);
console.log('getForward callback result---text: ' + text);
});
```
......@@ -614,9 +614,9 @@ getForward(length:number): Promise&lt;string&gt;
async function InputMethodEngine() {
var length = 1;
await TextInputClient.getForward(length).then((text) => {
console.info("getForward promise result---res: " + text);
console.info('getForward promise result---res: ' + text);
}).catch((err) => {
console.error("getForward promise err: " + err.msg);
console.error('getForward promise err: ' + err.msg);
});
}
```
......@@ -641,11 +641,11 @@ getBackward(length:number, callback: AsyncCallback&lt;string&gt;): void
```js
var length = 1;
TextInputClient.getBackward(length, (err, text) => {
if (err == undefined) {
console.error("getBackward callback result---err: " + err.msg);
if (err === undefined) {
console.error('getBackward callback result---err: ' + err.msg);
return;
}
console.log("getBackward callback result---text: " + text);
console.log('getBackward callback result---text: ' + text);
});
```
......@@ -675,9 +675,9 @@ getBackward(length:number): Promise&lt;string&gt;
async function InputMethodEngine() {
var length = 1;
await TextInputClient.getBackward(length).then((text) => {
console.info("getBackward promise result---res: " + text);
console.info('getBackward promise result---res: ' + text);
}).catch((err) => {
console.error("getBackward promise err: " + err.msg);
console.error('getBackward promise err: ' + err.msg);
});
}
```
......@@ -702,14 +702,14 @@ deleteForward(length:number, callback: AsyncCallback&lt;boolean&gt;): void
```js
var length = 1;
TextInputClient.deleteForward(length, (err, result) => {
if (err == undefined) {
if (err === undefined) {
console.error('deleteForward callback result---err: ' + err.msg);
return;
}
if (result) {
console.info("Success to deleteForward.(callback) ");
console.info('Success to deleteForward.(callback) ');
} else {
console.error("Failed to deleteForward.(callback) ");
console.error('Failed to deleteForward.(callback) ');
}
});
```
......@@ -740,12 +740,12 @@ async function InputMethodEngine() {
var length = 1;
await TextInputClient.deleteForward(length).then((result) => {
if (result) {
console.info("Success to deleteForward.(promise) ");
console.info('Success to deleteForward.(promise) ');
} else {
console.error("Failed to deleteForward.(promise) ");
console.error('Failed to deleteForward.(promise) ');
}
}).catch((err) => {
console.error("deleteForward promise err: " + err.msg);
console.error('deleteForward promise err: ' + err.msg);
});
}
```
......@@ -770,14 +770,14 @@ deleteBackward(length:number, callback: AsyncCallback&lt;boolean&gt;): void
```js
var length = 1;
TextInputClient.deleteBackward(length, (err, result) => {
if (err == undefined) {
console.error("deleteBackward callback result---err: " + err.msg);
if (err === undefined) {
console.error('deleteBackward callback result---err: ' + err.msg);
return;
}
if (result) {
console.info("Success to deleteBackward.(callback) ");
console.info('Success to deleteBackward.(callback) ');
} else {
console.error("Failed to deleteBackward.(callback) ");
console.error('Failed to deleteBackward.(callback) ');
}
});
```
......@@ -809,12 +809,12 @@ async function InputMethodEngine() {
var length = 1;
await TextInputClient.deleteBackward(length).then((result) => {
if (result) {
console.info("Success to deleteBackward.(promise) ");
console.info('Success to deleteBackward.(promise) ');
} else {
console.error("Failed to deleteBackward.(promise) ");
console.error('Failed to deleteBackward.(promise) ');
}
}).catch((err) => {
console.error("deleteBackward promise err: " + err.msg);
console.error('deleteBackward promise err: ' + err.msg);
});
}
```
......@@ -837,14 +837,14 @@ sendKeyFunction(action:number, callback: AsyncCallback&lt;boolean&gt;): void
```js
TextInputClient.sendKeyFunction(keyFunction, (err, result) => {
if (err == undefined) {
console.error("sendKeyFunction callback result---err: " + err.msg);
if (err === undefined) {
console.error('sendKeyFunction callback result---err: ' + err.msg);
return;
}
if (result) {
console.info("Success to sendKeyFunction.(callback) ");
console.info('Success to sendKeyFunction.(callback) ');
} else {
console.error("Failed to sendKeyFunction.(callback) ");
console.error('Failed to sendKeyFunction.(callback) ');
}
});
```
......@@ -875,12 +875,12 @@ sendKeyFunction(action:number): Promise&lt;boolean&gt;
async function InputMethodEngine() {
await client.sendKeyFunction(keyFunction).then((result) => {
if (result) {
console.info("Success to sendKeyFunction.(promise) ");
console.info('Success to sendKeyFunction.(promise) ');
} else {
console.error("Failed to sendKeyFunction.(promise) ");
console.error('Failed to sendKeyFunction.(promise) ');
}
}).catch((err) => {
console.error("sendKeyFunction promise err:" + err.msg);
console.error('sendKeyFunction promise err:' + err.msg);
});
}
```
......@@ -904,14 +904,14 @@ insertText(text:string, callback: AsyncCallback&lt;boolean&gt;): void
```js
TextInputClient.insertText('test', (err, result) => {
if (err == undefined) {
console.error("insertText callback result---err: " + err.msg);
if (err === undefined) {
console.error('insertText callback result---err: ' + err.msg);
return;
}
if (result) {
console.info("Success to insertText.(callback) ");
console.info('Success to insertText.(callback) ');
} else {
console.error("Failed to insertText.(callback) ");
console.error('Failed to insertText.(callback) ');
}
});
```
......@@ -942,12 +942,12 @@ insertText(text:string): Promise&lt;boolean&gt;
async function InputMethodEngine() {
await TextInputClient.insertText('test').then((result) => {
if (result) {
console.info("Success to insertText.(promise) ");
console.info('Success to insertText.(promise) ');
} else {
console.error("Failed to insertText.(promise) ");
console.error('Failed to insertText.(promise) ');
}
}).catch((err) => {
console.error("insertText promise err: " + err.msg);
console.error('insertText promise err: ' + err.msg);
});
}
```
......@@ -970,12 +970,12 @@ getEditorAttribute(callback: AsyncCallback&lt;EditorAttribute&gt;): void
```js
TextInputClient.getEditorAttribute((err, editorAttribute) => {
if (err == undefined) {
console.error("getEditorAttribute callback result---err: " + err.msg);
if (err === undefined) {
console.error('getEditorAttribute callback result---err: ' + err.msg);
return;
}
console.log("editorAttribute.inputPattern(callback): " + JSON.stringify(editorAttribute.inputPattern));
console.log("editorAttribute.enterKeyType(callback): " + JSON.stringify(editorAttribute.enterKeyType));
console.log('editorAttribute.inputPattern(callback): ' + JSON.stringify(editorAttribute.inputPattern));
console.log('editorAttribute.enterKeyType(callback): ' + JSON.stringify(editorAttribute.enterKeyType));
});
```
......@@ -998,10 +998,10 @@ getEditorAttribute(): Promise&lt;EditorAttribute&gt;
```js
async function InputMethodEngine() {
await TextInputClient.getEditorAttribute().then((editorAttribute) => {
console.info("editorAttribute.inputPattern(promise): " + JSON.stringify(editorAttribute.inputPattern));
console.info("editorAttribute.enterKeyType(promise): " + JSON.stringify(editorAttribute.enterKeyType));
console.info('editorAttribute.inputPattern(promise): ' + JSON.stringify(editorAttribute.inputPattern));
console.info('editorAttribute.enterKeyType(promise): ' + JSON.stringify(editorAttribute.enterKeyType));
}).catch((err) => {
console.error("getEditorAttribute promise err: " + err.msg);
console.error('getEditorAttribute promise err: ' + err.msg);
});
}
```
......@@ -1025,8 +1025,8 @@ moveCursor(direction: number, callback: AsyncCallback&lt;void&gt;): void
```js
TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => {
if (err == undefined) {
console.error("moveCursor callback result---err: " + err.msg);
if (err === undefined) {
console.error('moveCursor callback result---err: ' + err.msg);
return;
}
});
......@@ -1059,7 +1059,7 @@ async function InputMethodEngine() {
await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => {
console.log('moveCursor success');
}).catch((err) => {
console.error("moveCursor success err: " + err.msg);
console.error('moveCursor success err: ' + err.msg);
});
}
```
......
......@@ -52,7 +52,7 @@ createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 异步创建视频播放实例回调方法。 |
| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | 是 | 回调函数。异步返回VideoPlayer实例,可用于管理和播放视频媒体。 |
**示例:**
......@@ -81,7 +81,7 @@ createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)>
| 类型 | 说明 |
| ------------------------------------- | ----------------------------------- |
| Promise<[VideoPlayer](#videoplayer8)> | 异步创建视频播放实例Promise返回值。 |
| Promise<[VideoPlayer](#videoplayer8)> | Promise对象。异步返回VideoPlayer实例,可用于管理和播放视频媒体。 |
**示例:**
......@@ -134,7 +134,7 @@ createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>):
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------- | ---- | ------------------------------ |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | 是 | 异步创建视频录制实例回调方法。 |
| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | 是 | 回调函数。异步返回VideoRecorder实例,可用于录制视频媒体。 |
**示例:**
......@@ -164,7 +164,7 @@ createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)>
| 类型 | 说明 |
| ----------------------------------------- | ----------------------------------- |
| Promise<[VideoRecorder](#videorecorder9)> | 异步创建视频录制实例Promise返回值。 |
| Promise<[VideoRecorder](#videorecorder9)> | Promise对象。异步返回VideoRecorder实例,可用于录制视频媒体。 |
**示例:**
......@@ -441,7 +441,7 @@ function printfDescription(obj) {
}
}
audioPlayer.getTrackDescription((error, ) => {
audioPlayer.getTrackDescription((error, arrlist) => {
if (arrlist != null) {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
......@@ -1794,7 +1794,7 @@ on(type: 'prepare' | 'start' | 'pause' | 'resume' | 'stop' | 'release' | 'reset'
```js
let audioRecorder = media.createAudioRecorder(); // 创建一个音频录制实例
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, ,
audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
......@@ -1849,7 +1849,7 @@ on(type: 'error', callback: ErrorCallback): void
```js
let audioRecorderConfig = {
audioEncoder : media.AudioEncoder.AAC_LC, ,
audioEncoder : media.AudioEncoder.AAC_LC,
audioEncodeBitRate : 22050,
audioSampleRate : 22050,
numberOfChannels : 2,
......@@ -1973,29 +1973,13 @@ let videoConfig = {
}
// asyncallback
let videoRecorder = null;
let events = require('events');
let eventEmitter = new events.EventEmitter();
eventEmitter.on('prepare', () => {
videoRecorder.prepare(videoConfig, (err) => {
if (err == null) {
console.info('prepare success');
} else {
console.info('prepare failed and error is ' + err.message);
}
});
});
media.createVideoRecorder((err, recorder) => {
if (err == null && recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
eventEmitter.emit('prepare'); // prepare事件触发
videoRecorder.prepare(videoConfig, (err) => {
if (err == null) {
console.info('prepare success');
} else {
console.info('createVideoRecorder failed and error is ' + err.message);
console.info('prepare failed and error is ' + err.message);
}
});
})
```
### prepare<sup>9+</sup><a name=videorecorder_prepare2></a>
......@@ -2046,21 +2030,10 @@ let videoConfig = {
}
// promise
let videoRecorder = null;
media.createVideoRecorder().then((recorder) => {
if (recorder != null) {
videoRecorder = recorder;
console.info('createVideoRecorder success');
videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}).catch((err) => {
console.info('prepare failed and catch error is ' + err.message);
});
} else {
console.info('createVideoRecorder failed');
}
videoRecorder.prepare(videoConfig).then(() => {
console.info('prepare success');
}).catch((err) => {
console.info('catch err error message is ' + err.message);
console.info('prepare failed and catch error is ' + err.message);
});
```
......@@ -2474,11 +2447,10 @@ on(type: 'error', callback: ErrorCallback): void
**示例:**
```js
// 当获取videoRecordState接口出错时通过此订阅事件上报
videoRecorder.on('error', (error) => { // 设置'error'事件回调
console.info(`audio error called, error: ${error}`);
}
// 当获取videoRecordState接口出错时通过此订阅事件上报
});
})
```
## VideoRecordState<sup>9+</sup>
......
......@@ -68,6 +68,8 @@ hasDefaultNet(callback: AsyncCallback\<boolean>): void
检查默认数据网络是否被激活,使用callback方式作为异步方法。
默认数据网络:以太网>Wi-Fi>蜂窝,当只有一个网络为连接状态时,当前连接网络为默认数据网络。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core
**参数:**
......@@ -92,6 +94,8 @@ hasDefaultNet(): Promise\<boolean>
检查默认数据网络是否被激活,使用Promise方式作为异步方法。
默认数据网络:以太网>Wi-Fi>蜂窝,当只有一个网络为连接状态时,当前连接网络为默认数据网络。
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Communication.NetManager.Core
**返回值:**
......
# 标准NFC
本模块主要用于操作及管理NFC
本模块主要用于管理NFC状态,包括打开和关闭NFC,读取NFC的状态等
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......@@ -12,12 +12,24 @@
import controller from '@ohos.nfc.controller';
```
## NfcState
定义不同的NFC状态值。
**系统能力**:SystemCapability.Communication.NFC.Core
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| STATE_OFF | 1 | NFC已关闭状态。 |
| STATE_TURNING_ON | 2 | NFC正在打开状态。 |
| STATE_ON | 3 | NFC已打开状态。 |
| STATE_TURNING_OFF | 4 | NFC正在关闭状态。 |
## controller.isNfcAvailable
isNfcAvailable(): boolean
查询是否有NFC功能
查询设备是否有NFC能力。
**系统能力**:SystemCapability.Communication.NFC.Core
......@@ -25,7 +37,7 @@ isNfcAvailable(): boolean
| **类型** | **说明** |
| -------- | -------- |
| boolean | true:有NFC功能,&nbsp;false:无NFC功能。 |
| boolean | true: 设备具备NFC能力,&nbsp;false: 设备不具备NFC能力。 |
## controller.openNfc
......@@ -42,7 +54,7 @@ openNfc(): boolean
| **类型** | **说明** |
| -------- | -------- |
| boolean | true:打开NFC成功,&nbsp;false:打开NFC失败。 |
| boolean | true: 打开NFC成功,&nbsp;false: 打开NFC失败。 |
## controller.closeNfc
......@@ -58,7 +70,7 @@ closeNfc(): boolean
| **类型** | **说明** |
| -------- | ------------------------------------------- |
| boolean | true:关闭NFC成功,&nbsp;false:关闭NFC失败。 |
| boolean | true: 关闭NFC成功,&nbsp;false: 关闭NFC失败。 |
## controller.isNfcOpen
......@@ -72,11 +84,11 @@ isNfcOpen(): boolean
| **类型** | **说明** |
| -------- | ----------------------------------- |
| boolean | true:NFC打开,&nbsp;false:NFC关闭。 |
| boolean | true: NFC是打开的,&nbsp;false: NFC是关闭的。 |
## controller.getNfcState
getNfcState(): NfcState
getNfcState(): [NfcState](#nfcstate)
查询NFC状态。
......@@ -86,13 +98,13 @@ getNfcState(): NfcState
| **类型** | **说明** |
| -------- | ---------------------- |
| NfcState | 详细请见NfcState枚举值 |
| [NfcState](#nfcstate) | NFC状态值,详细请见[NfcState](#nfcstate)枚举值。 |
## controller.on('nfcStateChange')
on(type: "nfcStateChange", callback: Callback&lt;NfcState&gt;): void
on(type: "nfcStateChange", callback: Callback&lt;[NfcState](#nfcstate)&gt;): void
注册NFC开关状态事件。
注册NFC开关状态事件,通过Callback方式获取NFC状态的变化通知
**系统能力**:SystemCapability.Communication.NFC.Core
......@@ -100,16 +112,16 @@ on(type: "nfcStateChange", callback: Callback&lt;NfcState&gt;): void
| **参数名** | **类型** | **必填** | **说明** |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 固定填"nfcStateChange"字符串 |
| callback | Callback&lt;NfcState&gt; | 是 | 状态改变回调函数。 |
| type | string | 是 | 固定填"nfcStateChange"字符串 |
| callback | Callback&lt;[NfcState](#nfcstate)&gt; | 是 | NFC状态改变通知的回调函数。 |
## controller.off('nfcStateChange')
off(type: "nfcStateChange", callback?: Callback&lt;NfcState&gt;): void
off(type: "nfcStateChange", callback?: Callback&lt;[NfcState](#nfcstate)&gt;): void
取消NFC开关状态事件的注册。
取消NFC开关状态事件的注册,取消后NFC状态变化时,就不会再收到Callback的通知
**系统能力**:SystemCapability.Communication.NFC.Core
......@@ -117,36 +129,38 @@ off(type: "nfcStateChange", callback?: Callback&lt;NfcState&gt;): void
| **参数名** | **类型** | **必填** | **说明** |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 固定填"nfcStateChange"字符串 |
| callback | Callback&lt;NfcState&gt; | 否 | 状态改变回调函数。如果callback不填,将“去注册”该事件关联的所有回调函数。 |
| type | string | 是 | 固定填"nfcStateChange"字符串 |
| callback | Callback&lt;[NfcState](#nfcstate)&gt; | 否 | NFC状态改变回调函数,可以空缺不填。 |
**示例**
```js
import nfcController from '@ohos.nfcController';
var NFC_STATE_NOTIFY = "nfcStateChange";
var recvNfcStateNotifyFunc = result => {
console.info("nfc state receive state: " + result);
import controller from '@ohos.nfc.controller';
// callback key definition
var NFC_STATE_CALLBACK_KEY = "nfcStateChange";
// register callback to receive the nfc state changed notification
controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> {
if (err) {
console.log("controller on callback err: " + err);
} else {
console.log("controller on callback nfcState: " + nfcState);
}
});
// open nfc, require permission: ohos.permission.MANAGE_SECURE_SETTINGS
if (!controller.isNfcOpen()) {
var ret = controller.openNfc();
console.log("controller openNfc ret: " + ret);
}
// 注册事件
nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc);
// 解注册事件
nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc);
```
## NfcState
表示NFC状态的枚举。
**系统能力**:SystemCapability.Communication.NFC.Core
// close nfc, require permission: ohos.permission.MANAGE_SECURE_SETTINGS
if (controller.isNfcOpen()) {
var ret = controller.closeNfc();
console.log("controller closeNfc ret: " + ret);
}
| 名称 | 默认值 | 说明 |
| -------- | -------- | -------- |
| STATE_OFF | 1 | NFC关闭状态 |
| STATE_TURNING_ON | 2 | NFC正在打开状态 |
| STATE_ON | 3 | NFC打开状态 |
| STATE_TURNING_OFF | 4 | NFC正在关闭状态 |
// unregister callback
controller.off(NFC_STATE_CALLBACK_KEY);
```
......@@ -384,6 +384,26 @@ promise.then(data => {
});
```
## radio.isNrSupported<sup>7+</sup>
isNrSupported\(\): boolean
判断当前设备是否支持5G\(NR\)
**系统能力**:SystemCapability.Telephony.CoreService
**返回值:**
| 类型 | 说明 |
| ------- | -------------------------------- |
| boolean | - true:支持<br/>- false:不支持 |
**示例:**
```js
let result = radio.isNrSupported();
console.log("Result: "+ result);
```
## radio.isNrSupported<sup>8+</sup>
......
......@@ -2620,11 +2620,11 @@ queryLocalInterface(descriptor: string): IRemoteBroker
### sendRequest<sup>(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
> **说明:**
> 从 API Version 8 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2647,11 +2647,11 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options
### sendRequest<sup>8+(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
> **说明:**
> 从 API Version 9 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2806,11 +2806,11 @@ isObjectDead(): boolean
### sendRequest<sup>(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
> **说明:**
> 从 API Version 8 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9-1)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -2873,11 +2873,11 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options
### sendRequest<sup>8+(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
> **说明:**
> 从 API Version 9 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9-1)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -3725,11 +3725,11 @@ RemoteObject构造函数。
### sendRequest<sup>(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
> **说明:**
> 从 API Version 8 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9-2)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -3794,11 +3794,11 @@ sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options
### sendRequest<sup>8+(deprecated)</sup>
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
> **说明:**
> 从 API Version 9 开始废弃,建议使用[sendRequestAsync<sup>9+</sup>](#sendrequestasync9-2)替代。
sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise&lt;SendRequestResult&gt;
以同步或异步方式向对端进程发送MessageParcel消息。如果为选项设置了异步模式,则期约立即兑现,reply报文里没有内容。如果为选项设置了同步模式,则期约将在sendRequest返回时兑现,回复内容在reply报文里。
**系统能力**:SystemCapability.Communication.IPC.Core
......@@ -4004,6 +4004,7 @@ sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: Me
onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean
> **说明:**
> 从 API Version 9 开始废弃,建议使用[onRemoteRequestEx<sup>9+</sup>](#onremoterequestex9)替代。
......
......@@ -2657,8 +2657,6 @@ getOpKey(slotId: number, callback: AsyncCallback<string\>): void
获取指定卡槽中SIM卡的opkey。使用callback异步回调。
此接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService
**参数:**
......@@ -2683,8 +2681,6 @@ getOpKey(slotId: number): Promise<string\>
获取指定卡槽中SIM卡的opkey。使用Promise异步回调。
此接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService
**参数:**
......@@ -2716,8 +2712,6 @@ getOpName(slotId: number, callback: AsyncCallback<string\>): void
获取指定卡槽中SIM卡的OpName。使用callback异步回调。
此接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService
**参数:**
......@@ -2742,8 +2736,6 @@ getOpName(slotId: number): Promise<string\>
获取指定卡槽中SIM卡的OpName。使用Promise异步回调。
此接口为系统接口。
**系统能力**:SystemCapability.Telephony.CoreService
**参数:**
......
......@@ -9,7 +9,7 @@
```js
import cipher from '@system.cipher'
import cipher from '@system.cipher';
```
......
......@@ -330,10 +330,10 @@ createTimer的初始化选项。
**系统能力:** SystemCapability.MiscServices.Time
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------| ---- | ----------------------------------------------------------------------------------------------- |
| type | number | 是 | const TIMER_TYPE_REALTIME: 设置为系统启动时间定时器,否则为walltime定时器; <br/>const TIMER_TYPE_WAKEUP: 设置为唤醒定时器,否则为非唤醒; <br/>const TIMER_TYPE_EXACT: 设置为精准定时器,否则为非精准定时器; <br/>const TIMER_TYPE_IDLE: number: 设置为IDLE模式定时器,否则为非IDLE模式定时器(暂不支持) |
| repeat | boolean | 是 | true 为循环定时器,false为单次定时器。 |
| interval | number | 否 | 如果是循环定时器,repeat值应大于5000毫秒,非重复定时器置为0。 |
| wantAgent| wantAgent | 否 | 设置通知的wantagent,定时器到期后通知。(支持拉起应用MainAbility,暂不支持拉起ServiceAbility) |
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------| ---- | ------------------------------------------------------------------------------------------------------------------------- |
| type | number | 是 | const TIMER_TYPE_REALTIME: 设置为系统启动时间定时器(当设置系统时间超过定时器启动时间,定时器则失效),否则为walltime定时器; <br/>const TIMER_TYPE_WAKEUP: 设置为唤醒定时器,否则为非唤醒; <br/>const TIMER_TYPE_EXACT: 设置为精准定时器,否则为非精准定时器; <br/>const TIMER_TYPE_IDLE: number: 设置为IDLE模式定时器,否则为非IDLE模式定时器(暂不支持) |
| repeat | boolean | 是 | true 为循环定时器,false为单次定时器。 |
| interval | number | 否 | 如果是循环定时器,repeat值应大于5000毫秒,非重复定时器置为0。 |
| wantAgent| wantAgent | 否 | 设置通知的wantagent,定时器到期后通知。(支持拉起应用MainAbility,暂不支持拉起ServiceAbility) |
| callback | number | 是 | 以回调函数的形式返回定时器的ID |
\ No newline at end of file
......@@ -63,6 +63,28 @@ promise.then((data) => {
});
```
## data.getDefaultCellularDataSlotIdSync
getDefaultCellularDataSlotIdSync(): number
获取默认移动数据的SIM卡
**需要权限**:ohos.permission.GET_NETWORK_INFO
**系统能力**:SystemCapability.Telephony.CellularData
**返回值:**
| 类型 | 说明 |
| ------ | -------------------------------------------------- |
| number | 获取默认移动数据的SIM卡。<br />0:卡槽1。<br />1:卡槽2。 |
**示例:**
```js
console.log("Result: "+ data.getDefaultCellularDataSlotIdSync())
```
## data.setDefaultCellularDataSlotId
setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\<void\>): void
......
......@@ -31,25 +31,25 @@ getOnlineUpdater(upgradeInfo: UpgradeInfo): Updater
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------------------- | ---- | ------ |
| upgradeInfo | [UpgradeInfo](#upgradeinfo) | 是 | 升级信息对象 |
| upgradeInfo | [UpgradeInfo](#upgradeinfo) | 是 | 升级信息对象 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ---- |
| [Updater](#updater) | 升级对象 |
| [Updater](#updater) | 升级对象 |
**示例:**
```ts
try {
var upgradeInfo = {
const upgradeInfo = {
upgradeApp: "com.ohos.ota.updateclient",
businessType: {
vendor: update.BusinessVendor.PUBLIC,
subType: update.BusinessSubType.FIRMWARE
}
}
};
let updater = update.getOnlineUpdater(upgradeInfo);
} catch(error) {
console.error(`Fail to get updater error: ${error}`);
......@@ -69,7 +69,7 @@ getRestorer(): Restorer
| 类型 | 说明 |
| --------------------- | ------ |
| [Restorer](#restorer) | 恢复出厂对象 |
| [Restorer](#restorer) | 恢复出厂对象 |
**示例:**
......@@ -93,7 +93,7 @@ getLocalUpdater(): LocalUpdater
| 类型 | 说明 |
| ----------------------------- | ------ |
| [LocalUpdater](#localupdater) | 本地升级对象 |
| [LocalUpdater](#localupdater) | 本地升级对象 |
**示例:**
......@@ -225,23 +225,23 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption
| 参数名 | 类型 | 必填 | 说明 |
| ------------------ | ---------------------------------------- | ---- | -------------- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | 是 | 回调函数,返回新版本描述文件 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | 是 | 回调函数,返回新版本描述文件 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 描述文件选项
var descriptionOptions = {
const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // 标准格式
language: "zh-cn" // 中文
}
};
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions, (err, info) => {
console.log(`getNewVersionDescription info ${JSON.stringify(info)}`);
......@@ -263,28 +263,28 @@ getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOption
| 参数名 | 类型 | 必填 | 说明 |
| ------------------ | ---------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | ------------------- |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise对象,返回新版本描述文件 |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise对象,返回新版本描述文件 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 描述文件选项
var descriptionOptions = {
const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // 标准格式
language: "zh-cn" // 中文
}
};
updater.getNewVersionDescription(versionDigestInfo, descriptionOptions).then(info => {
console.log(`getNewVersionDescription promise info ${JSON.stringify(info)}`);
......@@ -361,17 +361,17 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: A
| 参数名 | 类型 | 必填 | 说明 |
| ------------------ | ---------------------------------------- | ---- | --------------- |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | 是 | 回调函数,返回当前版本描述文件 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| callback | AsyncCallback\<Array\<[ComponentDescription](#componentdescription)>>) | 是 | 回调函数,返回当前版本描述文件 |
**示例:**
```ts
// 描述文件选项
var descriptionOptions = {
const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // 标准格式
language: "zh-cn" // 中文
}
};
updater.getCurrentVersionDescription(descriptionOptions, (err, info) => {
console.log(`getCurrentVersionDescription info ${JSON.stringify(info)}`);
......@@ -393,22 +393,22 @@ getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise\<A
| 参数名 | 类型 | 必填 | 说明 |
| ------------------ | ---------------------------------------- | ---- | ------ |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
| descriptionOptions | [DescriptionOptions](#descriptionoptions) | 是 | 描述文件选项 |
**返回值:**
| 类型 | 说明 |
| ---------------------------------------- | -------------------- |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise对象,返回当前版本描述文件 |
| Promise\<Array\<[ComponentDescription](#componentdescription)>> | Promise对象,返回当前版本描述文件 |
**示例:**
```ts
// 描述文件选项
var descriptionOptions = {
const descriptionOptions = {
format: update.DescriptionFormat.STANDARD, // 标准格式
language: "zh-cn" // 中文
}
};
updater.getCurrentVersionDescription(descriptionOptions).then(info => {
console.log(`getCurrentVersionDescription promise info ${JSON.stringify(info)}`);
......@@ -481,23 +481,23 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions,
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ---------------------------------- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| downloadOptions | [DownloadOptions](#downloadoptions) | 是 | 下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| downloadOptions | [DownloadOptions](#downloadoptions) | 是 | 下载选项 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当下载成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 下载选项
var downloadOptions = {
const downloadOptions = {
allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载
order: update.Order.DOWNLOAD // 下载
}
};
updater.download(versionDigestInfo, downloadOptions, (err) => {
console.log(`download error ${JSON.stringify(err)}`);
});
......@@ -517,8 +517,8 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions)
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| downloadOptions | [DownloadOptions](#downloadoptions) | 是 | 下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| downloadOptions | [DownloadOptions](#downloadoptions) | 是 | 下载选项 |
**返回值:**
......@@ -530,15 +530,15 @@ download(versionDigestInfo: VersionDigestInfo, downloadOptions: DownloadOptions)
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 下载选项
var downloadOptions = {
const downloadOptions = {
allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载
order: update.Order.DOWNLOAD // 下载
}
};
updater.download(versionDigestInfo, downloadOptions).then(() => {
console.log(`download start`);
}).catch(err => {
......@@ -560,22 +560,22 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu
| 参数名 | 类型 | 必填 | 说明 |
| --------------------- | ---------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | 是 | 恢复下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | 是 | 恢复下载选项 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当恢复下载成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 恢复下载选项
var resumeDownloadOptions = {
const resumeDownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载
}
};
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions, (err) => {
console.log(`resumeDownload error ${JSON.stringify(err)}`);
});
......@@ -595,8 +595,8 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu
| 参数名 | 类型 | 必填 | 说明 |
| --------------------- | ---------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | 是 | 恢复下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | 是 | 恢复下载选项 |
**返回值:**
......@@ -608,14 +608,14 @@ resumeDownload(versionDigestInfo: VersionDigestInfo, resumeDownloadOptions: Resu
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 恢复下载选项
var resumeDownloadOptions = {
const resumeDownloadOptions = {
allowNetwork: update.NetType.CELLULAR, // 允许数据网络下载
}
};
updater.resumeDownload(versionDigestInfo, resumeDownloadOptions).then(value => {
console.log(`resumeDownload start`);
}).catch(err => {
......@@ -637,22 +637,22 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD
| 参数名 | 类型 | 必填 | 说明 |
| -------------------- | ---------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | 是 | 暂停下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | 是 | 暂停下载选项 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当暂停下载成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 暂停下载选项
var pauseDownloadOptions = {
const pauseDownloadOptions = {
isAllowAutoResume: true // 允许自动恢复下载
}
};
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions, (err) => {
console.log(`pauseDownload error ${JSON.stringify(err)}`);
});
......@@ -672,8 +672,8 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD
| 参数名 | 类型 | 必填 | 说明 |
| -------------------- | ---------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | 是 | 暂停下载选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | 是 | 暂停下载选项 |
**返回值:**
......@@ -685,14 +685,14 @@ pauseDownload(versionDigestInfo: VersionDigestInfo, pauseDownloadOptions: PauseD
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 暂停下载选项
var pauseDownloadOptions = {
const pauseDownloadOptions = {
isAllowAutoResume: true // 允许自动恢复下载
}
};
updater.pauseDownload(versionDigestInfo, pauseDownloadOptions).then(value => {
console.log(`pauseDownload`);
}).catch(err => {
......@@ -714,22 +714,22 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions, ca
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| upgradeOptions | [UpgradeOptions](#upgradeoptions) | 是 | 更新选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| upgradeOptions | [UpgradeOptions](#upgradeoptions) | 是 | 更新选项 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当升级执行成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 安装选项
var upgradeOptions = {
const upgradeOptions = {
order: update.Order.INSTALL // 安装指令
}
};
updater.upgrade(versionDigestInfo, upgradeOptions, (err) => {
console.log(`upgrade error ${JSON.stringify(err)}`);
});
......@@ -749,8 +749,8 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): P
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| upgradeOptions | [UpgradeOptions](#upgradeoptions) | 是 | 更新选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| upgradeOptions | [UpgradeOptions](#upgradeoptions) | 是 | 更新选项 |
**返回值:**
......@@ -762,14 +762,14 @@ upgrade(versionDigestInfo: VersionDigestInfo, upgradeOptions: UpgradeOptions): P
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 安装选项
var upgradeOptions = {
const upgradeOptions = {
order: update.Order.INSTALL // 安装指令
}
};
updater.upgrade(versionDigestInfo, upgradeOptions).then(() => {
console.log(`upgrade start`);
}).catch(err => {
......@@ -791,22 +791,22 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions, cal
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ------------------------------------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| clearOptions | [ClearOptions](#clearoptions) | 是 | 清除选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| clearOptions | [ClearOptions](#clearoptions) | 是 | 清除选项 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当清除异常成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 清除选项
var clearOptions = {
const clearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL,
}
};
updater.clearError(versionDigestInfo, clearOptions, (err) => {
console.log(`clearError error ${JSON.stringify(err)}`);
});
......@@ -826,8 +826,8 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Pr
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | --------------------------------------- | ---- | ------ |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| clearOptions | [ClearOptions](#clearoptions) | 是 | 更新选项 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要信息 |
| clearOptions | [ClearOptions](#clearoptions) | 是 | 更新选项 |
**返回值:**
......@@ -839,14 +839,14 @@ clearError(versionDigestInfo: VersionDigestInfo, clearOptions: ClearOptions): Pr
```ts
// 版本摘要信息
var versionDigestInfo = {
const versionDigestInfo = {
versionDigest: "versionDigest" // 检测结果中的版本摘要信息
}
};
// 清除选项
var clearOptions = {
lconstet clearOptions = {
status: update.UpgradeStatus.UPGRADE_FAIL,
}
};
updater.clearError(versionDigestInfo, clearOptions).then(() => {
console.log(`clearError success`);
}).catch(err => {
......@@ -868,7 +868,7 @@ getUpgradePolicy(callback: AsyncCallback\<UpgradePolicy>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | --------------- |
| callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | 是 | 回调函数,返回升级策略信息对象 |
| callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | 是 | 回调函数,返回升级策略信息对象 |
**示例:**
......@@ -920,17 +920,17 @@ setUpgradePolicy(policy: UpgradePolicy, callback: AsyncCallback\<void>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------- | ---- | ------------- |
| policy | [UpgradePolicy](#upgradepolicy) | 是 | 升级策略 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回设置结果对象 |
| policy | [UpgradePolicy](#upgradepolicy) | 是 | 升级策略 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回设置结果对象 |
**示例:**
```ts
let policy = {
const policy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // 自动升级时间段,用分钟表示
}
};
updater.setUpgradePolicy(policy, (err) => {
console.log(`setUpgradePolicy result: ${err}`);
});
......@@ -950,7 +950,7 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\<void>
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------------------------- | ---- | ---- |
| policy | [UpgradePolicy](#upgradepolicy) | 是 | 升级策略 |
| policy | [UpgradePolicy](#upgradepolicy) | 是 | 升级策略 |
**返回值:**
......@@ -961,11 +961,11 @@ setUpgradePolicy(policy: UpgradePolicy): Promise\<void>
**示例:**
```ts
let policy = {
const policy = {
downloadStrategy: false,
autoUpgradeStrategy: false,
autoUpgradePeriods: [ { start: 120, end: 240 } ] // 自动升级时间段,用分钟表示
}
};
updater.setUpgradePolicy(policy).then(() => {
console.log(`setUpgradePolicy success`);
}).catch(err => {
......@@ -1035,16 +1035,16 @@ on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): voi
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
**示例:**
```ts
var eventClassifyInfo = {
const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // 订阅升级更新事件
extraInfo: ""
}
};
updater.on(eventClassifyInfo, (eventInfo) => {
console.log("updater on " + JSON.stringify(eventInfo));
......@@ -1062,16 +1062,16 @@ off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): v
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 否 | 事件回调 |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 否 | 事件回调 |
**示例:**
```ts
var eventClassifyInfo = {
const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // 订阅升级更新事件
extraInfo: ""
}
};
updater.off(eventClassifyInfo, (eventInfo) => {
console.log("updater off " + JSON.stringify(eventInfo));
......@@ -1146,17 +1146,17 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string, callback: Asyn
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------------------- | ---- | ---------------- |
| upgradeFile | [UpgradeFile](#upgradefile) | 是 | 升级文件 |
| certsFile | string | 是 | 证书文件路径 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回升级包校验结果对象 |
| upgradeFile | [UpgradeFile](#upgradefile) | 是 | 升级文件 |
| certsFile | string | 是 | 证书文件路径 |
| callback | AsyncCallback\<void> | 是 | 回调函数,返回升级包校验结果对象 |
**示例:**
```ts
var upgradeFile = {
const upgradeFile = {
fileType: update.ComponentType.OTA, // OTA包
filePath: "path" // 本地升级包路径
}
};
localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath", (err) => {
console.log(`factoryReset error ${JSON.stringify(err)}`);
......@@ -1177,8 +1177,8 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\<void
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | --------------------------- | ---- | ------ |
| upgradeFile | [UpgradeFile](#upgradefile) | 是 | 升级文件 |
| certsFile | string | 是 | 证书文件路径 |
| upgradeFile | [UpgradeFile](#upgradefile) | 是 | 升级文件 |
| certsFile | string | 是 | 证书文件路径 |
**返回值:**
......@@ -1189,10 +1189,10 @@ verifyUpgradePackage(upgradeFile: UpgradeFile, certsFile: string): Promise\<void
**示例:**
```ts
var upgradeFile = {
const upgradeFile = {
fileType: update.ComponentType.OTA, // OTA包
filePath: "path" // 本地升级包路径
}
};
localUpdater.verifyUpgradePackage(upgradeFile, "cerstFilePath").then(() => {
console.log(`verifyUpgradePackage success`);
}).catch(err => {
......@@ -1213,16 +1213,16 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>, callback: Asyn
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ---------------------------------- | ---- | --------------------------------------- |
| upgradeFile | Array<[UpgradeFile](#upgradefile)> | 是 | 升级文件 |
| upgradeFile | Array<[UpgradeFile](#upgradefile)> | 是 | 升级文件 |
| callback | AsyncCallback\<void> | 是 | 回调函数。当安装升级包执行成功时,err为undefined,否则为错误对象。 |
**示例:**
```ts
var upgradeFiles = [{
const upgradeFiles = [{
fileType: update.ComponentType.OTA, // OTA包
filePath: "path" // 本地升级包路径
}]
}];
localUpdater.applyNewVersion(upgradeFiles, (err) => {
console.log(`applyNewVersion error ${JSON.stringify(err)}`);
......@@ -1248,10 +1248,10 @@ applyNewVersion(upgradeFiles: Array<[UpgradeFile](#upgradefile)>): Promise\<void
**示例:**
```ts
var upgradeFiles = [{
localUpdater upgradeFiles = [{
fileType: update.ComponentType.OTA, // OTA包
filePath: "path" // 本地升级包路径
}]
}];
localUpdater.applyNewVersion(upgradeFiles).then(() => {
console.log(`applyNewVersion success`);
}).catch(err => {
......@@ -1270,16 +1270,16 @@ on(eventClassifyInfo: EventClassifyInfo, taskCallback: UpgradeTaskCallback): voi
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
**示例:**
```ts
var eventClassifyInfo = {
const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // 订阅升级更新事件
extraInfo: ""
}
};
function onTaskUpdate(eventInfo) {
console.log(`on eventInfo id `, eventInfo.eventId);
......@@ -1299,16 +1299,16 @@ off(eventClassifyInfo: EventClassifyInfo, taskCallback?: UpgradeTaskCallback): v
| 参数名 | 类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
| eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | 是 | 事件信息 |
| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | 是 | 事件回调 |
**示例:**
```ts
var eventClassifyInfo = {
const eventClassifyInfo = {
eventClassify: update.EventClassify.TASK, // 订阅升级更新事件
extraInfo: ""
}
};
function onTaskUpdate(eventInfo) {
console.log(`on eventInfo id `, eventInfo.eventId);
......@@ -1325,8 +1325,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------ |
| upgradeApp | string | 是 | 调用方包名 |
| businessType | [BusinessType](#businesstype) | 是 | 升级业务类型 |
| upgradeApp | string | 是 | 调用方包名 |
| businessType | [BusinessType](#businesstype) | 是 | 升级业务类型 |
## BusinessType
......@@ -1336,8 +1336,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------- | ----------------------------------- | ---- | ---- |
| vendor | [BusinessVendor](#businessvendor) | 是 | 供应商 |
| subType | [BusinessSubType](#businesssubtype) | 是 | 类型 |
| vendor | [BusinessVendor](#businessvendor) | 是 | 供应商 |
| subType | [BusinessSubType](#businesssubtype) | 是 | 类型 |
## CheckResult
......@@ -1347,8 +1347,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----------------- | --------------------------------- | ---- | ------ |
| isExistNewVersion | bool | 是 | 是否有新版本 |
| newVersionInfo | [NewVersionInfo](#newversioninfo) | 否 | 新版本数据 |
| isExistNewVersion | bool | 是 | 是否有新版本 |
| newVersionInfo | [NewVersionInfo](#newversioninfo) | 否 | 新版本数据 |
## NewVersionInfo
......@@ -1358,8 +1358,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 是 | 版本组件 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 是 | 版本组件 |
## VersionDigestInfo
......@@ -1369,7 +1369,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------- | ------ | ---- | ---- |
| versionDigest | string | 是 | 版本摘要 |
| versionDigest | string | 是 | 版本摘要 |
## VersionComponent
......@@ -1379,14 +1379,14 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| --------------- | ----------------------------------- | ---- | -------- |
| componentId | string | 是 | 组件标识 |
| componentType | [ComponentType](#componenttype) | 是 | 组件类型 |
| upgradeAction | [UpgradeAction](#upgradeaction) | 是 | 升级方式 |
| displayVersion | string | 是 | 显示版本号 |
| innerVersion | string | 是 | 版本号 |
| size | number | 是 | 升级包大小 |
| effectiveMode | [EffectiveMode](#effectivemode) | 是 | 生效模式 |
| descriptionInfo | [DescriptionInfo](#descriptioninfo) | 是 | 版本描述文件信息 |
| componentId | string | 是 | 组件标识 |
| componentType | [ComponentType](#componenttype) | 是 | 组件类型 |
| upgradeAction | [UpgradeAction](#upgradeaction) | 是 | 升级方式 |
| displayVersion | string | 是 | 显示版本号 |
| innerVersion | string | 是 | 版本号 |
| size | number | 是 | 升级包大小 |
| effectiveMode | [EffectiveMode](#effectivemode) | 是 | 生效模式 |
| descriptionInfo | [DescriptionInfo](#descriptioninfo) | 是 | 版本描述文件信息 |
## DescriptionOptions
......@@ -1396,8 +1396,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | --------------------------------------- | ---- | ------ |
| format | [DescriptionFormat](#descriptionformat) | 是 | 描述文件格式 |
| language | string | 是 | 描述文件语言 |
| format | [DescriptionFormat](#descriptionformat) | 是 | 描述文件格式 |
| language | string | 是 | 描述文件语言 |
## ComponentDescription
......@@ -1407,8 +1407,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| --------------- | ----------------------------------- | ---- | ------ |
| componentId | string | 是 | 组件标识 |
| descriptionInfo | [DescriptionInfo](#descriptioninfo) | 是 | 描述文件信息 |
| componentId | string | 是 | 组件标识 |
| descriptionInfo | [DescriptionInfo](#descriptioninfo) | 是 | 描述文件信息 |
## DescriptionInfo
......@@ -1418,8 +1418,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| --------------- | ----------------------------------- | ---- | ------ |
| descriptionType | [DescriptionType](#descriptiontype) | 是 | 描述文件类型 |
| content | string | 是 | 描述文件内容 |
| descriptionType | [DescriptionType](#descriptiontype) | 是 | 描述文件类型 |
| content | string | 是 | 描述文件内容 |
## CurrentVersionInfo
......@@ -1429,9 +1429,9 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ----- |
| osVersion | string | 是 | 系统版本号 |
| deviceName | string | 是 | 设备名 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 否 | 版本组件 |
| osVersion | string | 是 | 系统版本号 |
| deviceName | string | 是 | 设备名 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 否 | 版本组件 |
## DownloadOptions
......@@ -1441,8 +1441,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------ | ------------------- | ---- | ---- |
| allowNetwork | [NetType](#nettype) | 是 | 网络类型 |
| order | [Order](#order) | 是 | 升级指令 |
| allowNetwork | [NetType](#nettype) | 是 | 网络类型 |
| order | [Order](#order) | 是 | 升级指令 |
## ResumeDownloadOptions
......@@ -1452,7 +1452,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------ | ------------------- | ---- | ---- |
| allowNetwork | [NetType](#nettype) | 是 | 网络类型 |
| allowNetwork | [NetType](#nettype) | 是 | 网络类型 |
## PauseDownloadOptions
......@@ -1462,7 +1462,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----------------- | ---- | ---- | -------- |
| isAllowAutoResume | bool | 是 | 是否允许自动恢复 |
| isAllowAutoResume | bool | 是 | 是否允许自动恢复 |
## UpgradeOptions
......@@ -1472,7 +1472,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----- | --------------- | ---- | ---- |
| order | [Order](#order) | 是 | 升级指令 |
| order | [Order](#order) | 是 | 升级指令 |
## ClearOptions
......@@ -1482,7 +1482,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------ | ------------------------------- | ---- | ---- |
| status | [UpgradeStatus](#upgradestatus) | 是 | 异常状态 |
| status | [UpgradeStatus](#upgradestatus) | 是 | 异常状态 |
## UpgradePolicy
......@@ -1492,9 +1492,9 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------------- | --------------------------------------- | ---- | ------- |
| downloadStrategy | bool | 是 | 自动下载策略 |
| autoUpgradeStrategy | bool | 是 | 自动升级策略 |
| autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | 是 | 自动升级时间段 |
| downloadStrategy | bool | 是 | 自动下载策略 |
| autoUpgradeStrategy | bool | 是 | 自动升级策略 |
| autoUpgradePeriods | Array\<[UpgradePeriod](#upgradeperiod)> | 是 | 自动升级时间段 |
## UpgradePeriod
......@@ -1504,8 +1504,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----- | ------ | ---- | ---- |
| start | number | 是 | 开始时间 |
| end | number | 是 | 结束时间 |
| start | number | 是 | 开始时间 |
| end | number | 是 | 结束时间 |
## TaskInfo
......@@ -1515,8 +1515,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| --------- | --------------------- | ---- | ------ |
| existTask | bool | 是 | 是否存在任务 |
| taskBody | [TaskBody](#taskinfo) | 是 | 任务数据 |
| existTask | bool | 是 | 是否存在任务 |
| taskBody | [TaskBody](#taskinfo) | 是 | 任务数据 |
## EventInfo
......@@ -1526,8 +1526,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | --------------------- | ---- | ---- |
| eventId | [EventId](#eventid) | 是 | 事件ID |
| taskBody | [TaskBody](#taskinfo) | 是 | 任务数据 |
| eventId | [EventId](#eventid) | 是 | 事件ID |
| taskBody | [TaskBody](#taskinfo) | 是 | 任务数据 |
## TaskBody
......@@ -1537,13 +1537,13 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ----------------- | ---------------------------------------- | ---- | ---- |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要 |
| status | [UpgradeStatus](#upgradestatus) | 是 | 升级状态 |
| subStatus | number | 否 | 子状态 |
| progress | number | 是 | 进度 |
| installMode | number | 是 | 安装模式 |
| errorMessages | Array\<[ErrorMessage](#errormessage)> | 否 | 错误信息 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 是 | 版本组件 |
| versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | 是 | 版本摘要 |
| status | [UpgradeStatus](#upgradestatus) | 是 | 升级状态 |
| subStatus | number | 否 | 子状态 |
| progress | number | 是 | 进度 |
| installMode | number | 是 | 安装模式 |
| errorMessages | Array\<[ErrorMessage](#errormessage)> | 否 | 错误信息 |
| versionComponents | Array\<[VersionComponent](#versioncomponent)> | 是 | 版本组件 |
## ErrorMessage
......@@ -1553,8 +1553,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------ | ------ | ---- | ---- |
| errorCode | number | 是 | 错误码 |
| errorMessage | string | 是 | 错误描述 |
| errorCode | number | 是 | 错误码 |
| errorMessage | string | 是 | 错误描述 |
## EventClassifyInfo
......@@ -1564,8 +1564,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| ------------- | ------------------------------- | ---- | ---- |
| eventClassify | [EventClassify](#eventclassify) | 是 | 事件类型 |
| extraInfo | string | 是 | 额外信息 |
| eventClassify | [EventClassify](#eventclassify) | 是 | 事件类型 |
| extraInfo | string | 是 | 额外信息 |
## UpgradeFile
......@@ -1575,8 +1575,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| -------- | ------------------------------- | ---- | ---- |
| fileType | [ComponentType](#componenttype) | 是 | 文件类型 |
| filePath | string | 是 | 文件路径 |
| fileType | [ComponentType](#componenttype) | 是 | 文件类型 |
| filePath | string | 是 | 文件路径 |
## UpgradeTaskCallback
......@@ -1588,7 +1588,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 名称 | 参数类型 | 必填 | 说明 |
| --------- | ----------------------- | ---- | ---- |
| eventInfo | [EventInfo](#eventinfo) | 是 | 事件信息 |
| eventInfo | [EventInfo](#eventinfo) | 是 | 事件信息 |
## BusinessVendor
......@@ -1598,7 +1598,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ------ | -------- | ---- |
| PUBLIC | "public" | 开源 |
| PUBLIC | "public" | 开源 |
## BusinessSubType
......@@ -1608,7 +1608,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| -------- | ---- | ---- |
| FIRMWARE | 1 | 固件 |
| FIRMWARE | 1 | 固件 |
## ComponentType
......@@ -1618,7 +1618,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ---- | ---- | ---- |
| OTA | 1 | 固件 |
| OTA | 1 | 固件 |
## UpgradeAction
......@@ -1628,8 +1628,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| -------- | ---------- | ---- |
| UPGRADE | "upgrade" | 差分包 |
| RECOVERY | "recovery" | 修复包 |
| UPGRADE | "upgrade" | 差分包 |
| RECOVERY | "recovery" | 修复包 |
## EffectiveMode
......@@ -1639,9 +1639,9 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ------------- | ---- | ---- |
| COLD | 1 | 冷升级 |
| LIVE | 2 | 热升级 |
| LIVE_AND_COLD | 3 | 融合升级 |
| COLD | 1 | 冷升级 |
| LIVE | 2 | 热升级 |
| LIVE_AND_COLD | 3 | 融合升级 |
## DescriptionType
......@@ -1651,8 +1651,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ------- | ---- | ---- |
| CONTENT | 0 | 内容 |
| URI | 1 | 链接 |
| CONTENT | 0 | 内容 |
| URI | 1 | 链接 |
## DescriptionFormat
......@@ -1662,8 +1662,8 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ---------- | ---- | ---- |
| STANDARD | 0 | 标准格式 |
| SIMPLIFIED | 1 | 简易格式 |
| STANDARD | 0 | 标准格式 |
| SIMPLIFIED | 1 | 简易格式 |
## NetType
......@@ -1673,11 +1673,11 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ----------------- | ---- | --------- |
| CELLULAR | 1 | 数据网络 |
| METERED_WIFI | 2 | 热点WIFI |
| NOT_METERED_WIFI | 4 | 非热点WIFI |
| WIFI | 6 | WIFI |
| CELLULAR_AND_WIFI | 7 | 数据网络和WIFI |
| CELLULAR | 1 | 数据网络 |
| METERED_WIFI | 2 | 热点WIFI |
| NOT_METERED_WIFI | 4 | 非热点WIFI |
| WIFI | 6 | WIFI |
| CELLULAR_AND_WIFI | 7 | 数据网络和WIFI |
## Order
......@@ -1687,11 +1687,11 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| -------------------- | ---- | ----- |
| DOWNLOAD | 1 | 下载 |
| INSTALL | 2 | 安装 |
| DOWNLOAD_AND_INSTALL | 3 | 下载并安装 |
| APPLY | 4 | 生效 |
| INSTALL_AND_APPLY | 6 | 安装并生效 |
| DOWNLOAD | 1 | 下载 |
| INSTALL | 2 | 安装 |
| DOWNLOAD_AND_INSTALL | 3 | 下载并安装 |
| APPLY | 4 | 生效 |
| INSTALL_AND_APPLY | 6 | 安装并生效 |
## UpgradeStatus
......@@ -1701,16 +1701,16 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ---------------- | ---- | ---- |
| WAITING_DOWNLOAD | 20 | 待下载 |
| DOWNLOADING | 21 | 下载中 |
| DOWNLOAD_PAUSED | 22 | 下载暂停 |
| DOWNLOAD_FAIL | 23 | 下载失败 |
| WAITING_INSTALL | 30 | 待安装 |
| UPDATING | 31 | 更新中 |
| WAITING_APPLY | 40 | 待生效 |
| APPLYING | 21 | 生效中 |
| UPGRADE_SUCCESS | 50 | 升级成功 |
| UPGRADE_FAIL | 51 | 升级失败 |
| WAITING_DOWNLOAD | 20 | 待下载 |
| DOWNLOADING | 21 | 下载中 |
| DOWNLOAD_PAUSED | 22 | 下载暂停 |
| DOWNLOAD_FAIL | 23 | 下载失败 |
| WAITING_INSTALL | 30 | 待安装 |
| UPDATING | 31 | 更新中 |
| WAITING_APPLY | 40 | 待生效 |
| APPLYING | 21 | 生效中 |
| UPGRADE_SUCCESS | 50 | 升级成功 |
| UPGRADE_FAIL | 51 | 升级失败 |
## EventClassify
......@@ -1720,7 +1720,7 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ---- | ---------- | ---- |
| TASK | 0x01000000 | 任务事件 |
| TASK | 0x01000000 | 任务事件 |
## EventId
......@@ -1730,20 +1730,20 @@ localUpdater.off(eventClassifyInfo, onTaskUpdate);
| 参数名 | 默认值 | 说明 |
| ---------------------- | ---------- | ------ |
| EVENT_TASK_BASE | 0x01000000 | 任务事件 |
| EVENT_TASK_RECEIVE | 0x01000001 | 收到任务 |
| EVENT_TASK_CANCEL | 0x01000010 | 取消任务 |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | 待下载 |
| EVENT_DOWNLOAD_START | 0x01000100 | 开始下载 |
| EVENT_DOWNLOAD_UPDATE | 0x01000101 | 下载进度更新 |
| EVENT_DOWNLOAD_PAUSE | 0x01000110 | 下载暂停 |
| EVENT_DOWNLOAD_RESUME | 0x01000111 | 恢复下载 |
| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | 下载成功 |
| EVENT_DOWNLOAD_FAIL | 0x01001001 | 下载失败 |
| EVENT_UPGRADE_WAIT | 0x01001010 | 待升级 |
| EVENT_UPGRADE_START | 0x01001011 | 开始升级 |
| EVENT_UPGRADE_UPDATE | 0x01001100 | 升级中 |
| EVENT_APPLY_WAIT | 0x01001101 | 待生效 |
| EVENT_APPLY_START | 0x01001110 | 开始生效 |
| EVENT_UPGRADE_SUCCESS | 0x01001111 | 更新成功 |
| EVENT_UPGRADE_FAIL | 0x01010000 | 更新失败 |
| EVENT_TASK_BASE | 0x01000000 | 任务事件 |
| EVENT_TASK_RECEIVE | 0x01000001 | 收到任务 |
| EVENT_TASK_CANCEL | 0x01000010 | 取消任务 |
| EVENT_DOWNLOAD_WAIT | 0x01000011 | 待下载 |
| EVENT_DOWNLOAD_START | 0x01000100 | 开始下载 |
| EVENT_DOWNLOAD_UPDATE | 0x01000101 | 下载进度更新 |
| EVENT_DOWNLOAD_PAUSE | 0x01000110 | 下载暂停 |
| EVENT_DOWNLOAD_RESUME | 0x01000111 | 恢复下载 |
| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | 下载成功 |
| EVENT_DOWNLOAD_FAIL | 0x01001001 | 下载失败 |
| EVENT_UPGRADE_WAIT | 0x01001010 | 待升级 |
| EVENT_UPGRADE_START | 0x01001011 | 开始升级 |
| EVENT_UPGRADE_UPDATE | 0x01001100 | 升级中 |
| EVENT_APPLY_WAIT | 0x01001101 | 待生效 |
| EVENT_APPLY_START | 0x01001110 | 开始生效 |
| EVENT_UPGRADE_SUCCESS | 0x01001111 | 更新成功 |
| EVENT_UPGRADE_FAIL | 0x01010000 | 更新失败 |
......@@ -20,18 +20,18 @@ ImageAnimator()
## 属性
| 参数名称 | 参数类型 | 必填 | 参数描述 |
| ---------- | ----------------------- | -------- | -------- |
| images | Array&lt;ImageFrameInfo&gt; | 否 | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。<br/>默认值:[] |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) | 否 | 默认为初始状态,用于控制播放状态。<br/>默认值:AnimationStatus.Initial |
| duration | number | 否 | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中任意一帧图片设置了单独的duration后,该属性设置无效。<br/>默认值:1000 |
| reverse | boolean | 否 | 设置播放顺序。false表示从第1张图片播放到最后1张图片;&nbsp;true表示从最后1张图片播放到第1张图片。<br/>默认值:false |
| fixedSize | boolean | 否 | 设置图片大小是否固定为组件大小。&nbsp;true表示图片大小与组件大小一致,此时设置图片的width&nbsp;、height&nbsp;、top&nbsp;和left属性是无效的。false表示每一张图片的width&nbsp;、height&nbsp;、top和left属性都要单独设置。<br/>默认值:true |
| preDecode | number | 否 | 是否启用预解码,默认值为0,即不启用预解码,如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。<br/>默认值:0 |
| 参数名称 | 参数类型 |参数描述 |
| ---------- | ----------------------- |-------- |
| images | Array&lt;[ImageFrameInfo](imageframeinfo对象说明)&gt; | 设置图片帧信息集合。每一帧的帧信息(ImageFrameInfo)包含图片路径、图片大小、图片位置和图片播放时长信息,详见ImageFrameInfo属性说明。<br/>默认值:[] |
| state | [AnimationStatus](ts-appendix-enums.md#animationstatus) |默认为初始状态,用于控制播放状态。<br/>默认值:AnimationStatus.Initial |
| duration | number | 单位为毫秒,默认时长为1000ms;duration为0时,不播放图片;值的改变只会在下一次循环开始时生效;当images中任意一帧图片设置了单独的duration后,该属性设置无效。<br/>默认值:1000 |
| reverse | boolean | 设置播放顺序。false表示从第1张图片播放到最后1张图片;&nbsp;true表示从最后1张图片播放到第1张图片。<br/>默认值:false |
| fixedSize | boolean | 设置图片大小是否固定为组件大小。&nbsp;true表示图片大小与组件大小一致,此时设置图片的width&nbsp;、height&nbsp;、top&nbsp;和left属性是无效的。false表示每一张图片的width&nbsp;、height&nbsp;、top和left属性都要单独设置。<br/>默认值:true |
| preDecode | number | 是否启用预解码,默认值为0,即不启用预解码,如该值设为2,则播放当前页时会提前加载后面两张图片至缓存以提升性能。<br/>默认值:0 |
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | 否 | 设置动画开始前和结束后的状态,可选值参见FillMode说明。<br/>默认值:FillMode.Forwards |
| iterations | number | 否 | 默认播放一次,设置为-1时表示无限次播放。<br/>默认值:1 |
| iterations | number | 默认播放一次,设置为-1时表示无限次播放。<br/>默认值:1 |
- ImageFrameInfo属性说明
## ImageFrameInfo对象说明
| 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------------- | -------- | -------- |
......
# LongPressGesture
用于触发长按手势事件,触发长按手势的最少手指数为1,最短时间为500毫秒。
用于触发长按手势事件,触发长按手势的最少手指数为1,最短长按时间为500毫秒。
> **说明:**
>
......@@ -36,24 +36,31 @@ LongPressGesture(value?: { fingers?: number, repeat?: boolean, duration?: number
@Entry
@Component
struct LongPressGestureExample {
@State count: number = 0
@State count: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('LongPress onAction:' + this.count)
Column() {
Text('LongPress onAction:' + this.count).fontSize(28)
// 单指长按文本触发该手势事件
.gesture(
LongPressGesture({ repeat: true })
// 由于repeat设置为true,长按动作存在时会连续触发,触发间隔为duration(默认值500ms)
.onAction((event: GestureEvent) => {
if (event.repeat) {
this.count++;
}
})
// 长按动作一结束触发
.onActionEnd(() => {
this.count = 0;
})
)
}
.height(200).width(300).padding(60).border({ width:1 }).margin(30)
.gesture(
LongPressGesture({ repeat: true })
// 长按动作存在会连续触发
.onAction((event: GestureEvent) => {
if (event.repeat) { this.count++ }
})
// 长按动作一结束触发
.onActionEnd(() => {
this.count = 0
})
)
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
}
}
```
......
......@@ -17,7 +17,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb
| -------- | -------- | -------- | -------- |
| fingers | number | 否 | 触发拖动的最少手指数,最小为1指,&nbsp;最大取值为10指。<br/>默认值:1 |
| direction | PanDirection | 否 | 触发拖动的手势方向,此枚举值支持逻辑与(&amp;)和逻辑或(\|)运算。<br/>默认值:PanDirection.All |
| distance | number | 否 | 最小拖动识别距离,单位为vp。<br/>默认值:5.0<br/>**说明:**<br/>> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 |
| distance | number | 否 | 最小拖动识别距离,单位为vp。<br/>默认值:5<br/>**说明:**<br/>> tab滑动与该拖动手势事件同时存在时,可将distance值设为1,使拖动更灵敏,避免造成事件错乱。 |
## PanDirection枚举说明
......@@ -73,28 +73,47 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance
@Entry
@Component
struct PanGestureExample {
@State offsetX: number = 0
@State offsetY: number = 0
@State offsetX: number = 0;
@State offsetY: number = 0;
@State positionX: number = 0;
@State positionY: number = 0;
private panOption: PanGestureOptions = new PanGestureOptions({ direction: PanDirection.Left | PanDirection.Right });
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
}
.height(100).width(200).padding(20).border({ width: 1 }).margin(80)
.translate({ x: this.offsetX, y: this.offsetY, z: 5 })
.gesture(
PanGesture({})
Column() {
Column() {
Text('PanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(50)
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
// 左右拖动触发该手势事件
.gesture(
PanGesture(this.panOption)
.onActionStart((event: GestureEvent) => {
console.info('Pan start')
console.info('Pan start');
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX
this.offsetY = event.offsetY
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
})
.onActionEnd(() => {
console.info('Pan end')
this.positionX = this.offsetX;
this.positionY = this.offsetY;
console.info('Pan end');
})
)
Button('修改PanGesture触发条件')
.onClick(() => {
// 将PanGesture手势事件触发条件改为双指以任意方向拖动
this.panOption.setDirection(PanDirection.All);
this.panOption.setFingers(2);
})
)
}
}
}
```
......
......@@ -16,7 +16,7 @@ PinchGesture(value?: { fingers?: number, distance?: number })
| 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- |
| fingers | number | 否 | 触发捏合的最少手指数,&nbsp;最小为2指,最大为5指。<br/>默认值:2 |
| distance | number | 否 | 最小识别距离,单位为vp。<br/>默认值:3.0 |
| distance | number | 否 | 最小识别距离,单位为vp。<br/>默认值:3 |
## 事件
......@@ -36,26 +36,40 @@ PinchGesture(value?: { fingers?: number, distance?: number })
@Entry
@Component
struct PinchGestureExample {
@State scaleValue: number = 1
@State scaleValue: number = 1;
@State pinchValue: number = 1;
@State pinchX: number = 0;
@State pinchY: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('PinchGesture scale:' + this.scaleValue)
}
.height(100).width(200).padding(20).border({ width: 1 }).margin(80)
.scale({ x: this.scaleValue, y: this.scaleValue, z: this.scaleValue })
.gesture(
PinchGesture()
Column() {
Column() {
Text('PinchGesture scale:\n' + this.scaleValue)
Text('PinchGesture center:\n(' + this.pinchX + ',' + this.pinchY + ')')
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin({ top: 100 })
.scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
// 三指捏合触发该手势事件
.gesture(
PinchGesture({ fingers: 3 })
.onActionStart((event: GestureEvent) => {
console.info('Pinch start')
console.info('Pinch start');
})
.onActionUpdate((event: GestureEvent) => {
this.scaleValue = event.scale
this.scaleValue = this.pinchValue * event.scale;
this.pinchX = event.pinchCenterX;
this.pinchY = event.pinchCenterY;
})
.onActionEnd(() => {
console.info('Pinch end')
this.pinchValue = this.scaleValue;
console.info('Pinch end');
})
)
)
}.width('100%')
}
}
```
......
......@@ -16,7 +16,7 @@ RotationGesture(value?: { fingers?: number, angle?: number })
| 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- |
| fingers | number | 否 | 触发旋转的最少手指数,&nbsp;最小为2指,最大为5指。<br/>默认值:2 |
| angle | number | 否 | 触发旋转手势的最小改变度数,单位为deg。<br/>默认值:1.0 |
| angle | number | 否 | 触发旋转手势的最小改变度数,单位为deg。<br/>默认值:1 |
## 事件
......@@ -36,26 +36,35 @@ RotationGesture(value?: { fingers?: number, angle?: number })
@Entry
@Component
struct RotationGestureExample {
@State angle: number = 0
@State angle: number = 0;
@State rotateValue: number = 0;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('RotationGesture angle:' + this.angle)
}
.height(100).width(200).padding(20).border({ width:1 })
.margin(80).rotate({ x:1, y:2, z:3, angle: this.angle })
.gesture(
Column() {
Column() {
Text('RotationGesture angle:' + this.angle)
}
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(80)
.rotate({ angle: this.angle })
// 双指旋转触发该手势事件
.gesture(
RotationGesture()
.onActionStart((event: GestureEvent) => {
console.log('Rotation start')
console.info('Rotation start');
})
.onActionUpdate((event: GestureEvent) => {
this.angle = event.angle
this.angle = this.rotateValue + event.angle;
})
.onActionEnd(() => {
console.log('Rotation end')
this.rotateValue = this.angle;
console.info('Rotation end');
})
)
)
}.width('100%')
}
}
```
......
# SwipeGesture
用于触发滑动事件,滑动最小速度为100vp/s时识别成功。
用于触发滑动事件,滑动速度大于100vp/s时可识别成功。
> **说明:**
>
......@@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| 名称 | 描述 |
| -------- | -------- |
| All | 所有方向。 |
| Horizontal | 水平方向。 |
| Vertical | 竖直方向。 |
| Horizontal | 水平方向,手指滑动方向与x轴夹角小于45度时触发。 |
| Vertical | 竖直方向,手指滑动方向与y轴夹角小于45度时触发。 |
| None | 任何方向均不可触发。 |
......@@ -35,7 +35,6 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
| -------- | -------- |
| onAction(event:(event?:&nbsp;[GestureEvent](ts-gesture-settings.md#gestureevent对象说明))&nbsp;=&gt;&nbsp;void) | 滑动手势识别成功回调。 |
![zh-cn_image_0000001231374559](figures/zh-cn_image_0000001231374661.png)
## 示例
```ts
......@@ -43,25 +42,29 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num
@Entry
@Component
struct SwipeGestureExample {
@State rotateAngle : number = 0
@State speed : number = 1
@State rotateAngle: number = 0;
@State speed: number = 1;
build() {
Column() {
Text("SwipGesture speed : " + this.speed)
Text("SwipGesture angle : " + this.rotateAngle)
}
.position({x: 80, y: 200})
.border({width:2})
.width(260).height(260)
.rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle})
.gesture(
SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical})
Column() {
Text("SwipeGesture speed\n" + this.speed)
Text("SwipeGesture angle\n" + this.rotateAngle)
}
.border({ width: 3 })
.width(300)
.height(200)
.margin(100)
.rotate({ angle: this.rotateAngle })
// 单指竖直方向滑动时触发该事件
.gesture(
SwipeGesture({ direction: SwipeDirection.Vertical })
.onAction((event: GestureEvent) => {
this.speed = event.speed
this.rotateAngle = event.angle
})
)
this.speed = event.speed;
this.rotateAngle = event.angle;
})
)
}.width('100%')
}
}
```
......
# TapGesture
支持单次点击、多次点击识别。
支持单次多次点击识别。
> **说明:**
>
......@@ -15,8 +15,8 @@ TapGesture(value?: { count?: number, fingers?: number })
| 参数名称 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- |
| count | number | 否 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;如配置多击,上一次抬起和下一次按下的超时时间为300毫秒(ms)。 |
| fingers | number | 否 | 触发点击的最少手指数,最小为1指,&nbsp;最大为10指。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;1.&nbsp;当配置多指时,第一根手指按下后300毫秒(ms)内未有足够的手指数按下,手势识别失败。<br/>>&nbsp;2.&nbsp;实际点击手指数超过配置值,手势识别失败。 |
| count | number | 否 | 识别的连续点击次数。如果设置小于1,会被转化为默认值。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;如配置多击,上一次抬起和下一次按下的超时时间为300毫秒。 |
| fingers | number | 否 | 触发点击的手指数,最小为1指,&nbsp;最大为10指。<br/>默认值:1<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;1.&nbsp;当配置多指时,第一根手指按下后300毫秒内未有足够的手指数按下,手势识别失败。<br/>>&nbsp;2.&nbsp;实际点击手指数超过配置值,手势识别失败。 |
## 事件
......@@ -33,20 +33,25 @@ TapGesture(value?: { count?: number, fingers?: number })
@Entry
@Component
struct TapGestureExample {
@State value: string = ''
@State value: string = '';
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('Click twice')
Column() {
// 单指双击文本触发手势事件
Text('Click twice').fontSize(28)
.gesture(
TapGesture({ count: 2 })
.onAction((event: GestureEvent) => {
this.value = JSON.stringify(event.fingerList[0]);
})
)
Text(this.value)
}
.height(200).width(300).padding(60).border({ width: 1 }).margin(30)
.gesture(
TapGesture({ count: 2 })
.onAction(() => {
this.value = 'TapGesture onAction'
})
)
.height(200)
.width(300)
.padding(20)
.border({ width: 3 })
.margin(30)
}
}
```
......
# 组合手势
手势识别组多种手势组合为复合手势,支持连续识别、并行识别和互斥识别。
手势识别组合,即多种手势组合为复合手势,支持连续识别、并行识别和互斥识别。
> **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
......@@ -38,39 +39,55 @@ GestureGroup(mode: GestureMode, ...gesture: GestureType[])
@Entry
@Component
struct GestureGroupExample {
@State count: number = 0
@State offsetX: number = 0
@State offsetY: number = 0
@State borderStyles: BorderStyle = BorderStyle.Solid
@State count: number = 0;
@State offsetX: number = 0;
@State offsetY: number = 0;
@State positionX: number = 0;
@State positionY: number = 0;
@State borderStyles: BorderStyle = BorderStyle.Solid;
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Column() {
Text('sequence gesture\n' + 'LongPress onAction:' + this.count + '\nPanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
}.translate({ x: this.offsetX, y: this.offsetY, z: 5 })
.height(100).width(200).padding(10).margin(80).border({ width: 1, style: this.borderStyles })
}
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
.height(150)
.width(200)
.padding(20)
.margin(20)
.border({ width: 3, style: this.borderStyles })
.gesture(
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event.repeat) {this.count++}
console.log('LongPress onAction')
})
.onActionEnd(() => {
console.log('LongPress end')
}),
PanGesture({})
.onActionStart(() => {
this.borderStyles = BorderStyle.Dashed
console.log('pan start')
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX
this.offsetY = event.offsetY
console.log('pan update')
})
)
//以下组合手势为顺序识别,当长按手势事件未正常触发时则不会触发拖动手势事件
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event.repeat) {
this.count++;
}
console.info('LongPress onAction');
})
.onActionEnd(() => {
console.info('LongPress end');
}),
PanGesture()
.onActionStart(() => {
this.borderStyles = BorderStyle.Dashed;
console.info('pan start');
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = this.positionX + event.offsetX;
this.offsetY = this.positionY + event.offsetY;
console.info('pan update');
})
.onActionEnd(() => {
this.positionX = this.offsetX;
this.positionY = this.offsetY;
this.borderStyles = BorderStyle.Solid;
console.info('pan end');
})
)
.onCancel(() => {
console.log('sequence gesture canceled')
console.info('sequence gesture canceled');
})
)
}
......
# Line
> **说明:**
>
> 该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
......@@ -21,11 +22,12 @@
Line(value?: {width?: string | number, height?: string | number})
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
## 属性
......
......@@ -16,11 +16,12 @@
Polygon(value?: {width?: string | number, height?: string | number})
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
## 属性
......
......@@ -16,11 +16,12 @@
Polyline(value?: {width?: string | number, height?: string | number})
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string \| number | 否 | 0 | 宽度。 |
| height | string \| number | 否 | 0 | 高度。 |
## 属性
......
......@@ -17,14 +17,15 @@
Rect(value?: {width?: string | number,height?: string | number,radius?: string | number | Array&lt;string | number&gt;} |
{width?: string | number,height?: string | number,radiusWidth?: string | number,radiusHeight?: string | number})
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string&nbsp;\|&nbsp;number | 否 | 0 | 宽度。 |
| height | string&nbsp;\|&nbsp;number | 否 | 0 | 高度。 |
| radius | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Array&lt;string&nbsp;\|&nbsp;number&gt; | 否 | 0 | 圆角半径,支持分别设置四个角的圆角度数。 |
| radiusWidth | string&nbsp;\|&nbsp;number | 否 | 0 | 圆角宽度。 |
| radiusHeight | string&nbsp;\|&nbsp;number | 否 | 0 | 圆角高度。 |
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| width | string&nbsp;\|&nbsp;number | 否 | 0 | 宽度。 |
| height | string&nbsp;\|&nbsp;number | 否 | 0 | 高度。 |
| radius | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;Array&lt;string&nbsp;\|&nbsp;number&gt; | 否 | 0 | 圆角半径,支持分别设置四个角的圆角度数。 |
| radiusWidth | string&nbsp;\|&nbsp;number | 否 | 0 | 圆角宽度。 |
| radiusHeight | string&nbsp;\|&nbsp;number | 否 | 0 | 圆角高度。 |
## 属性
......
......@@ -21,10 +21,11 @@
Shape(value?: PixelMap)
- 参数
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 |
**参数:**
| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 |
| -------- | -------- | -------- | -------- | -------- |
| value | PixelMap | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 |
## 属性
......
......@@ -3,15 +3,14 @@
为组件绑定不同类型的手势事件,并设置事件的响应方法。
> **说明:**
>
> 从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
## 绑定手势识别
通过如下属性给组件绑定手势识别,手势识别成功后可以通过事件回调通知组件。
| 名称 | 参数类型 | 默认值 | 描述 |
| -------- | -------- | -------- | -------- |
| gesture | gesture:&nbsp;[GestureType](#gesturetype),<br/>mask?:&nbsp;[GestureMask](#gesturemask枚举说明) | gesture:&nbsp;-,<br/>mask:&nbsp;GestureMask.Normal | 绑定手势。<br/>- gesture:&nbsp;绑定的手势类型,&nbsp;<br>- mask:&nbsp;事件响应设置。 |
......@@ -37,10 +36,9 @@
| Normal | 不屏蔽子组件的手势,按照默认手势识别顺序进行识别。 |
| IgnoreInternal | 屏蔽子组件的手势,仅当前容器的手势进行识别。<br/>子组件上系统内置的手势不会被屏蔽,如子组件为List组件时,内置的滑动手势仍然会触发。 |
## 响应手势事件
组件通过手势事件绑定不同GestureType的手势对象,各手势对象提供的事件响应手势操作,提供手势相关信息。下面通过TapGesture对象的onAction事件响应点击事件,获取事件相关信息。其余手势对象的事件定义见各个手势对象章节。
组件通过手势事件绑定不同GestureType的手势对象,各手势对象在响应手势操作的事件回调中提供手势相关信息。下面通过TapGesture手势对象的onAction事件响应点击事件,获取事件相关信息。其余手势对象的事件定义见各个手势对象章节。
- TapGesture事件说明
| 名称 | 功能描述 |
......@@ -50,18 +48,18 @@
## GestureEvent对象说明
| 名称 | 类型 | 描述 |
| -------- | -------- | -------- |
| timestamp<sup>8+</sup> | number | 事件时间戳。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 触发手势事件的元素对象显示区域。 |
| source<sup>8+</sup> | [SourceType](#sourcetype枚举说明) | 事件输入设备。 |
| repeat | boolean | 是否为重复触发事件,用于LongPressGesture手势触发场景。 |
| fingerList<sup>8+</sup> | [FingerInfo](#fingerinfo对象说明)[] | 触发事件的所有手指信息,用于LongPressGesture与TapGesture手势触发场景。 |
| offsetX | number | 手势事件x轴相对偏移量,单位为vp,用于PanGesture手势触发场景,从左向右滑动offsetX为正,反之为负。 |
| offsetY | number | 手势事件y轴相对偏移量,单位为vp,用于PanGesture手势触发场景,从上向下滑动offsetY为正,反之为负。 |
| angle | number | 用于RotationGesture手势触发场景时,表示旋转角度;用于SwipeGesture手势触发场景时,表示滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 |
| speed<sup>8+</sup> | number | 滑动手势速度,即所有手指滑动的平均速度,单位为vp/秒,用于SwipeGesture手势触发场景。 |
| angle | number | 用于RotationGesture手势触发场景时,表示旋转角度。<br/>用于SwipeGesture手势触发场景时,表示滑动手势的角度,即两根手指间的线段与水平方向的夹角变化的度数。<br/>>&nbsp;&nbsp;**说明:**<br/>>&nbsp;角度计算方式:滑动手势被识别到后,连接两根手指之间的线被识别为起始线条,随着手指的滑动,手指之间的线条会发生旋转,根据起始线条两端点和当前线条两端点的坐标,使用反正切函数分别计算其相对于水平方向的夹角,最后arctan2(cy2-cy1,cx2-cx1)-arctan2(y2-y1,x2-x1)为旋转的角度。以起始线条为坐标系,顺时针旋转为0到180度,逆时针旋转为-180到0度。 |
| scale | number | 缩放比例,用于PinchGesture手势触发场景。 |
| pinchCenterX | number | 捏合手势中心点相对于当前组件元素左上角x轴坐标,单位为vp,用于PinchGesture手势触发场景。 |
| pinchCenterY | number | 捏合手势中心点相对于当前组件元素左上角y轴坐标,单位为vp,用于PinchGesture手势触发场景。 |
| speed<sup>8+</sup> | number | 滑动手势速度,即所有手指滑动的平均速度,单位为vp/秒,用于SwipeGesture手势触发场景。 |
| fingerList<sup>8+</sup> | [FingerInfo](#fingerinfo对象说明)[] | 触发事件的所有手指信息,用于LongPressGesture与TapGesture手势触发场景。 |
| timestamp<sup>8+</sup> | number | 事件时间戳。 |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8对象说明) | 触发手势事件的元素对象显示区域。 |
| source<sup>8+</sup> | [SourceType](#sourcetype枚举说明) | 事件输入设备。 |
## SourceType枚举说明
| 名称 | 描述 |
......@@ -87,30 +85,54 @@
@Entry
@Component
struct GestureSettingsExample {
@State value: string = ''
@State priorityTestValue: string = '';
@State parallelTestValue: string = '';
build() {
Column(){
Column() {
Column() {
Text('Click\n' + this.value)
Text('TapGesture:' + this.priorityTestValue).fontSize(28)
.gesture(
TapGesture()
.onAction(() => {
this.value = 'gesture onAction'
this.priorityTestValue += '\nText';
}))
}.height(200).width(300).padding(60).border({ width: 1 })
//设置为priorityGesture时,会优先识别该绑定手势忽略内部gesture手势
}
.height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// 设置为priorityGesture时,点击文本会忽略Text组件的TapGesture手势事件,优先识别父组件Column的TapGesture手势事件
.priorityGesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.value = 'priorityGesture onAction' + '\ncomponent globalPos:('
+ event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\nwidth:'
+ event.target.area.width + '\nheight:' + event.target.area.height
}), GestureMask.IgnoreInternal
)
}.padding(60)
this.priorityTestValue += '\nColumn';
}), GestureMask.IgnoreInternal)
Column() {
Text('TapGesture:' + this.parallelTestValue).fontSize(28)
.gesture(
TapGesture()
.onAction(() => {
this.parallelTestValue += '\nText';
}))
}
.height(200)
.width(250)
.padding(20)
.margin(20)
.border({ width: 3 })
// 设置为parallelGesture时,点击文本会同时触发子组件Text与父组件Column的TapGesture手势事件
.parallelGesture(
TapGesture()
.onAction((event: GestureEvent) => {
this.parallelTestValue += '\nColumn';
}), GestureMask.Normal)
}
}
}
```
![zh-cn_image_0000001210195016](figures/zh-cn_image_0000001210195016.gif)
......@@ -21,7 +21,7 @@
| autoCancel | boolean | 否 | 点击遮障层时,是否关闭弹窗。<br>默认值:true |
| confirm | {<br/>value:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>fontColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>backgroundColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void<br/>} | 否 | 确认按钮的文本内容、文本色、按钮背景色和点击回调。 |
| cancel | ()&nbsp;=&gt;&nbsp;void | 否 | 点击遮障层关闭dialog时的回调。 |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 |
| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 |
......@@ -34,10 +34,25 @@
| primaryButton | {<br/>value:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>fontColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>backgroundColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void;<br/>} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 |
| secondaryButton | {<br/>value:&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>fontColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>backgroundColor?:&nbsp;Color&nbsp;\|&nbsp;number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>action:&nbsp;()&nbsp;=&gt;&nbsp;void;<br/>} | 否 | 按钮的文本内容、文本色、按钮背景色和点击回调。 |
| cancel | ()&nbsp;=&gt;&nbsp;void | 否 | 点击遮障层关闭dialog时的回调。 |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 |
| gridCount | number | 否 | 弹窗容器宽度所占用栅格数。 |
## DialogAlignment枚举说明
| 名称 | 描述 |
| ------------------------ | ------- |
| Top | 垂直顶部对齐。 |
| Center | 垂直居中对齐。 |
| Bottom | 垂直底部对齐。 |
| Default | 默认对齐。 |
| TopStart<sup>8+</sup> | 左上对齐。 |
| TopEnd<sup>8+</sup> | 右上对齐。 |
| CenterStart<sup>8+</sup> | 左中对齐。 |
| CenterEnd<sup>8+</sup> | 右中对齐。 |
| BottomStart<sup>8+</sup> | 左下对齐。 |
| BottomEnd<sup>8+</sup> | 右下对齐。 |
## 示例
```ts
......
......@@ -21,27 +21,11 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, aut
| builder | [CustomDialog](../../ui/ts-component-based-customdialog.md) | 是 | 自定义弹窗内容构造器。 |
| cancel | ()&nbsp;=&gt;&nbsp;void | 否 | 点击遮障层退出时的回调。 |
| autoCancel | boolean | 否 | 是否允许点击遮障层退出。<br>默认值:true |
| alignment | [DialogAlignment](#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| offset | {<br/>dx:&nbsp;Length&nbsp;\|&nbsp;[Resource](ts-types.md#resource),<br/>dy:&nbsp;Length&nbsp;&nbsp;\|&nbsp;[Resource](ts-types.md#resource)<br/>} | 否 | 弹窗相对alignment所在位置的偏移量。 |
| customStyle | boolean | 否 | 弹窗容器样式是否自定义。<br>默认值:false |
| gridCount<sup>8+</sup> | number | 否 | 弹窗宽度占栅格宽度的个数。 |
## DialogAlignment枚举说明
| 名称 | 描述 |
| ------------------------ | ------- |
| Top | 垂直顶部对齐。 |
| Center | 垂直居中对齐。 |
| Bottom | 垂直底部对齐。 |
| Default | 默认对齐。 |
| TopStart<sup>8+</sup> | 左上对齐。 |
| TopEnd<sup>8+</sup> | 右上对齐。 |
| CenterStart<sup>8+</sup> | 左中对齐。 |
| CenterEnd<sup>8+</sup> | 右中对齐。 |
| BottomStart<sup>8+</sup> | 左下对齐。 |
| BottomEnd<sup>8+</sup> | 右下对齐。 |
## CustomDialogController
### 导入对象
......
......@@ -13,8 +13,8 @@
| 名称 | 参数类型 | 描述 |
| -------------- | -------------------------------------------- | ----------------------------------- |
| linearGradient | {<br/>angle?:&nbsp;number \| string,<br/>direction?:&nbsp;[GradientDirection](ts-appendix-enums.md#gradientdirection),<br/>colors:&nbsp;Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br/>repeating?:&nbsp;boolean<br/>} | 线性渐变。<br/>- angle:&nbsp;线性渐变的角度。<br/>- direction:&nbsp;线性渐变的方向,设置angle后不生效。<br/>- colors:&nbsp;为渐变的颜色描述。<br/>- repeating:&nbsp;为渐变的颜色重复着色。 |
| sweepGradient | {<br/>center:&nbsp;Point,<br/>start?:&nbsp;number \| string,<br/>end?:&nbsp;number \| string,<br/>rotation?:&nbsp;number\|string,<br/>colors:&nbsp;Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br/>repeating?:&nbsp;boolean<br/>} | 角度渐变。<br/>- center:为角度渐变的中心点。<br/>- start:角度渐变的起点。<br/>- end:角度渐变的终点。<br/>- ;rotation:&nbsp;角度渐变的旋转角度。<br/>- colors:&nbsp;为渐变的颜色描述。<br/>- repeating:&nbsp;为渐变的颜色重复着色。 |
| radialGradient | {<br/>center:&nbsp;Point,<br/>-radius:&nbsp;number \| string,<br/>colors:&nbsp;Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br/>repeating?:&nbsp;boolean<br/>} | 径向渐变。<br/>- center:径向渐变的中心点。<br/>- radius:径向渐变的半径。<br/>- colors:&nbsp;为渐变的颜色描述。<br/>- repeating:&nbsp;为渐变的颜色重复着色。 |
| sweepGradient | {<br/>center:&nbsp;Point,<br/>start?:&nbsp;number \| string,<br/>end?:&nbsp;number \| string,<br/>rotation?:&nbsp;number\|string,<br/>colors:&nbsp;Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br/>repeating?:&nbsp;boolean<br/>} | 角度渐变。<br/>- center:为角度渐变的中心点。<br/>- start:角度渐变的起点。<br/>- end:角度渐变的终点。<br/>- rotation:&nbsp;角度渐变的旋转角度。<br/>- colors:&nbsp;为渐变的颜色描述。<br/>- repeating:&nbsp;为渐变的颜色重复着色。 |
| radialGradient | {<br/>center:&nbsp;Point,<br/>radius:&nbsp;number \| string,<br/>colors:&nbsp;Array&lt;[ColorStop](ts-basic-components-gauge.md#colorstop)&gt;,<br/>repeating?:&nbsp;boolean<br/>} | 径向渐变。<br/>- center:径向渐变的中心点。<br/>- radius:径向渐变的半径。<br/>- colors:&nbsp;为渐变的颜色描述。<br/>- repeating:&nbsp;为渐变的颜色重复着色。 |
## 示例
......
......@@ -39,5 +39,9 @@
- [OH_NativeXComponent_MouseEvent_Callback](_o_h___native_x_component___mouse_event___callback.md)
- [OH_NativeXComponent_TouchEvent](_o_h___native_x_component___touch_event.md)
- [OH_NativeXComponent_TouchPoint](_o_h___native_x_component___touch_point.md)
- [OHExtDataHandle](_o_h_ext_data_handle.md)
- [OHHDRMetaData](_o_h_h_d_r_meta_data.md)
- [OhosPixelMapInfo](_ohos_pixel_map_info.md)
- [RawFileDescriptor](_raw_file_descriptor.md)
- [Region](_region.md)
- [Rect](_rect.md)
......@@ -110,7 +110,7 @@ DEBUG级别写日志,宏封装接口。
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| fmt | 格式化字符串,基于类printf格式的增强,支持隐私参数标识,即在格式字符串每个参数中符号后类型前增加{public}、{private}标识。 |
......@@ -140,7 +140,7 @@ ERROR级别写日志,宏封装接口。
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| fmt | 格式化字符串,基于类printf格式的增强,支持隐私参数标识,即在格式字符串每个参数中符号后类型前增加{public}、{private}标识。 |
......@@ -170,7 +170,7 @@ FATAL级别写日志,宏封装接口。
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| fmt | 格式化字符串,基于类printf格式的增强,支持隐私参数标识,即在格式字符串每个参数中符号后类型前增加{public}、{private}标识。 |
......@@ -200,7 +200,7 @@ INFO级别写日志,宏封装接口。
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| fmt | 格式化字符串,基于类printf格式的增强,支持隐私参数标识,即在格式字符串每个参数中符号后类型前增加{public}、{private}标识。 |
......@@ -230,7 +230,7 @@ WARN级别写日志,宏封装接口。
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| fmt | 格式化字符串,基于类printf格式的增强,支持隐私参数标识,即在格式字符串每个参数中符号后类型前增加{public}、{private}标识。 |
......@@ -324,7 +324,7 @@ bool OH_LOG_IsLoggable (unsigned int domain, const char * tag, LogLevel level )
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| domain | 指定日志业务领域。 |
| tag | 指定日志TAG。 |
......@@ -354,7 +354,7 @@ int OH_LOG_Print (LogType type, LogLevel level, unsigned int domain, const char
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| type | 日志类型,三方应用日志类型为LOG_APP。 |
| level | 日志级别,日志级别包括LOG_DEBUG、LOG_INFO、LOG_WARN、LOG_ERROR、LOG_FATAL。 |
......
# NativeWindow
提供NativeWindow功能,主要用来和egl对接
提供NativeWindow功能,主要用来和egl对接
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**自从:**
......@@ -18,85 +18,199 @@
### 文件
| 文件名称 | 描述 |
| 文件名称 | 描述 |
| -------- | -------- |
| [external_window.h](external__window_8h.md) | 定义获取和使用NativeWindow的相关函数 |
| [external_window.h](external__window_8h.md) | 定义获取和使用NativeWindow的相关函数 |
### 结构体
| 结构体名称 | 描述 |
| -------- | -------- |
| [Region](_region.md) | 表示本地窗口NativeWindow需要更新内容的矩形区域(脏区) |
| [OHHDRMetaData](_o_h_h_d_r_meta_data.md) | HDR元数据结构体定义 |
| [OHExtDataHandle](_o_h_ext_data_handle.md) | 扩展数据句柄结构体定义 |
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| OHNativeWindow | 提供对NativeWindow的访问功能 |
| OHNativeWindowBuffer | 提供对NativeWindow的访问功能 |
| Region | 表示本地窗口NativeWindow需要更新内容的矩形区域(脏区) |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [NativeWindowOperation](#nativewindowoperation) { SET_BUFFER_GEOMETRY, GET_BUFFER_GEOMETRY, GET_FORMAT, SET_FORMAT, GET_USAGE, SET_USAGE, SET_STRIDE, GET_STRIDE, SET_SWAP_INTERVAL, GET_SWAP_INTERVAL, SET_TIMEOUT, GET_TIMEOUT, SET_COLOR_GAMUT, GET_COLOR_GAMUT, SET_TRANSFORM, GET_TRANSFORM, SET_UI_TIMESTAMP } | OH_NativeWindow_NativeWindowHandleOpt函数中的操作码 |
| [OHScalingMode](#ohscalingmode) { OH_SCALING_MODE_FREEZE = 0, OH_SCALING_MODE_SCALE_TO_WINDOW, OH_SCALING_MODE_SCALE_CROP, OH_SCALING_MODE_NO_SCALE_CROP } | 缩放模式 Scaling Mode |
| [OHHDRMetadataKey](#ohhdrmetadatakey) { OH_METAKEY_RED_PRIMARY_X = 0, OH_METAKEY_RED_PRIMARY_Y = 1, OH_METAKEY_GREEN_PRIMARY_X = 2, OH_METAKEY_GREEN_PRIMARY_Y = 3, OH_METAKEY_BLUE_PRIMARY_X = 4, OH_METAKEY_BLUE_PRIMARY_Y = 5, OH_METAKEY_WHITE_PRIMARY_X = 6, OH_METAKEY_WHITE_PRIMARY_Y = 7, OH_METAKEY_MAX_LUMINANCE = 8, OH_METAKEY_MIN_LUMINANCE = 9, OH_METAKEY_MAX_CONTENT_LIGHT_LEVEL = 10, OH_METAKEY_MAX_FRAME_AVERAGE_LIGHT_LEVEL = 11, OH_METAKEY_HDR10_PLUS = 12, OH_METAKEY_HDR_VIVID = 13 } | 枚举HDR元数据关键字 |
### 函数
| 函数名称 | 描述 |
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_NativeWindow_CreateNativeWindowFromSurface](#oh_nativewindow_createnativewindowfromsurface) (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例 |
| [OH_NativeWindow_DestroyNativeWindow](#oh_nativewindow_destroynativewindow) (struct NativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉 |
| [OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer](#oh_nativewindow_createnativewindowbufferfromsurfacebuffer) (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例 |
| [OH_NativeWindow_DestroyNativeWindowBuffer](#oh_nativewindow_destroynativewindowbuffer) (struct NativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉 |
| [OH_NativeWindow_NativeWindowRequestBuffer](#oh_nativewindow_nativewindowrequestbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产 |
| [OH_NativeWindow_NativeWindowFlushBuffer](#oh_nativewindow_nativewindowflushbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费 |
| [OH_NativeWindow_NativeWindowCancelBuffer](#oh_nativewindow_nativewindowcancelbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请 |
| [OH_NativeWindow_NativeWindowHandleOpt](#oh_nativewindow_nativewindowhandleopt) (struct NativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等 |
| [OH_NativeWindow_GetBufferHandleFromNative](#oh_nativewindow_getbufferhandlefromnative) (struct NativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针 |
| [OH_NativeWindow_NativeObjectReference](#oh_nativewindow_nativeobjectreference) (void \*obj) | 增加一个NativeObject的引用计数 |
| [OH_NativeWindow_NativeObjectUnreference](#oh_nativewindow_nativeobjectunreference) (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉 |
| [OH_NativeWindow_GetNativeObjectMagic](#oh_nativewindow_getnativeobjectmagic) (void \*obj) | 获取NativeObject的MagicId |
| [OH_NativeWindow_CreateNativeWindow](#oh_nativewindow_createnativewindow) (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例 |
| [OH_NativeWindow_DestroyNativeWindow](#oh_nativewindow_destroynativewindow) (OHNativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉 |
| [OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer](#oh_nativewindow_createnativewindowbufferfromsurfacebuffer) (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例 |
| [OH_NativeWindow_DestroyNativeWindowBuffer](#oh_nativewindow_destroynativewindowbuffer) (OHNativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉 |
| [OH_NativeWindow_NativeWindowRequestBuffer](#oh_nativewindow_nativewindowrequestbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产 |
| [OH_NativeWindow_NativeWindowFlushBuffer](#oh_nativewindow_nativewindowflushbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, [Region](_region.md) region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费 |
| [OH_NativeWindow_NativeWindowAbortBuffer](#oh_nativewindow_nativewindowabortbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请 |
| [OH_NativeWindow_NativeWindowHandleOpt](#oh_nativewindow_nativewindowhandleopt) (OHNativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等 |
| [OH_NativeWindow_GetBufferHandleFromNative](#oh_nativewindow_getbufferhandlefromnative) (OHNativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针 |
| [OH_NativeWindow_NativeObjectReference](#oh_nativewindow_nativeobjectreference) (void \*obj) | 增加一个NativeObject的引用计数 |
| [OH_NativeWindow_NativeObjectUnreference](#oh_nativewindow_nativeobjectunreference) (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉 |
| [OH_NativeWindow_GetNativeObjectMagic](#oh_nativewindow_getnativeobjectmagic) (void \*obj) | 获取NativeObject的MagicId |
| [OH_NativeWindow_NativeWindowSetScalingMode](#oh_nativewindow_nativewindowsetscalingmode) (OHNativeWindow \*window, uint32_t sequence, [OHScalingMode](#ohscalingmode) scalingMode) | 设置NativeWindow的ScalingMode |
| [OH_NativeWindow_NativeWindowSetMetaData](#oh_nativewindow_nativewindowsetmetadata) (OHNativeWindow \*window, uint32_t sequence, int32_t size, const [OHHDRMetaData](_o_h_h_d_r_meta_data.md) \*metaData) | 设置NativeWindow的元数据 |
| [OH_NativeWindow_NativeWindowSetMetaDataSet](#oh_nativewindow_nativewindowsetmetadataset) (OHNativeWindow \*window, uint32_t sequence, [OHHDRMetadataKey](#ohhdrmetadatakey) key, int32_t size, const uint8_t \*metaData) | 设置NativeWindow的元数据集。 |
| [OH_NativeWindow_NativeWindowSetTunnelHandle](#oh_nativewindow_nativewindowsettunnelhandle) (OHNativeWindow \*window, const [OHExtDataHandle](_o_h_ext_data_handle.md) \*handle) | 设置NativeWindow的TunnelHandle。 |
## 详细描述
## 函数说明
## 枚举类型说明
### OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer()
### NativeWindowOperation
```
enum NativeWindowOperation
```
**描述:**
OH_NativeWindow_NativeWindowHandleOpt函数中的操作码
| 枚举值 | 说明 |
| -------- | -------- |
| SET_BUFFER_GEOMETRY | 设置本地窗口缓冲区几何图形, 函数中的可变参数是 [输入] int32_t height,[输入] int32_t width。 |
| GET_BUFFER_GEOMETRY | 获取本地窗口缓冲区几何图形, 函数中的可变参数是 [输出] int32_t \*height, [输出] int32_t \*width。 |
| GET_FORMAT | 获取本地窗口缓冲区格式, 函数中的可变参数是 [输出] int32_t \*format。 |
| SET_FORMAT | 设置本地窗口缓冲区格式, 函数中的可变参数是 [输入] int32_t format。 |
| GET_USAGE | 获取本地窗口缓冲区格式, 函数中的可变参数是 [输出] int32_t \*usage。 |
| SET_USAGE | 设置本地窗口缓冲区使用方式, 函数中的可变参数是 [输入] int32_t usage。 |
| SET_STRIDE | 设置本地窗口缓冲区步幅, 函数中的可变参数是 [输入] int32_t stride。 |
| GET_STRIDE | 获取本地窗口缓冲区步幅, 函数中的可变参数是 [输出] int32_t \*stride。 |
| SET_SWAP_INTERVAL | 设置本地窗口缓冲区交换间隔, 函数中的可变参数是 [输入] int32_t interval。 |
| GET_SWAP_INTERVAL | 获取本地窗口缓冲区交换间隔, 函数中的可变参数是 [输出] int32_t \*interval。 |
| SET_TIMEOUT | 设置请求本地窗口缓冲区的超时等待时间, 函数中的可变参数是 [输入] int32_t timeout。 |
| GET_TIMEOUT | 获取请求本地窗口缓冲区的超时等待时间, 函数中的可变参数是 [输出] int32_t \*timeout。 |
| SET_COLOR_GAMUT | 设置本地窗口缓冲区色彩空间, 函数中的可变参数是 [输入] int32_t colorGamut。 |
| GET_COLOR_GAMUT | 获取本地窗口缓冲区色彩空间, 函数中的可变参数是 [out int32_t \*colorGamut]。 |
| SET_TRANSFORM | 设置本地窗口缓冲区变换, 函数中的可变参数是 [输入] int32_t transform。 |
| GET_TRANSFORM | 获取本地窗口缓冲区变换, 函数中的可变参数是 [输出] int32_t \*transform。 |
| SET_UI_TIMESTAMP | 设置本地窗口缓冲区UI时间戳, 函数中的可变参数是 [输入] uint64_t uiTimestamp。 |
### OHHDRMetadataKey
```
struct NativeWindowBuffer* OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void * pSurfaceBuffer)
enum OHHDRMetadataKey
```
**描述:**
创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例
枚举HDR元数据关键字
| 枚举值 | 描述 |
| -------- | -------- |
| OH_METAKEY_RED_PRIMARY_X | 红基色X坐标 |
| OH_METAKEY_RED_PRIMARY_Y | 红基色Y坐标 |
| OH_METAKEY_GREEN_PRIMARY_X | 绿基色X坐标 |
| OH_METAKEY_GREEN_PRIMARY_Y | 绿基色Y坐标 |
| OH_METAKEY_BLUE_PRIMARY_X | 蓝基色X坐标 |
| OH_METAKEY_BLUE_PRIMARY_Y | 蓝基色Y坐标 |
| OH_METAKEY_WHITE_PRIMARY_X | 白点X坐标 |
| OH_METAKEY_WHITE_PRIMARY_Y | 白点Y坐标 |
| OH_METAKEY_MAX_LUMINANCE | 最大的光亮度 |
| OH_METAKEY_MIN_LUMINANCE | 最小的光亮度 |
| OH_METAKEY_MAX_CONTENT_LIGHT_LEVEL | 最大的内容亮度水平 |
| OH_METAKEY_MAX_FRAME_AVERAGE_LIGHT_LEVEL | 最大的帧平均亮度水平 |
| OH_METAKEY_HDR10_PLUS | HDR10 Plus |
| OH_METAKEY_HDR_VIVID | Vivid |
### OHScalingMode
```
enum OHScalingMode
```
**描述:**
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
缩放模式 Scaling Mode
| 枚举值 | 描述 |
| -------- | -------- |
| OH_SCALING_MODE_FREEZE | 在接收到窗口大小的缓冲区之前,不可以更新窗口内容 |
| OH_SCALING_MODE_SCALE_TO_WINDOW | 缓冲区在二维中缩放以匹配窗口大小 |
| OH_SCALING_MODE_SCALE_CROP | 缓冲区被统一缩放,使得缓冲区的较小尺寸与窗口大小匹配 |
| OH_SCALING_MODE_NO_SCALE_CROP | 窗口被裁剪为缓冲区裁剪矩形的大小,裁剪矩形之外的像素被视为完全透明 |
## 函数说明
### OH_NativeWindow_CreateNativeWindow()
```
OHNativeWindow* OH_NativeWindow_CreateNativeWindow (void * pSurface)
```
**描述:**
创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| pSurfaceBuffer | 参数是一个指向生产者buffer的指针,类型为sptr&lt;OHOS::SurfaceBuffer&gt; |
| pSurface | 参数是一个指向生产者ProduceSurface的指针,类型为sptr&lt;OHOS::Surface&gt; |
**返回:**
返回一个指针,指向NativeWindowBuffer的结构体实例
返回一个指针,指向NativeWindow的结构体实例
**自从:**
8
### OH_NativeWindow_CreateNativeWindowFromSurface()
### OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer()
```
struct NativeWindow* OH_NativeWindow_CreateNativeWindowFromSurface (void * pSurface)
OHNativeWindowBuffer* OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer (void * pSurfaceBuffer)
```
**描述:**
创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例
创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| pSurface | 参数是一个指向生产者ProduceSurface的指针,类型为sptr&lt;OHOS::Surface&gt; |
| pSurfaceBuffer | 参数是一个指向生产者buffer的指针,类型为sptr&lt;OHOS::SurfaceBuffer&gt; |
**返回:**
返回一个指针,指向NativeWindow的结构体实例
返回一个指针,指向NativeWindowBuffer的结构体实例
**自从:**
......@@ -105,22 +219,22 @@ struct NativeWindow* OH_NativeWindow_CreateNativeWindowFromSurface (void * pSurf
### OH_NativeWindow_DestroyNativeWindow()
```
void OH_NativeWindow_DestroyNativeWindow (struct NativeWindow * window)
void OH_NativeWindow_DestroyNativeWindow (OHNativeWindow * window)
```
**描述:**
将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| window | 参数是一个NativeWindow的结构体实例的指针 |
**自从:**
......@@ -129,22 +243,22 @@ void OH_NativeWindow_DestroyNativeWindow (struct NativeWindow * window)
### OH_NativeWindow_DestroyNativeWindowBuffer()
```
void OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer * buffer)
void OH_NativeWindow_DestroyNativeWindowBuffer (OHNativeWindowBuffer * buffer)
```
**描述:**
将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
**自从:**
......@@ -153,22 +267,22 @@ void OH_NativeWindow_DestroyNativeWindowBuffer (struct NativeWindowBuffer * buff
### OH_NativeWindow_GetBufferHandleFromNative()
```
BufferHandle* OH_NativeWindow_GetBufferHandleFromNative (struct NativeWindowBuffer * buffer)
BufferHandle* OH_NativeWindow_GetBufferHandleFromNative (OHNativeWindowBuffer * buffer)
```
**描述:**
通过NativeWindowBuffer获取该buffer的BufferHandle指针
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
**返回:**
......@@ -181,7 +295,7 @@ BufferHandle 返回一个指针,指向BufferHandle的结构体实例
### OH_NativeWindow_GetNativeObjectMagic()
```
int32_t OH_NativeWindow_GetNativeObjectMagic (void * obj)
```
......@@ -190,13 +304,13 @@ int32_t OH_NativeWindow_GetNativeObjectMagic (void * obj)
获取NativeObject的MagicId
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
**返回:**
......@@ -209,7 +323,7 @@ MagicId 返回值为魔鬼数字,每个NativeObject唯一
### OH_NativeWindow_NativeObjectReference()
```
int32_t OH_NativeWindow_NativeObjectReference (void * obj)
```
......@@ -218,13 +332,13 @@ int32_t OH_NativeWindow_NativeObjectReference (void * obj)
增加一个NativeObject的引用计数
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
**返回:**
......@@ -237,7 +351,7 @@ GSError 返回值为错误码
### OH_NativeWindow_NativeObjectUnreference()
```
int32_t OH_NativeWindow_NativeObjectUnreference (void * obj)
```
......@@ -246,42 +360,42 @@ int32_t OH_NativeWindow_NativeObjectUnreference (void * obj)
减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
| obj | 参数是一个NativeWindow or NativeWindowBuffer的结构体实例的指针 |
**返回:**
GSError
GSError 返回值为错误码
**自从:**
8
### OH_NativeWindow_NativeWindowCancelBuffer()
### OH_NativeWindow_NativeWindowAbortBuffer()
```
int32_t OH_NativeWindow_NativeWindowCancelBuffer (struct NativeWindow * window, struct NativeWindowBuffer * buffer )
int32_t OH_NativeWindow_NativeWindowAbortBuffer (OHNativeWindow * window, OHNativeWindowBuffer * buffer )
```
**描述:**
通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
**返回:**
......@@ -294,25 +408,25 @@ GSError 返回值为错误码
### OH_NativeWindow_NativeWindowFlushBuffer()
```
int32_t OH_NativeWindow_NativeWindowFlushBuffer (struct NativeWindow * window, struct NativeWindowBuffer * buffer, int fenceFd, Region region )
int32_t OH_NativeWindow_NativeWindowFlushBuffer (OHNativeWindow * window, OHNativeWindowBuffer * buffer, int fenceFd, Region region )
```
**描述:**
通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
| fenceFd | 参数是一个文件描述符句柄,用以同步时序 |
| region | 参数表示一块脏区域,该区域有内容更新 |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的指针 |
| fenceFd | 参数是一个文件描述符句柄,用以同步时序 |
| region | 参数表示一块脏区域,该区域有内容更新 |
**返回:**
......@@ -325,23 +439,24 @@ GSError 返回值为错误码
### OH_NativeWindow_NativeWindowHandleOpt()
```
int32_t OH_NativeWindow_NativeWindowHandleOpt (struct NativeWindow * window, int code, ... )
int32_t OH_NativeWindow_NativeWindowHandleOpt (OHNativeWindow * window, int code, ... )
```
**描述:**
设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| code | 操作码 |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| code | 表示操作码,详见[NativeWindowOperation](#nativewindowoperation) |
| ... | 可变参数,必须与操作码一一对应 |
**返回:**
......@@ -354,24 +469,24 @@ GSError 返回值为错误码
### OH_NativeWindow_NativeWindowRequestBuffer()
```
int32_t OH_NativeWindow_NativeWindowRequestBuffer (struct NativeWindow * window, struct NativeWindowBuffer ** buffer, int * fenceFd )
int32_t OH_NativeWindow_NativeWindowRequestBuffer (OHNativeWindow * window, OHNativeWindowBuffer ** buffer, int * fenceFd )
```
**描述:**
通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产
@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| Name | 描述 |
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的二级指针 |
| fenceFd | 参数是一个文件描述符句柄 |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| buffer | 参数是一个NativeWindowBuffer的结构体实例的二级指针 |
| fenceFd | 参数是一个文件描述符句柄 |
**返回:**
......@@ -380,3 +495,125 @@ GSError 返回值为错误码
**自从:**
8
### OH_NativeWindow_NativeWindowSetMetaData()
```
int32_t OH_NativeWindow_NativeWindowSetMetaData (OHNativeWindow * window, uint32_t sequence, int32_t size, const OHHDRMetaData * metaData )
```
**描述:**
设置NativeWindow的元数据.
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| sequence | 生产缓冲区的序列 |
| size | OHHDRMetaData数组的大小 |
| metaDate | 指向OHHDRMetaData数组的指针 |
**返回:**
GSError 返回值为错误码
**自从:**
9
### OH_NativeWindow_NativeWindowSetMetaDataSet()
```
int32_t OH_NativeWindow_NativeWindowSetMetaDataSet (OHNativeWindow * window, uint32_t sequence, OHHDRMetadataKey key, int32_t size, const uint8_t * metaData )
```
**描述:**
设置NativeWindow的元数据集。
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针。 |
| sequence | 生产缓冲区的序列。 |
| key | 枚举值OHHDRMetadataKey |
| size | uint8_t向量的大小 |
| metaDate | 指向uint8_t向量的指针 |
**返回:**
GSError 返回值为错误码
**自从:**
9
### OH_NativeWindow_NativeWindowSetScalingMode()
```
int32_t OH_NativeWindow_NativeWindowSetScalingMode (OHNativeWindow * window, uint32_t sequence, OHScalingMode scalingMode )
```
**描述:**
设置NativeWindow的ScalingMode
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| sequence | 生产缓冲区的序列 |
| scalingMode | 枚举值OHScalingMode |
**返回:**
GSError 返回值为错误码
**自从:**
9
### OH_NativeWindow_NativeWindowSetTunnelHandle()
```
int32_t OH_NativeWindow_NativeWindowSetTunnelHandle (OHNativeWindow * window, const OHExtDataHandle * handle )
```
**描述:**
设置NativeWindow的TunnelHandle。
\@syscap SystemCapability.Graphic.Graphic2D.NativeWindow
**参数:**
| 名称 | 描述 |
| -------- | -------- |
| window | 参数是一个NativeWindow的结构体实例的指针 |
| handle | 指向OHExtDataHandle的指针 |
**返回:**
GSError 返回值为错误码
**自从:**
9
# OHExtDataHandle
## 概述
扩展数据句柄结构体定义。
**相关模块:**
[NativeWindow](_native_window.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [fd](#fd) | 句柄 Fd, -1代表不支持 |
| [reserveInts](#reserveints) | Reserve数组的个数 |
| [reserve](#reserve) [0] | Reserve数组 |
## 结构体成员变量说明
### fd
```
int32_t OHExtDataHandle::fd
```
**描述:**
句柄 Fd, -1代表不支持
### reserve
```
int32_t OHExtDataHandle::reserve[0]
```
**描述:**
Reserve数组
### reserveInts
```
uint32_t OHExtDataHandle::reserveInts
```
**描述:**
Reserve数组的个数
# OHHDRMetaData
## 概述
扩展数据句柄结构体定义。
**相关模块:**
[NativeWindow](_native_window.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [key](#key) | HDR元数据关键字 |
| [value](#value) | 关键字对应的值 |
## 结构体成员变量说明
### key
```
OHHDRMetadataKey OHHDRMetaData::key
```
**描述:**
HDR元数据关键字
### value
```
float OHHDRMetaData::value
```
**描述:**
关键字对应的值
# Rect
## 概述
矩形区域。
**相关模块:**
[NativeWindow](_native_window.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [x](#x) | 矩形框起始x坐标。 |
| [y](#y) | 矩形框起始y坐标。 |
| [w](#w) | 矩形框宽度。 |
| [h](#h) | 矩形框高度。 |
### x
```
int32_t Rect::x
```
**描述:**
矩形框起始x坐标。
### y
```
int32_t Rect::y
```
**描述:**
矩形框起始y坐标。
### w
```
uint32_t Rext::w
```
**描述:**
矩形框宽度。
### h
```
uint32_t Rect::h
```
**描述:**
矩形框高度。
# Region
## 概述
表示本地窗口NativeWindow需要更新内容的矩形区域(脏区)。
**相关模块:**
[NativeWindow](_native_window.md)
## 汇总
### 成员变量
| 成员变量名称 | 描述 |
| -------- | -------- |
| [*rects](#rects) | 如果rects是空指针nullptr, 默认Buffer大小为脏区。 |
| [rectNumber](#rectnumber) | 如果rectNumber为0,默认Buffer大小为脏区。 |
### rectNumber
```
int32_t Region::rectNumber
```
**描述:**
如果rectNumber为0,默认Buffer大小为脏区。
### \*rects
```
struct Rect Region::*rects
```
**描述:**
结构体指针,类型为[Rect](_rect.md)。如果rects是空指针nullptr, 默认Buffer大小为脏区。
<!--no_check-->
\ No newline at end of file
......@@ -17,19 +17,51 @@
## 汇总
### 结构体
| 结构体名称 | 描述 |
| -------- | -------- |
| [Region](_region.md) | 表示本地窗口NativeWindow需要更新内容的矩形区域(脏区)。 |
| [Region::Rect](_rect.md) | 矩形区域。 |
| [OHHDRMetaData](_o_h_h_d_r_meta_data.md) | HDR元数据结构体定义 。 |
| [OHExtDataHandle](_o_h_ext_data_handle.md) | 扩展数据句柄结构体定义 。 |
### 类型定义
| 类型定义名称 | 描述 |
| -------- | -------- |
| OHNativeWindow | 提供对NativeWindow的访问功能 |
| OHNativeWindowBuffer | 提供对NativeWindowBuffer的访问功能 |
| [Region](_region.md) | 表示本地窗口NativeWindow需要更新内容的矩形区域(脏区) |
### 枚举
| 枚举名称 | 描述 |
| -------- | -------- |
| [NativeWindowOperation](_native_window.md#nativewindowoperation) { SET_BUFFER_GEOMETRY, GET_BUFFER_GEOMETRY, GET_FORMAT, SET_FORMAT, GET_USAGE, SET_USAGE, SET_STRIDE, GET_STRIDE, SET_SWAP_INTERVAL, GET_SWAP_INTERVAL, SET_TIMEOUT, GET_TIMEOUT, SET_COLOR_GAMUT, GET_COLOR_GAMUT, SET_TRANSFORM, GET_TRANSFORM, SET_UI_TIMESTAMP } | OH_NativeWindow_NativeWindowHandleOpt函数中的操作码 |
| [OHScalingMode](_native_window.md#ohscalingmode) { OH_SCALING_MODE_FREEZE = 0, OH_SCALING_MODE_SCALE_TO_WINDOW, OH_SCALING_MODE_SCALE_CROP, OH_SCALING_MODE_NO_SCALE_CROP } | 缩放模式 Scaling Mode |
| [OHHDRMetadataKey](_native_window.md#ohhdrmetadatakey) { OH_METAKEY_RED_PRIMARY_X = 0, OH_METAKEY_RED_PRIMARY_Y = 1, OH_METAKEY_GREEN_PRIMARY_X = 2, OH_METAKEY_GREEN_PRIMARY_Y = 3, OH_METAKEY_BLUE_PRIMARY_X = 4, OH_METAKEY_BLUE_PRIMARY_Y = 5, OH_METAKEY_WHITE_PRIMARY_X = 6, OH_METAKEY_WHITE_PRIMARY_Y = 7, OH_METAKEY_MAX_LUMINANCE = 8, OH_METAKEY_MIN_LUMINANCE = 9, OH_METAKEY_MAX_CONTENT_LIGHT_LEVEL = 10, OH_METAKEY_MAX_FRAME_AVERAGE_LIGHT_LEVEL = 11, OH_METAKEY_HDR10_PLUS = 12, OH_METAKEY_HDR_VIVID = 13 } | 枚举HDR元数据关键字 |
### 函数
| 函数名称 | 描述 |
| 函数名称 | 描述 |
| -------- | -------- |
| [OH_NativeWindow_CreateNativeWindowFromSurface](_native_window.md#oh_nativewindow_createnativewindowfromsurface) (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例 |
| [OH_NativeWindow_DestroyNativeWindow](_native_window.md#oh_nativewindow_destroynativewindow) (struct NativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉 |
| [OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer](_native_window.md#oh_nativewindow_createnativewindowbufferfromsurfacebuffer) (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例 |
| [OH_NativeWindow_DestroyNativeWindowBuffer](_native_window.md#oh_nativewindow_destroynativewindowbuffer) (struct NativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉 |
| [OH_NativeWindow_NativeWindowRequestBuffer](_native_window.md#oh_nativewindow_nativewindowrequestbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产 |
| [OH_NativeWindow_NativeWindowFlushBuffer](_native_window.md#oh_nativewindow_nativewindowflushbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer, int fenceFd, Region region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费 |
| [OH_NativeWindow_NativeWindowCancelBuffer](_native_window.md#oh_nativewindow_nativewindowcancelbuffer) (struct NativeWindow \*window, struct NativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请 |
| [OH_NativeWindow_NativeWindowHandleOpt](_native_window.md#oh_nativewindow_nativewindowhandleopt) (struct NativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等 |
| [OH_NativeWindow_GetBufferHandleFromNative](_native_window.md#oh_nativewindow_getbufferhandlefromnative) (struct NativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针 |
| [OH_NativeWindow_NativeObjectReference](_native_window.md#oh_nativewindow_nativeobjectreference) (void \*obj) | 增加一个NativeObject的引用计数 |
| [OH_NativeWindow_NativeObjectUnreference](_native_window.md#oh_nativewindow_nativeobjectunreference) (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉 |
| [OH_NativeWindow_GetNativeObjectMagic](_native_window.md#oh_nativewindow_getnativeobjectmagic) (void \*obj) | 获取NativeObject的MagicId |
| [OH_NativeWindow_CreateNativeWindow](_native_window.md#oh_nativewindow_createnativewindow) (void \*pSurface) | 创建NativeWindow实例,每次调用都会产生一个新的NativeWindow实例 |
| [OH_NativeWindow_DestroyNativeWindow](_native_window.md#oh_nativewindow_destroynativewindow) (OHNativeWindow \*window) | 将NativeWindow对象的引用计数减1,当引用计数为0的时候,该NativeWindow对象会被析构掉 |
| [OH_NativeWindow_CreateNativeWindowBufferFromSurfaceBuffer](_native_window.md#oh_nativewindow_createnativewindowbufferfromsurfacebuffer) (void \*pSurfaceBuffer) | 创建NativeWindowBuffer实例,每次调用都会产生一个新的NativeWindowBuffer实例 |
| [OH_NativeWindow_DestroyNativeWindowBuffer](_native_window.md#oh_nativewindow_destroynativewindowbuffer) (OHNativeWindowBuffer \*buffer) | 将NativeWindowBuffer对象的引用计数减1,当引用计数为0的时候,该NativeWindowBuffer对象会被析构掉 |
| [OH_NativeWindow_NativeWindowRequestBuffer](_native_window.md#oh_nativewindow_nativewindowrequestbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*\*buffer, int \*fenceFd) | 通过NativeWindow对象申请一块NativeWindowBuffer,用以内容生产 |
| [OH_NativeWindow_NativeWindowFlushBuffer](_native_window.md#oh_nativewindow_nativewindowflushbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer, int fenceFd, [Region](_region.md) region) | 通过NativeWindow将生产好内容的NativeWindowBuffer放回到Buffer队列中,用以内容消费 |
| [OH_NativeWindow_NativeWindowAbortBuffer](_native_window.md#oh_nativewindow_nativewindowabortbuffer) (OHNativeWindow \*window, OHNativeWindowBuffer \*buffer) | 通过NativeWindow将之前申请出来的NativeWindowBuffer返还到Buffer队列中,供下次再申请 |
| [OH_NativeWindow_NativeWindowHandleOpt](_native_window.md#oh_nativewindow_nativewindowhandleopt) (OHNativeWindow \*window, int code,...) | 设置/获取NativeWindow的属性,包括设置/获取宽高、内容格式等 |
| [OH_NativeWindow_GetBufferHandleFromNative](_native_window.md#oh_nativewindow_getbufferhandlefromnative) (OHNativeWindowBuffer \*buffer) | 通过NativeWindowBuffer获取该buffer的BufferHandle指针 |
| [OH_NativeWindow_NativeObjectReference](_native_window.md#oh_nativewindow_nativeobjectreference) (void \*obj) | 增加一个NativeObject的引用计数 |
| [OH_NativeWindow_NativeObjectUnreference](_native_window.md#oh_nativewindow_nativeobjectunreference) (void \*obj) | 减少一个NativeObject的引用计数,当引用计数减少为0时,该NativeObject将被析构掉 |
| [OH_NativeWindow_GetNativeObjectMagic](_native_window.md#oh_nativewindow_getnativeobjectmagic) (void \*obj) | 获取NativeObject的MagicId |
| [OH_NativeWindow_NativeWindowSetScalingMode](_native_window.md#oh_nativewindow_nativewindowsetscalingmode) (OHNativeWindow \*window, uint32_t sequence, [OHScalingMode](_native_window.md#ohscalingmode) scalingMode) | 设置NativeWindow的ScalingMode |
| [OH_NativeWindow_NativeWindowSetMetaData](_native_window.md#oh_nativewindow_nativewindowsetmetadata) (OHNativeWindow \*window, uint32_t sequence, int32_t size, const [OHHDRMetaData](_o_h_h_d_r_meta_data.md) \*metaData) | 设置NativeWindow的元数据 |
| [OH_NativeWindow_NativeWindowSetMetaDataSet](_native_window.md#oh_nativewindow_nativewindowsetmetadataset) (OHNativeWindow \*window, uint32_t sequence, [OHHDRMetadataKey](_native_window.md#ohhdrmetadatakey) key, int32_t size, const uint8_t \*metaData) | 设置NativeWindow的元数据集。 |
| [OH_NativeWindow_NativeWindowSetTunnelHandle](_native_window.md#oh_nativewindow_nativewindowsettunnelhandle) (OHNativeWindow \*window, const [OHExtDataHandle](_o_h_ext_data_handle.md) \*handle) | 设置NativeWindow的TunnelHandle。 |
\ No newline at end of file
......@@ -58,7 +58,7 @@
1. 图片文件夹:放置文档中引用的图片,包含svg、png、gif等。
2. 系统资源文件夹:放置文档中引用的系统图标,无需关注。
3. Readme:目录 每一个新增的md文档,都需要写在Readme中。
3. Readme:目录每一个新增的md文档,都需要写在Readme中。
4. 文档:重点关注文档命名,详见后续描述。
![](figures/figure2.png)
......@@ -125,7 +125,7 @@ JS API 文档模板路径:[https://](https://gitee.com/openharmony/docs/blob/m
- **枚举(可选)**:一组值组成的类型。 以表格形式呈现,包括枚举名称、枚举值、说明。
- **类/interface(可选)**:一般包含自有属性和方法。以section形式呈现,包括类名/intrface名、描述、自有属性等。
- **类/interface(可选)**:一般包含自有属性和方法。以section形式呈现,包括类名/interface名、描述、自有属性等。
- **自定义类型( 可选)**:以k-v键值对表示的interface,描述和方法的参数一致。以表格形式呈现,包括参数名、类型、是否必填、说明。
......@@ -149,7 +149,7 @@ JS API 文档模板路径:[https://](https://gitee.com/openharmony/docs/blob/m
abandonmentMethod(deprecated)
\> 从API Version 7 开始废弃,建议使用newMethod替代。
\> 从API version 7 开始废弃,建议使用newMethod替代。
**写作示例**
......@@ -173,9 +173,9 @@ JS API 文档模板路径:[https://](https://gitee.com/openharmony/docs/blob/m
### 内容写作
概述模板链接:[https](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/concept-overview-template.md)[://gitee.com/openharmony/docs/blob/master/](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/concept-overview-template.md)[zh-cn](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/concept-overview-template.md)[/contribute/template/concept-overview-template.md](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/concept-overview-template.md)
概述模板链接:[concept-overview-template.md](template/concept-overview-template.md)
开发指导模板链接:[https://](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/guide-template.md)[gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/guide-template.md](https://gitee.com/openharmony/docs/blob/master/zh-cn/contribute/template/guide-template.md)
开发指导模板链接:[guide-template.md](template/guide-template.md)
**每一个文档必须包含的内容**
......
......@@ -27,13 +27,22 @@
**说明**:算法的安全性不在于算法本身的机密性。
**示例**:推荐使用的密码算法:
1)分组密码算法:AES(密钥长度在128位及以上)
2)流密码算法:AES(密钥长度在128位及以上)(OFB或CTR模式)
3)非对称加密算法:RSA(推荐3072位)
4)哈希算法:SHA2(256位及以上)
5)密钥交换算法:DH(推荐3072位)
6)HMAC(基于哈希的消息验证码)算法:HMAC-SHA2
不安全的密码算法举例如下:MD5/DES/3DES(加密传输协议TLS/SSH密码协议中避免使用3DES,非密码协议场景必须保证密钥K1≠K2≠K3)/HMAC-SHA2-256-96/HMAC-SHA1-96/HMAC-MD5/HMAC-MD5-96/SSH服务所有带CBC模式的算法/匿名算法套件/DH512/DH1024/SKIPJACK/RC2/RSA(1024位及以下)/MD2/MD4/blowfish/RC4。
不安全的密码算法举例如下:
MD5/DES/3DES(加密传输协议TLS/SSH密码协议中避免使用3DES,非密码协议场景必须保证密钥K1≠K2≠K3)/HMAC-SHA2-256-96/HMAC-SHA1-96/HMAC-MD5/HMAC-MD5-96/SSH服务所有带CBC模式的算法/匿名算法套件/DH512/DH1024/SKIPJACK/RC2/RSA(1024位及以下)/MD2/MD4/blowfish/RC4。
3-2 除标准协议外,避免使用差错控制编码(如奇偶校验、CRC)实现完整性校验。
3-3 密码算法中使用到的随机数必须是密码学意义上的安全随机数。
......@@ -41,10 +50,16 @@
**说明**:使用了不安全的随机数,容易导致密码算法的强度降低甚至算法的失效。
**示例**:可使用以下的安全随机数生成接口:
1) OpenSSL的RAND_bytes或RAND_priv_bytes;
2) OpenSSL FIPS模块中实现的DRBG;
3) JDK的java.security.SecureRandom;
4)类Unix平台的/dev/random文件
- OpenSSL的RAND_bytes或RAND_priv_bytes
- OpenSSL FIPS模块中实现的DRBG
- JDK的java.security.SecureRandom
- 类Unix平台的/dev/random文件
3-4 默认使用安全的密码算法,关闭或者禁用不安全的密码算法。在选择密码算法库时,应使用通过认证的或业界开源公认的或经评估认可的密码算法库。
......@@ -80,12 +95,19 @@
**示例**:截短消息认证码的配置举例:SSH协议中配置HMAC-MD5-96、HMAC-SHA1-96、HMAC-SHA2-256-96
哈希算法的标准输出长度如下,低于标准长度可视为截短:
1)SHA1/HMAC-SHA1,标准输出长度160比特
2)SHA224/HMAC-SHA224,标准输出长度224比特
3)SHA256/HMAC-SHA256,标准输出长度256比特
4)SHA384/HMAC-SHA384,标准输出长度384比特
5)SHA512/HMAC-SHA512,标准输出长度512比特
6)SHA-512/224/HMAC-SHA-512/224,标准输出长度224比特
7)SHA512/256/HMAC-SHA-512/256,标准输出长度256比特
3-13 使用HMAC保护数据完整性时,不能使用hash(key||message)或hash(message||key)的计算结果作为MAC值。
......@@ -94,7 +116,8 @@
3-14 同一笔业务中,若既需要加密运算也需要计算MAC时,加密操作和计算MAC操作不能使用同一个对称密钥。
**说明**:如果加密和MAC密钥相同,一旦密钥泄露,攻击者可以有针对性的篡改机密信息。
**说明**:如果加密和MAC密钥相同,一旦密钥泄露,攻击者可以有针对性的篡改机密信息。
3-15 加密时避免使用固定的IV(如:硬编码,或固定在配置文件中)。
**说明**:CBC模式的随机IV值可确保相同的明文、相同的密钥加密出的密文完全不同,如果IV无法确保每次加密都不同,对于CBC模式,攻击者可以轻易的进行密文替换攻击;CBC模式之外的其他分组密码运算模式(如:OFB、CRT等),攻击者可以非常容易的解密密文。
......@@ -103,7 +126,8 @@
**说明**:容易造成安全上的薄弱环节从而降低系统的安全性。
**示例**:匿名认证举例:TLS_DH_anon_WITH_3DES_EDE_CBC_SHA、TLS_DH_anon_WITH_AES_256_CBC_SHA
**示例**
匿名认证举例:TLS_DH_anon_WITH_3DES_EDE_CBC_SHA、TLS_DH_anon_WITH_AES_256_CBC_SHA
弱身份认证举例:密钥长度小于2048比特的RSA/DSA密钥
3-17 推荐仅选择使用ECDHE作为密钥交换算法的加密套件。
......@@ -128,9 +152,13 @@
4-2 认证凭据不需要还原的场景,应使用PBKDF2等不可逆的算法加密,对于性能敏感且安全性要求不高的场景可使用HMAC(认证凭据,盐值)(注:认证凭据、盐值位置可以互换)。
**示例**:1、认证凭据使用PBKDF2算法计算口令单向哈希时,迭代次数最低1000次。
2、盐值Salt为密码学意义上的安全随机数,由系统随机生成,盐值salt至少16字节,并按用户区分。
3、避免使用HASH(用户名||口令)、HMAC(用户名,口令)、HASH(口令 XOR salt)。
**示例**
1、认证凭据使用PBKDF2算法计算口令单向哈希时,迭代次数最低1000次。
2、盐值Salt为密码学意义上的安全随机数,由系统随机生成,盐值salt至少16字节,并按用户区分。
3、避免使用HASH(用户名||口令)、HMAC(用户名,口令)、HASH(口令 XOR salt)。
4-3 敏感数据如需通过非信任网络传输,应支持安全传输通道或者将数据加密后再传输的机制。
......@@ -140,11 +168,7 @@
## 5.系统管理和维护安全
5-1 对于系统自身操作维护类的接口的登录认证场景,应综合考虑实际业务场景及风险,采取下述一种或几种保护措施,实现口令防暴力破解机制:
1)锁定帐号;
2)锁定IP;
3)登录延迟;
4)验证码;
5-1 对于系统自身操作维护类的接口的登录认证场景,应综合考虑实际业务场景及风险,采取一种或几种保护措施,实现口令防暴力破解机制:锁定帐号、锁定IP、登录延迟、验证码。
5-2 对于系统自身操作维护类的口令,图形界面缺省不明文显示用户键入的所有口令。
......@@ -152,7 +176,10 @@
5-4 应使用合适的安全协议,不安全协议应默认关闭。
**示例**:安全协议举例:SSHv2/TLS1.2/TLS1.3/IPSec/SFTP/SNMPv3等协议,及其业界最新安全版本。对于流密码算法,建议使用AES的OFB和CTR模式或chacha20流加密算法替换RC4算法。
**示例**
安全协议举例:SSHv2/TLS1.2/TLS1.3/IPSec/SFTP/SNMPv3等协议,及其业界最新安全版本。对于流密码算法,建议使用AES的OFB和CTR模式或chacha20流加密算法替换RC4算法。
不安全协议举例:TFTP、FTP、Telnet、SSL2.0、SSL3.0、TLS1.0、TLS1.1、SNMP v1/v2和SSHv1.x。
5-5 基于权限最小化原则,系统新建账号默认不授予任何权限,或者默认只指派最小权限(如:只读权限)的角色。
......
# 概述
## 基本概念
*【 **写作要求**】*
*必选,描述本开发任务相关的基本概念,帮助开发者更好的理解开发任务。* *写作要求见下,完成写作后,请逐项自检*
| 内容要求 | 是否满足 |
| -------- | -------- |
| 业界通用的概念不用赘述。 | |
| 注意使用业界通用术语来表达,不用开发者无法理解的内部语言。 | |
【写作样例】
XX系统音频模块支持音频业务的开发,提供音频相关的功能,主要包括音频播放、音频采集、音量管理和短音播放等。
在进行应用的开发前,开发者应了解以下基本概念:
- 采样
采样就是把模拟信号数字化的过程,所有的模拟信号都需要通过采样转换为可以用0101来表示的数字信号。
- 采样率
采样率为每秒从连续信号中提取并组成离散信号的采样次数,单位用赫兹(Hz)来表示。通常人耳能听到频率范围大约在20Hz~20kHz之间的声音。常用的音频采样频率有:8kHz、11.025kHz、22.05kHz、16kHz、37.8kHz、44.1kHz、48kHz、96kHz、192kHz等。
- 声道
声道是指声音在录制或播放时在不同空间位置采集或回放的相互独立的音频信号,所以声道数也就是声音录制时的音源数量或回放时相应的扬声器数量。
- 音频帧
音频数据是流式的,本身没有明确的一帧帧的概念,在实际的应用中,为了音频算法处理/传输的方便,一般约定俗成取2.5ms~60ms为单位的数据量为一帧音频。这个时间被称之为“采样时间”,其长度没有特别的标准,它是根据编解码器和具体应用的需求来决定的。
## 运作机制
*【 **写作要求**】*
*可选。如果机制比较简单,通过前面基本概念就可以说清楚,此章节可以不用提供,删除标题即可*
*描述实现原理介绍机制,如关键步骤相关接口调用时机和触发时机,帮助开发者了解该功能的基本运作原理,以便更好的理解开发任务和定位问题*
*写作要求见下,完成写作后,请逐项自检*
| 内容要求 | 是否满足 |
| -------- | -------- |
| 仅描述开发任务相关的原理。 | |
| 尽量图文配合,一般使用时序图、流程图等形式。文字描述与图形描述匹配。 | |
【写作样例-1】
- 信号量初始化,为配置的N个信号量申请内存(N值可以由用户自行配置,受内存限制),并把所有的信号量初始化成未使用,并加入到未使用链表中供系统使用。
- 信号量创建,从未使用的信号量链表中获取一个信号量资源,并设定初值。
- 信号量申请,若其计数器值大于0,则直接减1返回成功。否则任务阻塞,等待其它任务释放该信号量,等待的超时时间可设定。当任务被一个信号量阻塞时,将该任务挂到信号量等待任务队列的队尾。
- 信号量释放,若没有任务等待该信号量,则直接将计数器加1返回。否则唤醒该信号量等待任务队列上的第一个任务。
- 信号量删除,将正在使用的信号量置为未使用信号量,并挂回到未使用链表。
- 信号量允许多个任务在同一时刻访问同一资源,但会限制同一时刻访问此资源的最大任务数目。访问同一资源的任务数达到该资源的最大数量时,会阻塞其他试图获取该资源的任务,直到有任务释放该信号量。
【写作样例-2】
**互斥锁运作原理**
多任务环境下会存在多个任务访问同一公共资源的场景,而有些公共资源是非共享的,需要任务进行独占式处理。互斥锁怎样来避免这种冲突呢?
用互斥锁处理非共享资源的同步访问时,如果有任务访问该资源,则互斥锁为加锁状态。此时其他任务如果想访问这个公共资源则会被阻塞,直到互斥锁被持有该锁的任务释放后,其他任务才能重新访问该公共资源,此时互斥锁再次上锁,如此确保同一时刻只有一个任务正在访问这个公共资源,保证了公共资源操作的完整性。
## 约束与限制
【写作要求】
*必选**描述本开发任务过程中* *的约束条件,以及此操作约束带来相应的负面影响,包括但不限于如下几方面*
- **功能限制**
- 功能使用范围(明确不支持的场景)。
- 规格限制。
* **操作限制**
* 已知问题的操作。
* 潜在风险的操作(如引起性能降低)。
* 引起性能降低的操作。
写作要求见下,完成写作后,请逐项自检。
| 内容要求 | 是否满足 |
| -------- | -------- |
| 明确功能限制或操作限制。 | |
| 约束对指导任务开发有影响或体验有感知,否则不用体现。 | |
| 容易出错的操作在步骤里描述,不在此体现。 | |
**写作样例**
**互斥锁的约束与限制**
- 两个任务不能对同一把互斥锁加锁。如果某任务对已被持有的互斥锁加锁,则该任务会被挂起,直到持有该锁的任务对互斥锁解锁,才能执行对这把互斥锁的加锁操作。
- 互斥锁不能在中断服务程序中使用。
- XXX作为实时操作系统需要保证任务调度的实时性,尽量避免任务的长时间阻塞,因此在获得互斥锁之后,应该尽快释放互斥锁。
- 持有互斥锁的过程中,不得再调用LOS_TaskPriSet等接口更改持有互斥锁任务的优先级。
# 许可证与版权规范
## 目的
本规范明确了OpenHarmony社区的代码贡献者、Committer、PMC成员如何处理Repo及源代码文件的许可与版权声明,包括如下几个部分
本规范明确了OpenHarmony社区的代码贡献者、Committer、PMC成员如何处理Repo及源代码文件的许可与版权声明,包括如下几个部分
1. LICENSE文件
2. NOTICE文件
3. 版权和许可头
......@@ -15,69 +15,72 @@
3. 最终规则经过社区充分的讨论后,由PMC定稿。
## LICENSE文件
1. 每个开源仓必须有清晰描述的许可证信息,且许可证必须与OpenHarmony整体许可证规则一致,如用户态开源仓使用Apache License 2.0许可协议,LiteOS内核态开源仓使用BSD 3-clause许可协议。
2. 每个开源仓的许可证文件必须为纯文本格式,放置于代码仓的根目录,里面包含该许可的全文,并且以“LICENSE”命名,不用带".txt",".md"等后缀。
1. 每个开源仓必须有清晰描述的许可证信息,且许可证必须与OpenHarmony整体许可证规则一致,如用户态开源仓使用Apache License 2.0许可协议LiteOS内核态开源仓使用BSD 3-clause许可协议。
2. 每个开源仓的许可证文件必须为纯文本格式,放置于代码仓的根目录,里面包含该许可的全文,并且以“LICENSE”命名,不用带".txt"".md"等后缀。
3. 如果开源仓的不同源码包含多种许可证,请将主许可证描述在以“LICENSE”命名的文件中,其它许可证请以“LICENSE-许可证类型-备注”命名并放置于仓的根目录或该许可证对应源码的根目录,同时在主许可证中描述各许可证文件位置及其适用的范围与场景。
4. 每个开源仓的许可证文件必须要涵盖该仓下所有文件,确保各许可证的涵盖范围描述准确、精简,并且不要包含不在本仓发布的其它源代码许可等不必要的信息,比如要单独下载的依赖软件的许可不要包含在仓和许可证信息中。
5. 如果开源仓在发布时以二进制形式发布,请确保许可证文件位于其发布格式的常规位置,如发布文件夹或压缩包的顶层目录,对于".jar"格式的文件,许可证可位于META-INF目录。
## NOTICE文件
1. 如分发的二进制文件中包含有第三方开源软件,请提供以“NOTICE”命名的文件,NOTICE文件以纯文本格式描述包含的所有第三方开源软件名称、软件版本、权利人声明、License信息
1. 如分发的二进制文件中包含有第三方开源软件,请提供以“NOTICE”命名的文件,NOTICE文件以纯文本格式描述包含的所有第三方开源软件名称、软件版本、权利人声明、License信息
2. NOTICE文件通常放置在发布文件夹或压缩包的顶层目录,对于".jar"格式的文件,许可证可位于META-INF目录。
## 版权和许可头
1. 开源仓中的文件原则上都应当包含合适的版权和许可头声明,除非是如下几种场景:
* 添加版权和许可声明会影响到该文件的功能,如JSON文件因不支持注释,可不添加版权和许可头。
* 工具生成的文件且包含说明该文件是由工具自动生成的描述信息。
* 简短的供用户阅读的说明文件,添加版权许可头会影响其可读性和,如README等。
* 添加版权和许可声明会影响到该文件的功能,如JSON文件因不支持注释,可不添加版权和许可头。
* 工具生成的文件且包含说明该文件是由工具自动生成的描述信息。
* 简短的供用户阅读的说明文件,添加版权许可头会影响其可读性和,如README等。
2. 版权和许可头声明形式如下:
```
Copyright (C) [第一次发布年份]-[当前版本发布年份] [版权所有者]
许可证头,以具体的许可证内容为准,如:
Apache License Version 2.0许可头:
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
BSD-3-Clause 许可头:
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
2. 版权头中的年份注意是作品对外发布的年份,如果是第一次发布则写发布年份即可,如果不是第一次发布,则写 "第一次发布年份-当前版本发布年份"。
3. 版权所有者是法律实体,可以是个人或者公司,若代表公司贡献代码,请写公司法律实体。
4. 许可头信息必须与该开源仓的许可证信息一致,如果某文件是双重许可证,则其许可头要清晰地说明各许可证的适用条件,并在文件许可头中包含各许可证定义的许可头描述。
```
Copyright (C) [第一次发布年份]-[当前版本发布年份] [版权所有者]
许可证头,以具体的许可证内容为准,如:
Apache License Version 2.0许可头:
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
BSD-3-Clause 许可头:
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list
of conditions and the following disclaimer in the documentation and/or other materials
provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
3. 版权头中的年份注意是作品对外发布的年份,如果是第一次发布则写发布年份即可,如果不是第一次发布,则写 "第一次发布年份-当前版本发布年份"。
4. 版权所有者是法律实体,可以是个人或者公司,若代表公司贡献代码,请写公司法律实体。
5. 许可头信息必须与该开源仓的许可证信息一致,如果某文件是双重许可证,则其许可头要清晰地说明各许可证的适用条件,并在文件许可头中包含各许可证定义的许可头描述。
......@@ -677,7 +677,7 @@ WLAN驱动基于HDF框架和Platform框架开发,不区分OS和芯片平台,
exit 0
```
- 新建udhcpd.conf文件(启动UDHCPD配置文件)并将以下内容复制到该文件中。
- 新建udhcpd.conf文件(启动UDHCPD配置文件)并将以下内容(其中opt dns x.x.x.x x.x.x.x配置了两个DNS服务器地址,开发者可按照实际情况自行配置)复制到该文件中。
```text
start 192.168.12.2
......@@ -691,7 +691,7 @@ WLAN驱动基于HDF框架和Platform框架开发,不区分OS和芯片平台,
offer_time 60 #default: 60 (1 minute)
min_lease 60 #defult: 60
lease_file /vendor/etc/udhcpd.leases
opt dns 10.221.0.11 8.8.8.8
opt dns x.x.x.x x.x.x.x
option subnet 255.255.255.0
opt router 192.168.12.1
```
......
......@@ -23,7 +23,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完
1. 安装Docker,Docker安装请参考[官方指导](https://docs.docker.com/engine/install/)
2. 获取OpenHarmony源码,请参考[获取源码](https://device.harmonyos.com/cn/docs/documentation/guide/sourcecode-acquire-0000001050769927)
2. 获取OpenHarmony源码,请参考[获取源码](sourcecode-acquire.md)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**<br>
> HPM Docker环境无需单独获取源码。
......
......@@ -175,15 +175,20 @@ bash build/prebuilts_download.sh
```shell
./build.sh --product-name {product_name} --gn-args is_debug=true
```
![icon-note.gif](public_sys-resources/icon-note.gif)**注意**:Debug全版本因镜像大小限制,全量编译可能无法烧录,建议单模块编译Debug二进制。使用如下命令单独编译模块 :
```
./build.sh --product-name {product_name} --gn-args is_debug=true --build-target {target_name}
```
> ![icon-caution.gif](public_sys-resources/icon-caution.gif) **注意:**
> Debug全版本因镜像大小限制,全量编译可能无法烧录,建议单模块编译Debug二进制。使用如下命令单独编译模块:
>
>
> ```
> ./build.sh --product-name {product_name} --gn-args is_debug=true --build-target {target_name}
> ```
>
{product_name}为当前版本支持的平台。比如:hispark_taurus_standard等。
编译完成后,结果镜像保存在 out/{device_name}/packages/phone/images/ 目录下。
- 编译命令支持选项:./build.sh
```shell
......@@ -321,6 +326,10 @@ optional arguments:
-h, --help show this help message and exit
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> - 设备开发过程中详细的编译环境搭建及编译步骤请参考[快速入门中的环境搭建及编译章节。](../quick-start/Readme-CN.md)
> - OpenHarmony还为开发者提供了Docker编译环境,可以省略编译工具的安装,具体使用请参考[Docker编译指导。](../get-code/gettools-acquire.md)
### 新增并编译不同配置
根据上一节的配置规则新增相应配置并进行编译,主要包含产品、部件、芯片解决方案和模块四个粒度。具体如下:
......
......@@ -8,5 +8,5 @@
- [版本说明](release-notes/Readme.md)
- [子系统介绍](./readme)
- OpenHarmony项目贡献者参考文档
- [项目贡献指南](contribute/贡献指南.md)
- [项目贡献指南](contribute/Readme-CN.md)
- [部件及API设计参考](./design)
\ No newline at end of file
# 全局资源调度子系统
全局资源调度子系统承担系统中CPU、内存、存储资源的调度管理,包括任务的分组,优先级管理,后台任务的管理等。在保障前台操作流畅的基础上,尽力提供后台多任务流畅运行的环境。同时, 全局资源调度子系统也负责性能、功耗、热的均衡调度,即考虑用户操作的及时响应, 也护航系统的长续航能力,并兼顾系统发热控制,避免发热和控制发热的影响在可控范围内。
## 简介
全局资源调度子系统主要适用于标准系统,对于轻量系统,一般进行删减处理。下面的介绍仅针对标准系统。
全局资源调度子系统从整个系统的性能、功耗、热三个维度分别对CPU、内存、IO、网络、软资源进行调度和管控,即三大调度引擎五大资源维度。所述软资源包括前后台任务、消息、队列等可管理的软件实体。全局资源调度子系统的模块划分如下图所示:
![子系统readme](figures/res_sched.png)
全局资源调度子系统主要分接口层、框架层、服务层、内核层。DFX覆盖整个系统的所有层面和领域。
分层说明如下:
接口层: 提供调度API 接口扩展。核心API主要是应用后台API,按应用在后台的行为逻辑分长时任务、短时任务、定时任务、延时任务、传输任务、PUSH消息。
框架层: 提供资源调度的三大核心引擎:
性能调度引擎: 主要保障用户操作的及时响应和长期流畅。 其核心功能围绕CPU、内存、IO、网络、软资源提供资源的及时供给,优先保障前台应用的资源需求;同时保障后台可感知任务的基本需求,避免后台任务的饿死。
功耗调度引擎: 主要是限制资源的过渡使用,对五大资源的使用提供约束手段。并提供后台任务管理、外设器件低功耗调度、省电和待机模式、功耗异常防护等核心功能。
温控调度引擎: 根据系统的发热情况和发热预期提供对高功耗资源的长时间限制策略。温控调度引擎区分发热级别和识别发热源,针对性的采取发热控制。
服务层:提供资源访问的统一接口,对并发访问实现冲突消减措施。包括SoC 调频、电源管理、传输代理、PUSH 消息代理、以及外设驱动框架。
内核层:实现资源调度的内核扩展和适配,为用户态的调度提供扩展能力。
DFX:提供场景化信息采集功能,性能、功耗、热管控事件日志功能,外设器件功耗建模功能,以及系统异常的分析和告警功能。
## 目录
```
foundation/resourceschedule/
├── background_task_mgr #后台任务管理
├── device_usage_statistics #设备使用统计
├── frame_aware_sched #感知调度
├── memmgr #内存管理
├── resource_schedule_service #全局资源调度引擎
└── work_scheduler #后台定时任务调度
```
## 约束
语言版本:C++11及以上
## 编译构建/使用方法
参考各仓README以及test目录
## 相关仓
**资源调度子系统**
[resourceschedule_background_task_mgr](https://gitee.com/openharmony/resourceschedule_background_task_mgr)
[resourceschedule_device_usage_statistics](https://gitee.com/openharmony/resourceschedule_device_usage_statistics)
[resourceschedule_work_scheduler](https://gitee.com/openharmony/resourceschedule_work_scheduler)
[aafwk_standard](https://gitee.com/openharmony/aafwk_standard)
[windowmanager](https://gitee.com/openharmony/windowmanager)
[communication_ipc](https://gitee.com/openharmony/communication_ipc)
[powermgr_battery_manager](https://gitee.com/openharmony/powermgr_battery_manager)
[notification_ces_standard](https://gitee.com/openharmony/notification_ces_standard)
[hiviewdfx_hilog](https://gitee.com/openharmony/hiviewdfx_hilog)
\ No newline at end of file
# 帐号子系统<a name="ZH-CN_TOPIC_0000001078092678"></a>
# 帐号子系统<a name="ZH-CN_TOPIC_0000001123681215"></a>
- [简介](#section11660541593)
- [子系统架构图](#section1412183212132)
- [架构图](#section1412183212132)
- [目录](#section161941989596)
- [使用说明](#section1312121216216)
- [说明](#section1312121216216)
- [模块说明](#section1551164914236)
- [使用说明](#section1551164914237)
- [相关仓](#section1371113476307)
## 简介<a name="section11660541593"></a>
在标准系统上,帐号子系统主要提供分布式帐号登录状态管理能力,支持在端侧对接厂商云帐号应用,提供云帐号登录状态查询和更新的管理能力。
在标准系统上,帐号子系统主要提供系统帐号生命周期管理,分布式帐号登录状态管理和应用帐号信息管理等基础能力。
## 子系统架构图<a name="section1412183212132"></a>
## 架构图<a name="section1412183212132"></a>
**图 1** 帐号子系统架构图<a name="fig4460722185514"></a>
![](figures/zh-cn_image_0000001079026550.png)
![](figures/zh-cn_image_account_struct.png)
## 目录<a name="section161941989596"></a>
```
/base/account
└── os_account # 系统帐号组件
├── common # 公共基础模块
├── interfaces # 对外接口存放目录
├── kits # 系统帐号组件开发框架
├── sa_profile # 帐号SA配置文件定义目录
├── services # 系统帐号组件服务代码
└── test # 系统帐号组件测试代码
└── resource # 系统帐号组件测试资源
/base/account/os_account
├── dfx
│ ├── hidumper_adapter 系统服务信息导出适配器代码
│ ├── hisysevent_adapter 系统事件打点适配器代码
├── figures README图片
├── frameworks 帐号子系统kit代码
│ ├── account_iam 账号身份认证和访问管理内部API代码
│ │ └── src 账号身份认证和访问管理内部API实现代码
│ ├── appaccount 应用帐号内部API代码
│ │ └── native 应用帐号内部API实现代码
│ ├── common 共通模块代码
│ │ ├── account_error 错误码
│ │ ├── database 数据库基础代码
│ │ ├── file_operator 文件操作代码
│ │ ├── log 打印日志代码
│ │ ├── perf_stat 性能统计
│ │ └── test 共通模块测试代码
│ ├── ohosaccount 分布式帐号内部API代码
│ │ ├── native 分布式帐号内部API实现代码
│ │ └── test 分布式帐号内部API测试代码
│ └── osaccount 系统帐号内部API代码
│ ├── core 系统帐号ipc
│ └── native 系统帐号内部API实现代码
├── interfaces 帐号子系统对外公开的API
│ ├── innerkits 内部API头文件
│ │ ├── account_iam 账号身份认证和访问管理
│ │ ├── appaccount 应用帐号内部API头文件
│ │ ├── ohosaccount 分布式帐号内部API头文件
│ │ └── osaccount 系统帐号内部API头文件
│ └── kits 对外API封装
│ └── napi 帐号子系统对外API封装代码
├── sa_profile 帐号子系统SA配置文件定义目录
├── services 帐号子系统accountmgr服务代码
│ └── accountmgr 帐号子系统服务代码
│ ├── include 帐号子系统服务代码头文件
│ ├── src 帐号子系统服务代码源文件
│ └── test 帐号子系统服务测试
├── test 测试代码
│ ├── fuzztest 模糊测试代码
│ ├── resource 测试资源文件
│ └── systemtest 系统测试代码
└── tools acm工具代码
├── acm acm工具代码
│ ├── include acm工具代码头文件
│ └── src acm工具代码源文件
└── test acm工具测试代码
```
## 使用说明<a name="section1312121216216"></a>
通过提供的分布式帐号管理类,可以查询和更新帐号登录状态,包括登录、登出、注销及Token失效。
查询和更新分布式帐号登录状态,需要系统权限,仅支持系统应用。
## 说明<a name="section1312121216216"></a>
### 模块说明<a name="section1551164914236"></a>
<table>
<thead align="left"><tr id="row175061254462">
<th class="cellrowborder" valign="top" width="20%" id="mcps1.2.3.1.1"><p id="p1250613547612"><a name="p1250613547612"></a><a name="p1250613547612"></a>模块名</p>
</th>
<th class="cellrowborder" valign="top" width="80%" id="mcps1.2.3.1.2"><p id="p85066541767"><a name="p85066541767"></a><a name="p85066541767"></a>描述</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row0506185417614"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1561112131788"><a name="p1561112131788"></a><a name="p1561112131788"></a>系统帐号</p>
</td>
<td class="cellrowborder" valign="top" width="80%" headers="mcps1.2.3.1.2 "><p id="p1954531161115"><a name="p1954531161115"></a><a name="p1954531161115"></a>提供系统帐号的添加、删除、查询、修改、订阅和启动等功能。</p>
</td>
</tr>
<tr id="row0506185417614"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1561112131788"><a name="p1561112131788"></a><a name="p1561112131788"></a>分布式帐号</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p1954531161115"><a name="p1954531161115"></a><a name="p1954531161115"></a>提供分布式帐号登录状态管理能力,支持在端侧对接厂商云帐号应用,提供云帐号登录状态查询和更新能力。</p>
</td>
</tr>
<tr id="row0506185417614"><td class="cellrowborder" valign="top" width="20%" headers="mcps1.2.3.1.1 "><p id="p1561112131788"><a name="p1561112131788"></a><a name="p1561112131788"></a>应用帐号</p>
</td>
<td class="cellrowborder" valign="top" width="80%" headers="mcps1.2.3.1.2 "><p id="p1954531161115"><a name="p1954531161115"></a><a name="p1954531161115"></a>提供应用帐号的添加、删除、查询、修改和鉴权等功能。</p>
</td>
</tr>
</tbody>
</table>
### 使用说明<a name="section1551164914237"></a>
[1. 系统帐号](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-osAccount.md)
[2. 分布式帐号](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md)
[3. 应用帐号](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-appAccount.md)
## 相关仓<a name="section1371113476307"></a>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册