提交 e207d64e 编写于 作者: X xsz233 提交者: Gitee

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

Signed-off-by: Nxsz233 <xushizhe@huawei.com>
......@@ -18,7 +18,7 @@ This repository stores device and application development documents provided by
- master: the latest version.
- OpenHarmony 3.2 Beta5. [Learn more](en/release-notes/OpenHarmony-v3.2-beta5.md)
- OpenHarmony 3.2 Release. [Learn more](en/release-notes/OpenHarmony-v3.2-release.md)
- OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md)
......
......@@ -36,7 +36,7 @@ Strong consistency has high requirements on distributed data management and may
## Access Control Mechanism in Cross-Device Synchronization
In the application data synchronization across devices, data access is controlled based on the device level and [data security label](access-control-by-device-and-data-level.md#data-security-label). In principle, data can be synchronized only to the devices whose data security labels are not higher than the device's security level. The access control matrix is as follows:
In the application data synchronization across devices, data access is controlled based on the device level and [data security label](access-control-by-device-and-data-level.md#data-security-labels). In principle, data can be synchronized only to the devices whose data security labels are not higher than the device's security level. The access control matrix is as follows:
|Device Security Level|Data Security Labels of the Synchornizable Device|
|---|---|
......
# Atomic Service Space Management (for System Applications Only)
Space management for atomic services is necessary from two aspects. On the one hand, users are unaware of the installation of atomic services and do not proactively uninstall them. On the other hand, atomic services have the [installation-free](../reference/apis/js-apis-freeInstall.md) feature, but they are not actually free of installation. This topic describes how to manage the space usage of atomic services for better system space usage.
## Managing Quota for Atomic Service Data Directories
Set a storage quota for the data sandbox directory of an atomic service. This quota can be obtained through the system parameter **persist.sys.bms.aging.policy.atomicservice.datasize.threshold**. The default value is 1024 MB. When the quota is used up, writing data will return an error message.
You can run the [param get/set](../../device-dev/subsystems/subsys-boot-init-plugin.md) command to view and set system parameters.
## Proactively Destroying Atomic Services
To proactively destroy an atomic service, call the [uninstall](../reference/apis/js-apis-installer.md#bundleinstalleruninstall) API.
**Example**
```ts
import installer from '@ohos.bundle.installer';
let bundleName = 'com.ohos.demo';
let installParam = {
userId: 100
};
try {
installer.getBundleInstaller().then(data => {
data.uninstall(bundleName, installParam, err => {
if (err) {
console.error('uninstall failed:' + err.message);
} else {
console.info('uninstall successfully.');
}
});
}).catch(error => {
console.error('getBundleInstaller failed. Cause: ' + error.message);
});
} catch (error) {
console.error('getBundleInstaller failed. Cause: ' + error.message);
}
```
## Automatically Destroying Atomic Services
### Automatic Destruction Time
Automatic destruction of atomic services can be triggered in any of the following conditions:
- When a timer is set and the given interval has elapsed. The timer interval can be obtained through the system parameter **persist.sys.bms.aging.policy.timer.interval**, which is 8 hours by default. The remaining battery level must be greater than or equal to the value of **persist.sys.bms.aging.policy.battery.threshold**, which is 10% by default.
- When an atomic service is installed.
- When the clearance flag of an atomic service is modified.
### Destruction Conditions
#### Prerequisites
- [isHapModuleRemovable](../reference/apis/js-apis-freeInstall.md#ishapmoduleremovable) is set to **true**.
- The atomic service is not running.
#### Condition for Starting Destruction
The space occupied by all atomic services (including their installation and data directories) is greater than the value of **persist.sys.bms.aging.policy.data.size.threshold**, which is 500 MB by default.
#### Condition for Ending Destruction
The space occupied by all atomic services (including the installation and data directories) is less than 80% of the value of **persist.sys.bms.aging.policy.data.size.threshold**.
### Automatic Destruction Sequence
- Atomic services that can be destroyed are classified into different time slots based on the last used time, for example, [0, 10), [10, 20), [20, 30), [30, ~). The time slot unit can be obtained from the system parameter **persist.sys.bms.aging.policy.recently.used.threshold**, which is 1 day by default.
- For any two atomic services that can be destroyed, if they are in the same time slot, the atomic service that is less used is destroyed first; if they are in different time slots, the atomic service that is not used for a longer time is destroyed first.
### Automatic Destruction by Level
- When the condition for starting automatic destruction is met, the cache directories of the atomic services are destroyed first based on the destruction sequence. If the condition for ending destruction is met, the destruction is ended.
- If the condition for ending destruction is not met, the other directories of the atomic service are destroyed based on the destruction sequence.
......@@ -932,6 +932,11 @@ Indicates that the HTTP proxy configuration has changed.
- Value: **usual.event.HTTP_PROXY_CHANGE**
- Required subscriber permissions: none
## COMMON_EVENT_DOMAIN_ACCOUNT_STATUS_CHANGED<sup>10+<sup>
Indicates that the domain account status has changed.
- Value: **usual.event.DOMAIN_ACCOUNT_STATUS_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIM_STATE_CHANGED<sup>10+<sup>
Indicates that the SIM card state has changed.
- Value: **usual.event.SIM_STATE_CHANGED**
......
......@@ -122,6 +122,14 @@ Deregisters a mission status listener.
| listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300002 | Input error. The specified mission listener does not exist. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -209,6 +217,14 @@ Deregisters a mission status listener. This API uses a promise to return the res
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300002 | Input error. The specified mission listener does not exist. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -624,6 +640,14 @@ Locks a given mission. This API uses an asynchronous callback to return the resu
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -667,6 +691,14 @@ Locks a given mission. This API uses a promise to return the result.
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
......@@ -702,6 +734,14 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
import missionManager from '@ohos.app.ability.missionManager';
......@@ -744,6 +784,14 @@ Unlocks a given mission. This API uses a promise to return the result.
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16300001 | Mission not found. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -924,6 +972,14 @@ Switches a given mission to the foreground. This API uses an asynchronous callba
| missionId | number | Yes| Mission ID.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -963,6 +1019,14 @@ Switches a given mission to the foreground, with the startup parameters for the
| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......@@ -1007,6 +1071,14 @@ Switches a given mission to the foreground, with the startup parameters for the
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Error codes**
| ID| Error Message|
| ------- | -------- |
| 16000009 | An ability cannot be started or stopped in Wukong mode. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
......
......@@ -32,12 +32,12 @@ import StartOptions from '@ohos.app.ability.StartOptions';
try {
missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) {
console.error('getMissionInfos failed, error.code: ${error.code}, error.message: ${error.message}');
if (error) {
console.error(`getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`);
return;
}
console.log('size = ${missions.length}');
console.log('missions = ${JSON.stringify(missions)}');
console.log(`size = ${missions.length}`);
console.log(`missions = ${JSON.stringify(missions)}`);
let id = missions[0].missionId;
let startOptions = {
......@@ -45,10 +45,10 @@ import StartOptions from '@ohos.app.ability.StartOptions';
displayId: 0
};
missionManager.moveMissionToFront(id, startOptions).then(() => {
console.log('moveMissionToFront is called ');
console.log('moveMissionToFront is called');
});
});
} catch (paramError) {
console.error('error: ${paramError.code}, ${paramError.message}');
console.error(`error: ${paramError.code}, ${paramError.message}`);
}
```
......@@ -28,31 +28,13 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return
| callback | AsyncCallback\<WantAgent\> | Yes | Callback used to return the **WantAgent** object.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -125,31 +107,13 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. If
| Promise\<WantAgent\> | Promise used to return the **WantAgent** object.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -211,31 +175,13 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous
| callback | AsyncCallback\<string\> | Yes | Callback used to return the bundle name.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -321,31 +267,13 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re
| Promise\<string\> | Promise used to return the bundle name.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -422,31 +350,13 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal
| callback | AsyncCallback\<number\> | Yes | Callback used to return the user ID.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -533,31 +443,13 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return
| Promise\<number\> | Promise used to return the user ID.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -635,31 +527,14 @@ Obtains the want in a **WantAgent** object. This API uses an asynchronous callba
| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -747,31 +622,14 @@ Obtains the want in a **WantAgent** object. This API uses a promise to return th
| Promise\<Want\> | Promise used to return the want.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -826,7 +684,7 @@ function getWantAgentCallback(err, data) {
try {
WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback);
} catch(err) {
console.error('getWantAgent failed! ${err.code} ${err.message}');
console.error('getWantAgent failed! ${err.code} ${err.message}}');
}
```
......@@ -848,31 +706,13 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -958,31 +798,13 @@ Cancels a **WantAgent** object. This API uses a promise to return the result.
| Promise\<void\> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1057,33 +879,6 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur
| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. |
| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example**
```ts
......@@ -1167,33 +962,6 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
| otherAgent | WantAgent | Yes | Target **WantAgent** object. |
| callback | AsyncCallback\<boolean\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example**
```ts
......@@ -1280,33 +1048,6 @@ Checks whether two **WantAgent** objects are equal to determine whether the same
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| Promise\<boolean\> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
**Example**
```ts
......@@ -1382,31 +1123,14 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron
| callback | AsyncCallback\<number> | Yes | Callback used to return the operation type.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -1490,31 +1214,14 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to
| Promise\<number> | Promise used to return the operation type.|
**Error codes**
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
| ID | Error Message |
|-----------|--------------------|
| 16000001 | Input error. The specified ability name does not exist. |
| 16000002 | Ability type error. The specified ability type is wrong.|
| 16000003 | Input error. The specified id does not exist.|
| 16000004 | Visibility verification failed.|
| 16000006 | Can not cross user operations.|
| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.|
| 16000008 | Crowdtest App Expiration.|
| 16000009 | Can not start ability in wukong mode.|
| 16000010 | Can not operation with continue flag.|
| 16000011 | Context does not exist.|
| 16000050 | Internal Error.|
| 16000051 | Network error. The network is abnormal.|
| 16000052 | Free install not support. The application does not support free install.|
| 16000053 | Not top ability. The application is not top ability.|
| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.|
| 16000055 | Free install timeout.|
| 16000056 | Can not free install other ability.|
| 16000057 | Not support cross device free install.|
| 16000101 | execute shell command failed.|
| 16000015 | Service timeout.|
| 16000151 | Invalid wantagent object.|
| 16000152 | wantAgent object not found.|
| 16000153 | wangAgent object canceled.|
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......
......@@ -9,6 +9,7 @@ The **ApplicationInfo** module defines the application information. A system app
## ApplicationInfo
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
| Name | Type | Readable| Writable| Description |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Application name. |
......@@ -33,3 +34,4 @@ The **ApplicationInfo** module defines the application information. A system app
| appProvisionType | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**. |
| systemApp | boolean | Yes | No | Whether the application is a system application. |
| bundleType |[BundleType](js-apis-bundleManager.md#bundletype) | Yes | No | Bundle type, which can be **APP** (common application) or **ATOMIC_SERVICE** (atomic service). |
| debug<sup>10+</sup> | boolean | Yes | No | Whether the application is in debugging mode. The default value is **false**. |
# BusinessAbilityInfo
> **NOTE**
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
The **BusinessAbilityInfo** module provides basic information about a business ability.
## BusinessAbilityInfo
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
| Name | Type | Readable| Writable| Description |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
| bundleName | string | Yes | No | Bundle name.|
| moduleName | string | Yes | No | Module name.|
| name | string | Yes | No | Name of the business ability.|
| labelId | number | Yes | No | Label ID of the module. |
| descriptionId | number | Yes | No | Description ID of the module. |
| iconId | number | Yes | No | ID of the icon that describes the ability information.|
| businessType | [businessAbilityRouter.BusinessType](js-apis-businessAbilityRouter.md#businesstype) | Yes| No| Type of the business ability.|
| applicationInfo | Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | No | Application information. |
# @ohos.app.businessAbilityRouter (Business Ability Router)
The **businessAbilityRouter** module provides APIs for you to query the business ability information of applications installed on the device. It provides a unified template for you to register standard services by type. Based on the information, a system application or third-party application can obtain services that meet certain criteria and select a proper service. The module also provides unified rules to manage redirection between applications and services. It prevents arbitrary switching between the foreground and background and avoids the distribution of third-party applications by means of redirection.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. 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
``` ts
import businessAbilityRouter from '@ohos.app.businessAbilityRouter';
```
## Required Permissions
| Permission | Permission Level | Description |
| ------------------------------------------ | ------------ | -------------------- |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all bundles.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
## BusinessType
Enumerates the types of business abilities.
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**System API**: This is a system API.
| Name | Value | Description |
| ----------- | ---- | ------------------------------------ |
| SHARE | 0 | Business ability of the share type.|
| UNSPECIFIED | 255 | Business ability of an unspecified type. |
## BusinessAbilityFilter
Describes the criteria for filtering business abilities.
**System capability**: SystemCapability.BundleManager.BundleFrameWork.FreeInstall
**System API**: This is a system API.
| Name | Type | Readable| Writable| Description |
| ------------ | ------------ | ---- | ---- | -------------------------------------- |
| businessType | BusinessType | Yes | No | Type of the business ability. |
| mimeType | string | Yes | No | MIME type supported by the business ability.|
| uri | string | Yes | No | URI supported by the business ability. |
## businessAbilityRouter.queryBusinessAbilityInfo
queryBusinessAbilityInfo(filter: BusinessAbilityFilter, callback: AsyncCallback\<Array\<BusinessAbilityInfo\>\>): void;
Obtains the business ability information based on the specified filter criteria. This API uses an asynchronous callback to return the result. If the operation is successful, the business ability information is returned; otherwise, an error object is returned.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| filter | [BusinessAbilityFilter](#businessabilityfilter) | Yes | Object used to filter the business abilities.|
| callback | AsyncCallback\<Array\<[BusinessAbilityInfo](js-apis-bundleManager-businessAbilityInfo.md#businessabilityinfo)\>\> | Yes| Callback used to return the result. If the operation is successful, the business ability information that meets the filter criteria is returned; otherwise, an error object is returned.|
**Example**
```ts
import businessAbilityRouter from '@ohos.app.businessAbilityRouter';
let filter = {businessType: businessAbilityRouter.BusinessType.SHARE};
try {
businessAbilityRouter.queryBusinessAbilityInfo(filter)
.then(() => {
console.info('queryBusinessAbilityInfo success');
}).catch((error) => {
console.error('queryBusinessAbilityInfo failed ' + error.message);
});
} catch (error) {
console.error('queryBusinessAbilityInfo failed ' + error.message);
}
```
## businessAbilityRouter.queryBusinessAbilityInfo
queryBusinessAbilityInfo(filter: BusinessAbilityFilter): Promise\<Array\<BusinessAbilityInfo\>\>;
Obtains the business ability information based on the specified filter criteria. This API uses a promise to return the result. If the operation is successful, the business ability information is returned; otherwise, an error object is returned.
**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**: SystemCapability.BundleManager.BundleFramework.Core
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------------------- | ---- | --------------------------------------- |
| filter | [BusinessAbilityFilter](#businessabilityfilter) | Yes | Object used to filter the business abilities. |
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ------------------------------------------- |
| Promise\<Array\<[BusinessAbilityInfo](js-apis-bundleManager-businessAbilityInfo.md#businessabilityinfo)\>\> | Promise used to return the business ability information that meets the filter criteria.|
**Example**
```ts
import businessAbilityRouter from '@ohos.app.businessAbilityRouter';
let filter = {businessType: businessAbilityRouter.BusinessType.SHARE};
try {
businessAbilityRouter.queryBusinessAbilityInfo(filter, (error, data) => {
if (error) {
console.error('queryBusinessAbilityInfo failed ' + error.message);
return;
}
console.info('queryBusinessAbilityInfo success');
});
} catch (error) {
console.error('queryBusinessAbilityInfo failed ' + error.message);
}
```
......@@ -20,9 +20,7 @@ For details about the definitions of all system common events, see [System Commo
## CommonEventManager.publish
```ts
publish(event: string, callback: AsyncCallback<void>): void
```
publish(event: string, callback: AsyncCallback\<void>): void
Publishes a common event and executes an asynchronous callback after the event is published.
......@@ -37,7 +35,15 @@ Publishes a common event and executes an asynchronous callback after the event i
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -61,9 +67,7 @@ try {
## CommonEventManager.publish
```ts
publish(event: string, options: CommonEventPublishData, callback: AsyncCallback<void>): void
```
publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
Publishes a common event with given attributes. This API uses an asynchronous callback to return the result.
......@@ -79,7 +83,15 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -110,9 +122,7 @@ try {
## CommonEventManager.publishAsUser<sup>
```ts
publishAsUser(event: string, userId: number, callback: AsyncCallback<void>): void
```
publishAsUser(event: string, userId: number, callback: AsyncCallback\<void>): void
Publishes a common event to a specific user. This API uses an asynchronous callback to return the result.
......@@ -130,7 +140,16 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -157,9 +176,7 @@ try {
## CommonEventManager.publishAsUser
```ts
publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback<void>): void
```
publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\<void>): void
Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result.
......@@ -178,7 +195,16 @@ Publishes a common event with given attributes to a specific user. This API uses
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not System services. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
| 1500009 | error obtaining system parameters. |
**Example**
......@@ -212,9 +238,7 @@ try {
## CommonEventManager.createSubscriber
```ts
createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback<CommonEventSubscriber>): void
```
createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>): void
Creates a subscriber. This API uses an asynchronous callback to return the result.
......@@ -227,6 +251,14 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
| subscribeInfo | [CommonEventSubscribeInfo](./js-apis-inner-commonEvent-commonEventSubscribeInfo.md) | Yes | Subscriber information. |
| callback | AsyncCallback\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
**Example**
......@@ -258,9 +290,7 @@ try {
## CommonEventManager.createSubscriber
```ts
createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise<CommonEventSubscriber>
```
createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\<CommonEventSubscriber>
Creates a subscriber. This API uses a promise to return the result.
......@@ -277,6 +307,14 @@ Creates a subscriber. This API uses a promise to return the result.
| --------------------------------------------------------- | ---------------- |
| Promise\<[CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md)> | Promise used to return the subscriber object.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
**Example**
```ts
......@@ -299,9 +337,7 @@ CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber)
## CommonEventManager.subscribe
```ts
subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback<CommonEventData>): void
```
subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>): void
Subscribes to common events. This API uses an asynchronous callback to return the result.
......@@ -314,6 +350,17 @@ Subscribes to common events. This API uses an asynchronous callback to return th
| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. |
| callback | AsyncCallback\<[CommonEventData](./js-apis-inner-commonEvent-commonEventData.md)> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 801 | capability not supported. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
**Example**
```ts
......@@ -360,9 +407,7 @@ try {
## CommonEventManager.unsubscribe
```ts
unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback<void>): void
```
unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>): void
Unsubscribes from common events. This API uses an asynchronous callback to return the result.
......@@ -375,6 +420,17 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
| subscriber | [CommonEventSubscriber](./js-apis-inner-commonEvent-commonEventSubscriber.md) | Yes | Subscriber object. |
| callback | AsyncCallback\<void> | No | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 401 | The parameter check failed. |
| 801 | capability not supported. |
| 1500007 | error sending message to Common Event Service. |
| 1500008 | Common Event Service does not complete initialization. |
**Example**
```ts
......@@ -428,3 +484,93 @@ try {
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
}
```
## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
removeStickyCommonEvent(event: string, callback: AsyncCallback\<void>): void
Removes a sticky common event. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.CommonEvent
**Required permissions**: ohos.permission.COMMONEVENT_STICKY
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------------------- |
| event | string | Yes | Sticky common event to remove. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 201 | The application dose not have permission to call the interface. |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not system service. |
| 1500007 | The message send error. |
| 1500008 | The CEMS error. |
**Example**
```ts
CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => {
if (err) {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
return;
}
console.info(`Remove sticky event AsyncCallback success`);
}
});
```
## CommonEventManager.removeStickyCommonEvent<sup>10+</sup>
removeStickyCommonEvent(event: string): Promise\<void>
Removes a sticky common event. This API uses a promise to return the result.
**System capability**: SystemCapability.Notification.CommonEvent
**Required permissions**: ohos.permission.COMMONEVENT_STICKY
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------- |
| event | string | Yes | Sticky common event to remove.|
**Return value**
| Type | Description |
| -------------- | ---------------------------- |
| Promise\<void> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md).
| ID| Error Message |
| -------- | ----------------------------------- |
| 201 | The application dose not have permission to call the interface. |
| 202 | not system app. |
| 401 | The parameter check failed. |
| 1500004 | not system service. |
| 1500007 | The message send error. |
| 1500008 | The CEMS error. |
**Example**
```ts
commonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
console.info(`Remove sticky event AsyncCallback success`);
}).catch ((err) => {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
});
```
......@@ -2,6 +2,12 @@
The **AppStateData** module defines the application state data, which can be obtained through [getForegroundApplications](js-apis-app-ability-appManager.md#appmanagergetforegroundapplications).
## Modules to Import
```ts
import appManager from '@ohos.app.ability.appManager';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This module is marked as @systemapi and not visible to third-party applications.
......@@ -19,8 +25,8 @@ import appManager from '@ohos.app.ability.appManager';
function getForegroundAppInfos() {
appManager.getForegroundApplications((error, data) => {
if (error && error.code) {
console.log('getForegroundApplications failed, error.code: ${error.code}, error.message: ${error.message}');
if (error) {
console.log('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
return;
}
for (let i = 0; i < data.length; i++) {
......
......@@ -7,6 +7,12 @@ The **Context** module provides context for abilities or applications. It allows
> - 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 of this module can be used only in the stage model.
## Modules to Import
```ts
import common from '@ohos.app.ability.common';
```
## Attributes
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
......@@ -20,7 +26,7 @@ The **Context** module provides context for abilities or applications. It allows
| filesDir | string | Yes | No | File directory.|
| databaseDir | string | Yes | No | Database directory.|
| preferencesDir | string | Yes | No | Preferences directory.|
| bundleCodeDir | string | Yes | No | Bundle code directory.|
| bundleCodeDir | string | Yes | No | Bundle code directory. Do not access resource files by concatenating paths. Use the [resourceManager API](js-apis-resource-manager.md) instead.|
| distributedFilesDir | string | Yes | No | Distributed file directory.|
| eventHub | [EventHub](js-apis-inner-application-eventHub.md) | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.|
| area | contextConstant.[AreaMode](js-apis-app-ability-contextConstant.md) | Yes | No | Area in which the file to be access is located.|
......@@ -47,18 +53,10 @@ Creates the context based on the bundle name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let bundleContext;
let bundleContext: common.Context;
try {
bundleContext = this.context.createBundleContext('com.example.test');
} catch (error) {
......@@ -86,18 +84,10 @@ Creates the context based on the module name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let moduleContext;
let moduleContext: common.Context;
try {
moduleContext = this.context.createModuleContext('entry');
} catch (error) {
......@@ -126,18 +116,10 @@ Creates the context based on the bundle name and module name.
| -------- | -------- |
| Context | Context created.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
```ts
let moduleContext;
let moduleContext: common.Context;
try {
moduleContext = this.context.createModuleContext('com.example.test', 'entry');
} catch (error) {
......@@ -162,7 +144,7 @@ Obtains the context of this application.
**Example**
```ts
let applicationContext;
let applicationContext: common.Context;
try {
applicationContext = this.context.getApplicationContext();
} catch (error) {
......
......@@ -7,6 +7,12 @@ The **ExtensionRunningInfo** module encapsulates ExtensionAbility running inform
> - 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.
> - This module is marked as @systemapi and not visible to third-party applications.
## Modules to Import
```ts
import abilityManager from '@ohos.app.ability.abilityManager';
```
## Usage
Import the **abilityManager** module and obtain the ExtensionAbility running information by calling the method in the **abilityManager** module.
......@@ -32,8 +38,8 @@ import abilityManager from '@ohos.app.ability.abilityManager';
let upperLimit = 1;
function getExtensionInfos() {
abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => {
if (error && error.code) {
console.error('getForegroundApplications failed, error.code: ${error.code}, error.message: ${error.message}');
if (error) {
console.error('getForegroundApplications failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
return;
}
......
......@@ -2,6 +2,12 @@
The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo).
## Modules to Import
```ts
import missionManager from '@ohos.app.ability.missionManager';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
**System API**: This is a system API and cannot be called by third-party applications.
......@@ -23,7 +29,7 @@ import missionManager from '@ohos.app.ability.missionManager';
try {
missionManager.getMissionInfo('', 1, (error, data) => {
if (error.code) {
if (error) {
// Process service logic errors.
console.error('getMissionInfo failed, error.code: ${error.code}, error.message: ${error.message}');
return;
......
......@@ -7,6 +7,12 @@ The **MissionSnapshot** module defines the snapshot of a mission. The snapshot c
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import
```ts
import missionManager from '@ohos.app.ability.missionManager';
```
**System capability**: SystemCapability.Ability.AbilityRuntime.Mission
| Name| Type| Readable| Writable| Description|
......@@ -26,8 +32,8 @@ The mission snapshot information can be obtained by using **getMissionSnapShot**
try {
missionManager.getMissionInfos('', 10, (error, missions) => {
if (error.code) {
console.error('getMissionInfos failed, error.code: ${error.code}, error.message: ${error.message}');
if (error) {
console.error('getMissionInfos failed, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
return;
}
console.log('size = ${missions.length}');
......@@ -35,8 +41,8 @@ The mission snapshot information can be obtained by using **getMissionSnapShot**
let id = missions[0].missionId;
missionManager.getMissionSnapShot('', id, (err, snapshot) => {
if (err.code) {
console.error('getMissionInfos failed, err.code: ${err.code}, err.message: ${err.message}');
if (err) {
console.error('getMissionInfos failed, err.code: ${JSON.stringify(err.code)}, err.message: ${JSON.stringify(err.message)}');
return;
}
......
......@@ -351,7 +351,7 @@ Enumerates the reasons for the state transition of the **AVPlayer** or **AVRecor
A playback management class that provides APIs to manage and play media assets. Before calling any API in **AVPlayer**, you must use [createAVPlayer()](#mediacreateavplayer9) to create an **AVPlayer** instance.
For details about the AVPlayer demo, see [AVPlayer Development](../../media/avplayer-playback.md).
For details about the audio and video playback demo, see [Audio Playback](../../media/using-avplayer-for-playback.md) and [Video Playback](../../media/video-playback.md).
### Attributes<a name=avplayer_attributes></a>
......@@ -475,9 +475,9 @@ The AVPlayer provides the following error types<a name = error_info></a>:
| 801 | Unsupport Capability: | Unsupported API, causing an invalid call. |
| 5400101 | No Memory: | Insufficient memory. The [AVPlayer state](#avplayerstate9) is error.|
| 5400102 | Operate Not Permit: | Unsupported operation in the current state, causing an invalid call. |
| 5400103 | IO Error: | Abnormal stream. |
| 5400103 | IO Error: | A stream exception is detected during playback. The [AVPlayer state](#avplayerstate9) is error.|
| 5400104 | Network Timeout: | The response times out due to a network error. The [AVPlayer state](#avplayerstate9) is error.|
| 5400105 | Service Died: | The playback process is dead. The [AVPlayer state](#avplayerstate9) is error.|
| 5400105 | Service Died: | The playback process is dead. The [AVPlayer state](#avplayerstate9) is error. In this case, you need to release the instance and then create an instance again.|
| 5400106 | Unsupport Format: | Unsupported file format. The [AVPlayer state](#avplayerstate9) is error.|
**Example**
......@@ -1139,7 +1139,7 @@ Sets the bit rate, which is valid only for HTTP Live Streaming (HLS) streams. Th
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| bitrate | number | Yes | Bit rate to set. You can obtain the available bit rates of the current HLS stream by subscribing to the [availableBitrates](#availableBitrates_on) event. If the bit rate to set is not in the list of the available bit rates, the AVPlayer selects from the list the minimum bit rate that is closed to the bit rate to set.|
| bitrate | number | Yes | Bit rate to set. You can obtain the available bit rates of the current HLS stream by subscribing to the [availableBitrates](#availableBitrates_on) event. If the bit rate to set is not in the list of the available bit rates, the AVPlayer selects from the list the minimum bit rate that is closed to the bit rate to set. If the length of the available bit rate list obtained through the event is 0, no bit rate can be set and the **bitrateDone** callback will not be triggered.|
**Example**
......@@ -1204,7 +1204,7 @@ Subscribes to available bit rates of HLS streams. This event is reported only af
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Event type, which is **'availableBitrates'** in this case. This event is triggered once after the AVPlayer switches to the prepared state.|
| callback | function | Yes | Callback invoked when the event is triggered. It returns an array that holds the available bit rates.|
| callback | function | Yes | Callback invoked when the event is triggered. It returns an array that holds the available bit rates. If the array length is 0, no bit rate can be set.|
**Example**
......@@ -1603,7 +1603,7 @@ avPlayer.off('audioInterrupt')
## AVPlayerState<sup>9+</sup><a name = avplayerstate></a>
Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#stateChange_on) event. For details about the rules for state transition, see [AVPlayer Development](../../media/avplayer-playback.md).
Enumerates the states of the [AVPlayer](#avplayer9). Your application can proactively obtain the AVPlayer state through the **state** attribute or obtain the reported AVPlayer state by subscribing to the [stateChange](#stateChange_on) event. For details about the rules for state transition, see [Audio Playback](../../media/using-avplayer-for-playback.md).
**System capability**: SystemCapability.Multimedia.Media.AVPlayer
......@@ -1710,7 +1710,11 @@ audioPlayer.getTrackDescription((error, arrList) => {
A recording management class that provides APIs to record media assets. Before calling any API in **AVRecorder**, you must use **createAVRecorder()** to create an **AVRecorder** instance.
For details about the AVRecorder demo, see [AVRecorder Development](../../media/avrecorder.md).
For details about the audio and video recording demo, see [Audio Recording](../../media/using-avrecorder-for-recording.md) and [Video Recording](../../media/video-recording.md).
> **NOTE**
>
> To use the camera to record videos, the camera module is required. For details about how to use the APIs provided by the camera module, see [Camera Management](js-apis-camera.md).
### Attributes
......@@ -1763,7 +1767,7 @@ let AVRecorderProfile = {
audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoCodec : media.CodecMimeType.VIDEO_AVC,
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
......@@ -1834,7 +1838,7 @@ let AVRecorderProfile = {
audioSampleRate : 48000,
fileFormat : media.ContainerFormatType.CFT_MPEG_4,
videoBitrate : 2000000,
videoCodec : media.CodecMimeType.VIDEO_MPEG4,
videoCodec : media.CodecMimeType.VIDEO_AVC,
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
......@@ -2536,7 +2540,7 @@ Describes the audio and video recording profile.
| audioSampleRate | number | No | Audio sampling rate. This parameter is mandatory for audio recording. |
| fileFormat | [ContainerFormatType](#containerformattype8) | Yes | Container format of a file. This parameter is mandatory. |
| videoBitrate | number | No | Video encoding bit rate. This parameter is mandatory for video recording. |
| videoCodec | [CodecMimeType](#codecmimetype8) | No | Video encoding format. This parameter is mandatory for video recording. Only **VIDEO_AVC** and **VIDEO_MPEG4** are supported.|
| videoCodec | [CodecMimeType](#codecmimetype8) | No | Video encoding format. This parameter is mandatory for video recording. You need to query the encoding capabilities (including the encoding format and resolution) supported by the device.|
| videoFrameWidth | number | No | Width of a video frame. This parameter is mandatory for video recording. |
| videoFrameHeight | number | No | Height of a video frame. This parameter is mandatory for video recording. |
| videoFrameRate | number | No | Video frame rate. This parameter is mandatory for video recording. |
......@@ -2593,8 +2597,6 @@ Describes the geographical location of the recorded video.
Implements video recording. Before calling any API in the **VideoRecorder** class, you must use [createVideoRecorder()](#mediacreatevideorecorder9) to create a [VideoRecorder](#videorecorder9) instance.
For details about the video recording demo, see [Video Recording Development](../../media/video-recorder.md).
### Attributes
**System capability**: SystemCapability.Multimedia.Media.VideoRecorder
......@@ -2646,7 +2648,7 @@ let videoProfile = {
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 2000000,
videoCodec : 'video/mp4v-es',
videoCodec : 'video/avc',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
......@@ -2717,7 +2719,7 @@ let videoProfile = {
audioSampleRate : 48000,
fileFormat : 'mp4',
videoBitrate : 2000000,
videoCodec : 'video/mp4v-es',
videoCodec : 'video/avc',
videoFrameWidth : 640,
videoFrameHeight : 480,
videoFrameRate : 30
......@@ -3795,7 +3797,7 @@ Subscribes to the audio playback events.
**Example**
```js
import fileio from '@ohos.fileio'
import fs from '@ohos.file.fs';
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
......@@ -3839,15 +3841,15 @@ audioPlayer.on('error', (error) => { // Set the 'error' event callback
let fdPath = 'fd://';
// The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command.
let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3';
fileio.open(path).then((fdValue) => {
fdPath = fdPath + '' + fdValue;
fs.open(path).then((file) => {
fdPath = fdPath + '' + file.fd;
console.info('open fd success fd is' + fdPath);
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
}, (err) => {
console.info('open fd failed err is' + err);
}).catch((err) => {
console.info('open fd failed err is' + err);
});
audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
```
### on('timeUpdate')
......@@ -3928,8 +3930,6 @@ Enumerates the audio playback states. You can obtain the state through the **sta
Provides APIs to manage and play video. Before calling any API of **VideoPlayer**, you must use [createVideoPlayer()](#createvideoplayer) to create a **VideoPlayer** instance.
For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md).
### Attributes<a name=videoplayer_attributes></a>
**System capability**: SystemCapability.Multimedia.Media.VideoPlayer
......@@ -4750,8 +4750,6 @@ Enumerates the video playback states. You can obtain the state through the **sta
Implements audio recording. Before calling any API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorder) to create an **AudioRecorder** instance.
For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md).
### prepare<a name=audiorecorder_prepare></a>
prepare(config: AudioRecorderConfig): void
......
......@@ -16,10 +16,11 @@ import request from '@ohos.request';
## Constraints
The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')<sup>7+</sup>](#onfail7).
Only HTTP requests are supported. HTTPS requests are not supported.
The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')<sup>7+</sup>](#onfail7).
## Constants
**Required permissions**: ohos.permission.INTERNET
......@@ -79,7 +80,7 @@ The table below lists the download task status codes that may be returned by [ge
uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
Uploads files. This API uses a promise to return the result. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information.
**Required permissions**: ohos.permission.INTERNET
......@@ -87,24 +88,24 @@ Uploads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
**Example**
......@@ -133,7 +134,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
Uploads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'fail')<sup>9+</sup>](#oncomplete--fail9) to obtain the upload error information.
**Required permissions**: ohos.permission.INTERNET
......@@ -141,18 +142,18 @@ Uploads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
**Example**
......@@ -196,15 +197,15 @@ Uploads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example**
......@@ -243,10 +244,10 @@ Uploads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Example**
......@@ -286,10 +287,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).|
| callback | function | Yes| Callback for the upload progress event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).|
| callback | function | Yes| Callback for the upload progress event.|
Parameters of the callback function
......@@ -320,10 +321,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).|
| callback | function | Yes| Callback for the HTTP Response Header event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).|
| callback | function | Yes| Callback for the HTTP Response Header event.|
Parameters of the callback function
......@@ -353,10 +354,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | Yes| Callback used to return the result.|
Parameters of the callback function
......@@ -395,10 +396,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).|
| callback | function | No| Callback for the upload progress event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).|
| callback | function | No| Callback for the upload progress event.|
Parameters of the callback function
......@@ -429,10 +430,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).|
| callback | function | No| Callback for the HTTP Response Header event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).|
| callback | function | No| Callback for the HTTP Response Header event.|
Parameters of the callback function
......@@ -461,10 +462,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | No| Callback used to return the result.|
Parameters of the callback function
......@@ -501,9 +502,9 @@ Deletes this upload task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
**Example**
......@@ -532,9 +533,9 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -569,9 +570,9 @@ Removes this upload task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
**Example**
......@@ -604,9 +605,9 @@ Removes this upload task. This API uses an asynchronous callback to return the r
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -625,6 +626,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r
```
## UploadConfig
Describes the configuration for an upload task.
**Required permissions**: ohos.permission.INTERNET
......@@ -639,6 +641,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r
| data | Array&lt;[RequestData](#requestdata)&gt; | Yes| Form data in the request body.|
## TaskState<sup>9+</sup>
Implements a **TaskState** object, which is the callback parameter of the [on('complete' | 'fail')<sup>9+</sup>](#oncomplete--fail9) and [off('complete' | 'fail')<sup>9+</sup>](#offcomplete--fail9) APIs.
**Required permissions**: ohos.permission.INTERNET
......@@ -651,6 +654,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r
| message | string | Yes| Description of the upload task result.|
## File
Describes the list of files in [UploadConfig](#uploadconfig).
**Required permissions**: ohos.permission.INTERNET
......@@ -665,6 +669,7 @@ Removes this upload task. This API uses an asynchronous callback to return the r
## RequestData
Describes the form data in [UploadConfig](#uploadconfig).
**Required permissions**: ohos.permission.INTERNET
......@@ -679,7 +684,8 @@ Removes this upload task. This API uses an asynchronous callback to return the r
downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
Downloads files. This API uses a promise to return the result. You can use [on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')<sup>7+</sup>](#onfail7) to obtain the task download error information.
**Required permissions**: ohos.permission.INTERNET
......@@ -687,25 +693,25 @@ Downloads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
**Example**
......@@ -727,7 +733,8 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
Downloads files. This API uses an asynchronous callback to return the result.
Downloads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'pause'|'remove')<sup>7+</sup>](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')<sup>7+</sup>](#onfail7) to obtain the task download error information.
**Required permissions**: ohos.permission.INTERNET
......@@ -735,20 +742,20 @@ Downloads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
**Example**
......@@ -786,15 +793,15 @@ Downloads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Example**
......@@ -826,10 +833,10 @@ Downloads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -862,10 +869,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).|
| callback | function | Yes| Callback for the download progress event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).|
| callback | function | Yes| Callback for the download progress event.|
Parameters of the callback function
......@@ -896,10 +903,10 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).|
| callback | function | No| Callback for the download progress event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).|
| callback | function | No| Callback for the download progress event.|
Parameters of the callback function
......@@ -930,10 +937,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | Yes| Callback used to return the result.|
**Example**
......@@ -957,10 +964,10 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | No| Callback used to return the result.|
**Example**
......@@ -984,10 +991,10 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).|
| callback | function | Yes| Callback for the download task failure event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).|
| callback | function | Yes| Callback for the download task failure event.|
Parameters of the callback function
......@@ -1017,10 +1024,10 @@ Unsubscribes from the download task failure event. This API uses an asynchronous
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).|
| callback | function | No| Callback for the download task failure event.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).|
| callback | function | No| Callback for the download task failure event.|
Parameters of the callback function
......@@ -1049,9 +1056,9 @@ Removes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
**Example**
......@@ -1080,9 +1087,9 @@ Deletes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task deletion result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task deletion result.|
**Example**
......@@ -1113,9 +1120,9 @@ Obtains the information about this download task. This API uses a promise to ret
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
**Example**
......@@ -1140,9 +1147,9 @@ Obtains the information about this download task. This API uses an asynchronous
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
**Example**
......@@ -1169,9 +1176,9 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
**Example**
......@@ -1196,9 +1203,9 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
**Example**
......@@ -1225,9 +1232,9 @@ Pauses this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the download task pause result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the download task pause result.|
**Example**
......@@ -1256,9 +1263,9 @@ Pauses this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -1289,9 +1296,9 @@ Resumes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
......@@ -1321,9 +1328,9 @@ Resumes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -1359,9 +1366,9 @@ Removes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
**Example**
......@@ -1394,9 +1401,9 @@ Removes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result.|
**Example**
......@@ -1431,9 +1438,9 @@ Queries this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
**Example**
......@@ -1462,9 +1469,9 @@ Queries this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
**Example**
......@@ -1495,9 +1502,9 @@ Queries the **MimeType** of this download task. This API uses a promise to retur
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
**Example**
......@@ -1526,9 +1533,9 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
**Example**
......@@ -1559,9 +1566,9 @@ Pauses this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the download task pause result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the download task pause result.|
**Example**
......@@ -1594,9 +1601,9 @@ Pauses this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -1631,9 +1638,9 @@ Resumes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
......@@ -1667,9 +1674,9 @@ Resumes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
......@@ -1689,6 +1696,7 @@ Resumes this download task. This API uses an asynchronous callback to return the
## DownloadConfig
Defines the download task configuration.
**Required permissions**: ohos.permission.INTERNET
......@@ -1698,16 +1706,17 @@ Resumes this download task. This API uses an asynchronous callback to return the
| -------- | -------- | -------- | -------- |
| url | string | Yes| Resource URL.|
| header | Object | No| HTTPS flag header to be included in the download request.<br>The **X-TLS-Version** parameter in **header** specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:<br>CURL_SSLVERSION_TLSv1_0<br>CURL_SSLVERSION_TLSv1_1<br>CURL_SSLVERSION_TLSv1_2<br>CURL_SSLVERSION_TLSv1_3<br>The **X-Cipher-List** parameter in **header** specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:<br>- The TLS 1.2 cipher suite list includes the following ciphers:<br>TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,<br>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,<br>TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,<br>TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,<br>TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,<br>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,<br>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,<br>TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,<br>TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,<br>TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,<br>TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,<br>TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,<br>TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256<br>- The TLS 1.3 cipher suite list includes the following ciphers:<br>TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256<br>- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:<br>TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 |
| enableMetered | boolean | No| Whether download is allowed on a metered connection.<br>- **true**: allowed<br>- **false**: not allowed |
| enableRoaming | boolean | No| Whether download is allowed on a roaming network.<br>- **true**: allowed<br>- **false**: not allowed |
| enableMetered | boolean | No| Whether download is allowed on a metered connection.<br>- **true**: allowed<br>- **false**: not allowed|
| enableRoaming | boolean | No| Whether download is allowed on a roaming network.<br>- **true**: allowed<br>- **false**: not allowed|
| description | string | No| Description of the download session.|
| filePath<sup>7+</sup> | string | No| Path where the downloaded file is stored.<br>- filePath:'/data/storage/el2/base/haps/entry/files/test.txt': Save the file to an absolute path.<br>- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **'${featureAbility.getContext().getFilesDir()}/test.txt'**, and store the file in this directory.<br>- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the fie path, for example, **'${globalThis.abilityContext.tempDir}/test.txt'**, and store the file in this path.|
| filePath<sup>7+</sup> | string | No| Path where the downloaded file is stored.<br>- filePath:'/data/storage/el2/base/haps/entry/files/test.txt': Save the file to an absolute path.<br>- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.<br>- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.|
| networkType | number | No| Network type allowed for download.<br>- NETWORK_MOBILE: 0x00000001<br>- NETWORK_WIFI: 0x00010000|
| title | string | No| Download task name.|
| background<sup>9+</sup> | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.|
## DownloadInfo<sup>7+</sup>
Defines the download task information, which is the callback parameter of the [query<sup>(deprecated)</sup>](#querydeprecated-1) API.
**Required permissions**: ohos.permission.INTERNET
......@@ -1726,3 +1735,4 @@ Resumes this download task. This API uses an asynchronous callback to return the
| downloadTotalBytes | number | Yes| Total size of the files to download, in bytes.|
| description | string | Yes| Description of the file to download.|
| downloadedBytes | number | Yes| Size of the files downloaded, in bytes.|
<!--no_check-->
\ No newline at end of file
......@@ -144,7 +144,7 @@ Describes the injected simulated mouse button.
## On<sup>9+</sup>
Since API version 9, the UiTest framework provides a wide range of UI component feature description APIs in the **On** class to filter and match components.
The API capabilities provided by the **On** class exhibit the following features: 1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. <br>2. Provide multiple match patterns for component attributes. <br>3. Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore) and [ON.isAfter](#isafter) can be used to specify the features of adjacent components to assist positioning. <br>All APIs provided in the **On** class are synchronous. You are advised to use the static constructor **ON** to create an **On** object in chain mode.
The API capabilities provided by the **On** class exhibit the following features: 1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component. <br>2. Provide multiple match patterns for component attributes. <br>3. Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore9) and [ON.isAfter](#isafter9) can be used to specify the features of adjacent components to assist positioning. <br>All APIs provided in the **On** class are synchronous. You are advised to use the static constructor **ON** to create an **On** object in chain mode.
```js
ON.text('123').type('button');
......@@ -542,7 +542,7 @@ Specifies that the target component is within the given application window.
**Example**
```js
let on = ON.inWindow(ON.inWindow('com.uitestScene.acts')); // Create an On object using the static constructor ON, specifying that the target component is within the given application window.
let on = ON.inWindow('com.uitestScene.acts'); // Create an On object using the static constructor ON, specifying that the target component is within the given application window.
```
## Component<sup>9+</sup>
......@@ -1553,7 +1553,7 @@ Searches this **Driver** object for the target component that matches the given
| Type | Description |
| --------------------------------- | --------------------------------- |
| Promise\<[Component](#component)> | Promise used to return the found component.|
| Promise\<[Component](#component9)> | Promise used to return the found component.|
**Error codes**
......
......@@ -234,7 +234,7 @@ Sends a message. For the complete sample code, see [onMessageEventExt](#onmessag
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | :------------- |
| message | [WebMessageExt](#webmessageext) | Yes | Message to send.|
| message | [WebMessageExt](#webmessageext10) | Yes | Message to send.|
**Error codes**
......@@ -491,7 +491,7 @@ Sets how the \<Web> component uses HTTPDNS for DNS resolution.
| Name | Type | Mandatory | Description|
| ------------------ | ------- | ---- | ------------- |
| secureDnsMode | [SecureDnsMode](#securednsmode) | Yes | Mode in which HTTPDNS is used.|
| secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.|
| secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.|
**Example**
......@@ -504,7 +504,6 @@ import web_webview from '@ohos.web.webview';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
console.log("EntryAbility onCreate")
web_webview.WebviewController.initializeWebEngine()
try {
web_webview.WebviewController.setHttpDns(web_webview.SecureDnsMode.Auto, "https://example1.test")
} catch(error) {
......@@ -1420,7 +1419,7 @@ Executes a JavaScript script. This API uses a promise to return the script execu
| Type | Description |
| --------------- | --------------------------------------------------- |
| Promise\<string> | Promise used to return the result. Returns **null** if the JavaScript script fails to be executed|
| Promise\<string> | Promise used to return the result if the operation is successful and null otherwise.|
**Error codes**
......@@ -2637,7 +2636,7 @@ Stores this web page. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------------------------------------------ |
| baseName | string | Yes | Save path. The value cannot be null. |
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise. |
**Error codes**
......@@ -2662,7 +2661,7 @@ struct WebComponent {
build() {
Column() {
Button('saveWebArchive')
Button('storeWebArchive')
.onClick(() => {
try {
this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => {
......@@ -2697,7 +2696,7 @@ Stores this web page. This API uses a promise to return the result.
| Name | Type| Mandatory| Description |
| -------- | -------- | ---- | ------------------------------------------------------------ |
| baseName | string | Yes | Save path. The value cannot be null. |
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
**Return value**
......@@ -2727,7 +2726,7 @@ struct WebComponent {
build() {
Column() {
Button('saveWebArchive')
Button('storeWebArchive')
.onClick(() => {
try {
this.controller.storeWebArchive("/data/storage/el2/base/", true)
......@@ -2848,6 +2847,8 @@ backOrForward(step: number): void
Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack.
Because the previously loaded web pages are used for the operation, no page reloading is involved.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
......@@ -3586,10 +3587,11 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
**Example**
1. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
@Entry
@Component
......@@ -3602,11 +3604,13 @@ struct WebComponent {
.onClick(() => {
try {
let state = this.controller.serializeWebState();
let path = globalThis.AbilityContext.cacheDir;
// Obtain the value of globalThis.cacheDir from MainAbility.ts.
let path = globalThis.cacheDir;
path += '/WebState';
let fd = fileio.openSync(path, 0o2 | 0o100, 0o666);
fileio.writeSync(fd, state.buffer);
fileio.closeSync(fd);
// Synchronously open a file.
let file = fs.openSync(path, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
fs.writeSync(file.fd, state.buffer);
fs.closeSync(file.fd);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
......@@ -3617,6 +3621,21 @@ struct WebComponent {
}
```
2. Modify **MainAbility.ts**.
Obtain the path of the application cache file.
```ts
// xxx.ts
import UIAbility from '@ohos.app.ability.UIAbility';
import web_webview from '@ohos.web.webview';
export default class MainAbility extends UIAbility {
onCreate(want, launchParam) {
// Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page.
globalThis.cacheDir = this.context.cacheDir;
}
}
```
### restoreWebState
restoreWebState(state: Uint8Array): void
......@@ -3641,10 +3660,11 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
**Example**
1. To perform operations on files, you must import the file management module. For details, see [File Management](./js-apis-file-fs.md).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
import fileio from '@ohos.fileio';
import fs from '@ohos.file.fs';
@Entry
@Component
......@@ -3656,17 +3676,22 @@ struct WebComponent {
Button('RestoreWebState')
.onClick(() => {
try {
let path = globalThis.AbilityContext.cacheDir;
// Obtain the value of globalThis.cacheDir from MainAbility.ts.
let path = globalThis.cacheDir;
path += '/WebState';
let fd = fileio.openSync(path, 0o002, 0o666);
let stat = fileio.fstatSync(fd);
// Synchronously open a file.
let file = fs.openSync(path, fs.OpenMode.READ_WRITE);
let stat = fs.statSync(path);
let size = stat.size;
let buf = new ArrayBuffer(size);
fileio.read(fd, buf, (err, data) => {
if (data) {
this.controller.restoreWebState(new Uint8Array(data.buffer));
fs.read(file.fd, buf, (err, readLen) => {
if (err) {
console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("read file data succeed");
this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen)));
fs.closeSync(file);
}
fileio.closeSync(fd);
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
......@@ -3678,6 +3703,21 @@ struct WebComponent {
}
```
2. Modify **MainAbility.ts**.
Obtain the path of the application cache file.
```ts
// xxx.ts
import UIAbility from '@ohos.app.ability.UIAbility';
import web_webview from '@ohos.web.webview';
export default class MainAbility extends UIAbility {
onCreate(want, launchParam) {
// Bind cacheDir to the globalThis object to implement data synchronization between the UIAbility component and the page.
globalThis.cacheDir = this.context.cacheDir;
}
}
```
### customizeSchemes
static customizeSchemes(schemes: Array\<WebCustomScheme\>): void
......
......@@ -54,7 +54,7 @@ Defines the parameters for creating a subwindow or system window.
| ---------- | -------------------------- | -- | ----------------------------------- |
| name | string | Yes| Name of the window. |
| windowType | [WindowType](#windowtype7) | Yes| Type of the window. |
| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | No| Current application context. If this parameter is not set, no context is used.<br>You do not need to set this parameter to create a subwindow in the FA model or a system window in the stage model. |
| ctx | [BaseContext](js-apis-inner-application-baseContext.md) | No| Current application context. If this parameter is not set, no context is used.<br>You do not need to set this parameter to create a subwindow in the FA model<br>or a system window in the stage model.|
| displayId | number | No| ID of the current physical screen. If this parameter is not set, the default value **-1** is used.|
| parentId | number | No| ID of the parent window. If this parameter is not set, the default value **-1** is used. |
......@@ -66,7 +66,7 @@ Enumerates the types of the area where the window cannot be displayed.
| Name | Value | Description |
| -------------------------------- | ---- | ------------------------------------------------------------ |
| TYPE_SYSTEM | 0 | Default area of the system. Generally, the status bar, navigation bar, and Dock bar are included. The default area may vary according to the device in use.|
| TYPE_SYSTEM | 0 | Default area of the system. Generally, the status bar and navigation bar are included. The default area may vary according to the device in use.|
| TYPE_CUTOUT | 1 | Notch. |
| TYPE_SYSTEM_GESTURE<sup>9+</sup> | 2 | Gesture area. |
| TYPE_KEYBOARD<sup>9+</sup> | 3 | Soft keyboard area. |
......@@ -108,10 +108,10 @@ Describes the properties of the status bar and navigation bar.
| Name | Type| Mandatory| Description |
| -------------------------------------- | -------- | ---- | ------------------------------------------------------------ |
| statusBarColor | string | No | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.|
| statusBarColor | string | No | Background color of the status bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.|
| isStatusBarLightIcon<sup>7+</sup> | boolean | No | Whether any icon on the status bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.|
| statusBarContentColor<sup>8+</sup> | string | No | Color of the text on the status bar. After this property is set, the setting of **isStatusBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.|
| navigationBarColor | string | No | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.|
| navigationBarColor | string | No | Background color of the navigation bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.|
| isNavigationBarLightIcon<sup>7+</sup> | boolean | No | Whether any icon on the navigation bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.|
| navigationBarContentColor<sup>8+</sup> | string | No | Color of the text on the navigation bar. After this property is set, the setting of **isNavigationBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.|
......@@ -164,7 +164,7 @@ Describes the callback for a single system bar.
| type | [WindowType](#windowtype7) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.|
| isEnable | boolean | Yes | No | Whether the system bar is displayed. The value **true** means that the system bar is displayed, and **false** means the opposite.|
| region | [Rect](#rect7) | Yes | No | Current position and size of the system bar. |
| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.|
| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.|
| contentColor | string | Yes | No | Color of the text on the system bar. |
## SystemBarTintState<sup>8+</sup>
......@@ -300,8 +300,6 @@ Describes the translation parameters.
Enumerates the window lifecycle states.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
| Name | Value| Description |
......@@ -832,6 +830,148 @@ try {
}
```
## window.on('gestureNavigationEnabledChange')<sup>10+</sup>
on(type: 'gestureNavigationEnabledChange', callback: Callback&lt;boolean&gt;): void
Enables listening for gesture navigation status changes.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ----------------------------------------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event. |
| callback | Callback&lt;boolean&gt; | Yes | Callback used to return the gesture navigation status. The value **true** means that the gesture navigation status is changed to enabled, and **false** means that the gesture navigation status is changed to disabled.|
**Example**
```js
try {
window.on('gestureNavigationEnabledChange', (data) => {
console.info('Succeeded in enabling the listener for gesture navigation status changes. Data: ' + JSON.stringify(data));
});
} catch (exception) {
console.error('Failed to enable the listener for gesture navigation status changes. Cause: ' + JSON.stringify(exception));
}
```
## window.off('gestureNavigationEnabledChange')<sup>10+</sup>
off(type: 'gestureNavigationEnabledChange', callback?: Callback&lt;boolean&gt;): void
Disables the listening for gesture navigation status changes.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | -- | ------------------------------------------------------------ |
| type | string | Yes| Event type. The value is fixed at **'gestureNavigationEnabledChange'**, indicating the gesture navigation status change event.|
| callback | Callback&lt;boolean&gt; | No| Callback function that has been used for registering the listener. If this parameter is passed in, only the listener registered using this callback function is removed; otherwise, all gesture navigation status change listeners are removed.|
**Example**
```js
try {
window.off('gestureNavigationEnabledChange');
} catch (exception) {
console.error('Failed to disable the listener for gesture navigation status changes. Cause: ' + JSON.stringify(exception));
}
```
## window.setGestureNavigationEnabled<sup>10+</sup>
setGestureNavigationEnabled(enable: boolean, callback: AsyncCallback&lt;void&gt;): void
Enables or disables gesture navigation. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | -------------- |
| enable | boolean | Yes | Whether to enable gesture navigation. The value **true** means to enable gesture navigation, and **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md).
| ID| Error Message|
| ------- | --------------------------------------------- |
| 1300002 | This window state is abnormal. |
| 1300003 | This window manager service works abnormally. |
**Example**
```js
try {
window.setGestureNavigationEnabled(true, (err) => {
if(err.code) {
console.error('Failed to set gesture navigation enabled. Cause: ' + JSON.stringify(err));
return;
}
console.info('Succeeded in setting gesture navigation enabled.');
});
} catch (exception) {
console.error('Failed to set gesture navigation enabled. Cause: ' + JSON.stringify(exception));
}
```
## window.setGestureNavigationEnabled<sup>10+</sup>
setGestureNavigationEnabled(enable: boolean): Promise&lt;void&gt;
Enables or disables gesture navigation. This API uses a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------- |
| enable | boolean | Yes | Whether to enable gesture navigation. The value **true** means to enable gesture navigation, and **false** means the opposite.|
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md).
| ID| Error Message|
| ------- | -------------------------------------------- |
| 1300002 | This window state is abnormal. |
| 1300003 | This window manager service works abnormally. |
**Example**
```js
try {
let promise = window.setGestureNavigationEnabled(true);
promise.then(()=> {
console.info('Succeeded in setting gesture navigation enabled.');
}).catch((err)=>{
console.error('Failed to set gesture navigation enabled. Cause: ' + JSON.stringify(err));
});
} catch (exception) {
console.error('Failed to set gesture navigation enabled. Cause: ' + JSON.stringify(exception));
}
```
## window.create<sup>(deprecated)</sup>
create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void
......@@ -1910,7 +2050,9 @@ try {
setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void
Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result.
Sets whether the window layout is immersive. This API uses an asynchronous callback to return the result.
An immersive layout means that the layout does not avoid the status bar and navigation bar, and components may overlap with them.
A non-immersive layout means that the layout avoids the status bar and navigation bar, and components do not overlap with them.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -1918,7 +2060,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
| Name| Type| Mandatory| Description|
| ------------------ | ------------------------- | -- | --------- |
| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.|
| isLayoutFullScreen | boolean | Yes| Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window layout is immersive, and **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Error codes**
......@@ -1951,7 +2093,9 @@ try {
setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise&lt;void&gt;
Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result.
Sets whether the window layout is immersive. This API uses a promise to return the result.
An immersive layout means that the layout does not avoid the status bar and navigation bar, and components may overlap with them.
A non-immersive layout means that the layout avoids the status bar and navigation bar, and components do not overlap with them.
**System capability**: SystemCapability.WindowManager.WindowManager.Core
......@@ -1959,7 +2103,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
| Name| Type| Mandatory| Description|
| ------------------ | ------- | -- | ------------------------------------------------------------------------------------------------ |
| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.|
| isLayoutFullScreen | boolean | Yes| Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window layout is immersive, and **false** means the opposite.|
**Return value**
......@@ -2361,7 +2505,7 @@ Loads content from a page associated with a local storage to this window. This A
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the page from which the content will be loaded. |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.|
| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Error codes**
......@@ -2407,7 +2551,7 @@ Loads content from a page associated with a local storage to this window. This A
| Name | Type | Mandatory| Description |
| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the page from which the content will be loaded. |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.|
| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.|
**Return value**
......@@ -3335,7 +3479,7 @@ Sets the background color for this window. In the stage model, this API must be
| Name| Type| Mandatory| Description|
| ----- | ------ | -- | ----------------------------------------------------------------------- |
| color | string | Yes| Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.|
| color | string | Yes| Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.|
**Error codes**
......@@ -4019,7 +4163,7 @@ promise.then((pixelMap)=> {
opacity(opacity: number): void
Sets the opacity for this window.
Sets the opacity for this window. This API can be used only when you [customize an animation to be played during the display or hiding of a system window](../../windowmanager/system-window-stage.md#customizing-an-animation-to-be-played-during-the-display-or-hiding-of-a-system-window).
**System API**: This is a system API.
......@@ -4028,8 +4172,8 @@ Sets the opacity for this window.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | --------- | ------------------------------------------------- |
| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. |
| ------- | ------ | --------- | ------------------------------------------------------------ |
| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. The value **0.0** means completely transparent, and **1.0** means completely opaque. |
**Error codes**
......@@ -4054,7 +4198,7 @@ try {
scale(scaleOptions: ScaleOptions): void
Sets the scale parameters for this window.
Sets the scale parameters for this window. This API can be used only when you [customize an animation to be played during the display or hiding of a system window](../../windowmanager/system-window-stage.md#customizing-an-animation-to-be-played-during-the-display-or-hiding-of-a-system-window).
**System API**: This is a system API.
......@@ -4095,7 +4239,7 @@ try {
rotate(rotateOptions: RotateOptions): void
Sets the rotation parameters for this window.
Sets the rotation parameters for this window. This API can be used only when you [customize an animation to be played during the display or hiding of a system window](../../windowmanager/system-window-stage.md#customizing-an-animation-to-be-played-during-the-display-or-hiding-of-a-system-window).
**System API**: This is a system API.
......@@ -4137,7 +4281,7 @@ try {
translate(translateOptions: TranslateOptions): void
Sets the translation parameters for this window.
Sets the translation parameters for this window. This API can be used only when you [customize an animation to be played during the display or hiding of a system window](../../windowmanager/system-window-stage.md#customizing-an-animation-to-be-played-during-the-display-or-hiding-of-a-system-window).
**System API**: This is a system API.
......@@ -4146,8 +4290,8 @@ Sets the translation parameters for this window.
**Parameters**
| Name | Type | Mandatory | Description |
| ---------------- | -------------------------------------- | --------- | ------------------------------ |
| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set. |
| ---------------- | -------------------------------------- | --------- | ------------------------------------------- |
| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters. The unit is pixels. |
**Error codes**
......@@ -4303,7 +4447,6 @@ try {
} catch (exception) {
console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception));
}
```
### setBackdropBlurStyle<sup>9+</sup>
......@@ -4339,7 +4482,6 @@ try {
} catch (exception) {
console.error('Failed to set backdrop blur style. Cause: ' + JSON.stringify(exception));
}
```
### setShadow<sup>9+</sup>
......@@ -4357,7 +4499,7 @@ Sets the shadow for the window borders.
| Name | Type | Mandatory | Description |
| ------- | ------ | --------- | ------------------------------------------------------------ |
| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders. |
| color | string | No | Color of the shadow. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
| color | string | No | Color of the shadow. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. |
| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. |
......@@ -4378,7 +4520,6 @@ try {
} catch (exception) {
console.error('Failed to set shadow. Cause: ' + JSON.stringify(exception));
}
```
### setCornerRadius<sup>9+</sup>
......@@ -4414,7 +4555,6 @@ try {
} catch (exception) {
console.error('Failed to set corner radius. Cause: ' + JSON.stringify(exception));
}
```
### raiseToAppTop<sup>10+</sup>
......@@ -4454,7 +4594,6 @@ windowClass.raiseToAppTop((err) => {
}
console.info('Succeeded in raising the window to app top.');
});
```
### raiseToAppTop<sup>10+</sup>
......@@ -4493,9 +4632,7 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to raise the window to app top. Cause: ' + JSON.stringify(err));
});
```
### setAspectRatio<sup>10+</sup>
setAspectRatio(ratio: number): Promise&lt;void&gt;
......@@ -4541,7 +4678,6 @@ try {
} catch (exception) {
console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception));
}
```
### setAspectRatio<sup>10+</sup>
......@@ -4585,7 +4721,6 @@ try {
} catch (exception) {
console.error('Failed to set the aspect ratio of window. Cause: ' + JSON.stringify(exception));
}
```
### resetAspectRatio<sup>10+</sup>
......@@ -4626,7 +4761,6 @@ try {
} catch (exception) {
console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception));
}
```
### resetAspectRatio<sup>10+</sup>
......@@ -4668,7 +4802,6 @@ try {
} catch (exception) {
console.error('Failed to reset the aspect ratio of window. Cause: ' + JSON.stringify(exception));
}
```
### setWaterMarkFlag<sup>10+</sup>
......@@ -4717,7 +4850,6 @@ try {
} catch (exception) {
console.error('Failed to set water mark flag of window. Cause: ' + JSON.stringify(exception));
}
```
### setWaterMarkFlag<sup>10+</sup>
......@@ -4762,7 +4894,6 @@ try {
} catch (exception) {
console.error('Failed to set water mark flag of window. Cause: ' + JSON.stringify(exception));
}
```
### show<sup>(deprecated)</sup>
......@@ -4793,7 +4924,6 @@ windowClass.show((err) => {
}
console.info('Succeeded in showing the window.');
});
```
### show<sup>(deprecated)</sup>
......@@ -4823,7 +4953,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to show the window. Cause: ' + JSON.stringify(err));
});
```
### destroy<sup>(deprecated)</sup>
......@@ -4854,7 +4983,6 @@ windowClass.destroy((err) => {
}
console.info('Succeeded in destroying the window.');
});
```
### destroy<sup>(deprecated)</sup>
......@@ -4884,7 +5012,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err));
});
```
### moveTo<sup>(deprecated)</sup>
......@@ -4919,7 +5046,6 @@ windowClass.moveTo(300, 300, (err)=>{
}
console.info('Succeeded in moving the window.');
});
```
### moveTo<sup>(deprecated)</sup>
......@@ -4958,7 +5084,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to move the window. Cause: ' + JSON.stringify(err));
});
```
### resetSize<sup>(deprecated)</sup>
......@@ -4999,7 +5124,6 @@ windowClass.resetSize(500, 1000, (err) => {
}
console.info('Succeeded in changing the window size.');
});
```
### resetSize<sup>(deprecated)</sup>
......@@ -5044,7 +5168,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to change the window size. Cause: ' + JSON.stringify(err));
});
```
### setWindowType<sup>(deprecated)</sup>
......@@ -5079,7 +5202,6 @@ windowClass.setWindowType(type, (err) => {
}
console.info('Succeeded in setting the window type.');
});
```
### setWindowType<sup>(deprecated)</sup>
......@@ -5118,7 +5240,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the window type. Cause: ' + JSON.stringify(err));
});
```
### getProperties<sup>(deprecated)</sup>
......@@ -5149,7 +5270,6 @@ windowClass.getProperties((err, data) => {
}
console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data));
});
```
### getProperties<sup>(deprecated)</sup>
......@@ -5179,7 +5299,6 @@ promise.then((data)=> {
}).catch((err)=>{
console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err));
});
```
### getAvoidArea<sup>(deprecated)</sup>
......@@ -5212,7 +5331,6 @@ windowClass.getAvoidArea(type, (err, data) => {
}
console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data));
});
```
### getAvoidArea<sup>(deprecated)</sup>
......@@ -5249,7 +5367,6 @@ promise.then((data)=> {
}).catch((err)=>{
console.error('Failed to obtain the area. Cause:' + JSON.stringify(err));
});
```
### setFullScreen<sup>(deprecated)</sup>
......@@ -5282,7 +5399,6 @@ windowClass.setFullScreen(isFullScreen, (err) => {
}
console.info('Succeeded in enabling the full-screen mode.');
});
```
### setFullScreen<sup>(deprecated)</sup>
......@@ -5319,14 +5435,15 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err));
});
```
### setLayoutFullScreen<sup>(deprecated)</sup>
setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback&lt;void&gt;): void
Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result.
Sets whether the window layout is immersive. This API uses an asynchronous callback to return the result.
An immersive layout means that the layout does not avoid the status bar and navigation bar, and components may overlap with them.
A non-immersive layout means that the layout avoids the status bar and navigation bar, and components do not overlap with them.
> **NOTE**
>
......@@ -5338,7 +5455,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
| Name | Type | Mandatory | Description |
| ------------------ | ------------------------- | --------- | ------------------------------------------------------------ |
| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. |
| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window is immersive, and **false** means the opposite. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
......@@ -5352,14 +5469,15 @@ windowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => {
}
console.info('Succeeded in setting the window layout to full-screen mode.');
});
```
### setLayoutFullScreen<sup>(deprecated)</sup>
setLayoutFullScreen(isLayoutFullScreen: boolean): Promise&lt;void&gt;
Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result.
Sets whether the window layout is immersive. This API uses a promise to return the result.
An immersive layout means that the layout does not avoid the status bar and navigation bar, and components may overlap with them.
A non-immersive layout means that the layout avoids the status bar and navigation bar, and components do not overlap with them.
> **NOTE**
>
......@@ -5371,7 +5489,7 @@ Sets whether to enable the full-screen mode for the window layout. This API uses
| Name | Type | Mandatory | Description |
| ------------------ | ------- | --------- | ------------------------------------------------------------ |
| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. |
| isLayoutFullScreen | boolean | Yes | Whether the window layout is immersive. (The status bar and navigation bar of the immersive layout are still displayed.) The value **true** means that the window is immersive, and **false** means the opposite. |
**Return value**
......@@ -5389,7 +5507,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err));
});
```
### setSystemBarEnable<sup>(deprecated)</sup>
......@@ -5423,7 +5540,6 @@ windowClass.setSystemBarEnable(names, (err) => {
}
console.info('Succeeded in setting the system bar to be invisible.');
});
```
### setSystemBarEnable<sup>(deprecated)</sup>
......@@ -5461,7 +5577,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err));
});
```
### setSystemBarProperties<sup>(deprecated)</sup>
......@@ -5500,7 +5615,6 @@ windowClass.setSystemBarProperties(SystemBarProperties, (err) => {
}
console.info('Succeeded in setting the system bar properties.');
});
```
### setSystemBarProperties<sup>(deprecated)</sup>
......@@ -5543,7 +5657,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err));
});
```
### loadContent<sup>(deprecated)</sup>
......@@ -5575,7 +5688,6 @@ windowClass.loadContent('pages/page2/page2', (err) => {
}
console.info('Succeeded in loading the content.');
});
```
### loadContent<sup>(deprecated)</sup>
......@@ -5611,7 +5723,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to load the content. Cause: ' + JSON.stringify(err));
});
```
### isShowing<sup>(deprecated)</sup>
......@@ -5642,7 +5753,6 @@ windowClass.isShowing((err, data) => {
}
console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data));
});
```
### isShowing<sup>(deprecated)</sup>
......@@ -5672,7 +5782,6 @@ promise.then((data)=> {
}).catch((err)=>{
console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err));
});
```
### on('systemAvoidAreaChange')<sup>(deprecated)</sup>
......@@ -5700,7 +5809,6 @@ Enables listening for changes to the area where the window cannot be displayed.
windowClass.on('systemAvoidAreaChange', (data) => {
console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data));
});
```
### off('systemAvoidAreaChange')<sup>(deprecated)</sup>
......@@ -5726,7 +5834,6 @@ Disables listening for changes to the area where the window cannot be displayed.
```js
windowClass.off('systemAvoidAreaChange');
```
### isSupportWideGamut<sup>(deprecated)</sup>
......@@ -5757,7 +5864,6 @@ windowClass.isSupportWideGamut((err, data) => {
}
console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data));
});
```
### isSupportWideGamut<sup>(deprecated)</sup>
......@@ -5787,7 +5893,6 @@ promise.then((data)=> {
}).catch((err)=>{
console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err));
});
```
### setColorSpace<sup>(deprecated)</sup>
......@@ -5819,7 +5924,6 @@ windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => {
}
console.info('Succeeded in setting window colorspace.');
});
```
### setColorSpace<sup>(deprecated)</sup>
......@@ -5855,7 +5959,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err));
});
```
### getColorSpace<sup>(deprecated)</sup>
......@@ -5886,7 +5989,6 @@ windowClass.getColorSpace((err, data) => {
}
console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data));
});
```
### getColorSpace<sup>(deprecated)</sup>
......@@ -5916,7 +6018,6 @@ promise.then((data)=> {
}).catch((err)=>{
console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err));
});
```
### setBackgroundColor<sup>(deprecated)</sup>
......@@ -5935,7 +6036,7 @@ Sets the background color for this window. This API uses an asynchronous callbac
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | --------- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Example**
......@@ -5949,7 +6050,6 @@ windowClass.setBackgroundColor(color, (err) => {
}
console.info('Succeeded in setting the background color.');
});
```
### setBackgroundColor<sup>(deprecated)</sup>
......@@ -5968,7 +6068,7 @@ Sets the background color for this window. This API uses a promise to return the
| Name | Type | Mandatory | Description |
| ----- | ------ | --------- | ------------------------------------------------------------ |
| color | string | Yes | Background color to set. The value is a hexadecimal RGB or aRGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
| color | string | Yes | Background color to set. The value is a hexadecimal RGB or ARGB color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. |
**Return value**
......@@ -5986,7 +6086,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the background color. Cause: ' + JSON.stringify(err));
});
```
### setBrightness<sup>(deprecated)</sup>
......@@ -6019,7 +6118,6 @@ windowClass.setBrightness(brightness, (err) => {
}
console.info('Succeeded in setting the brightness.');
});
```
### setBrightness<sup>(deprecated)</sup>
......@@ -6056,7 +6154,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err));
});
```
### setDimBehind<sup>(deprecated)</sup>
......@@ -6088,7 +6185,6 @@ windowClass.setDimBehind(0.5, (err) => {
}
console.info('Succeeded in setting the dimness.');
});
```
### setDimBehind<sup>(deprecated)</sup>
......@@ -6124,7 +6220,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err));
});
```
### setFocusable<sup>(deprecated)</sup>
......@@ -6157,7 +6252,6 @@ windowClass.setFocusable(isFocusable, (err) => {
}
console.info('Succeeded in setting the window to be focusable.');
});
```
### setFocusable<sup>(deprecated)</sup>
......@@ -6194,7 +6288,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err));
});
```
### setKeepScreenOn<sup>(deprecated)</sup>
......@@ -6227,7 +6320,6 @@ windowClass.setKeepScreenOn(isKeepScreenOn, (err) => {
}
console.info('Succeeded in setting the screen to be always on.');
});
```
### setKeepScreenOn<sup>(deprecated)</sup>
......@@ -6264,7 +6356,6 @@ promise.then(() => {
}).catch((err)=>{
console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err));
});
```
### setOutsideTouchable<sup>(deprecated)</sup>
......@@ -6296,7 +6387,6 @@ windowClass.setOutsideTouchable(true, (err) => {
}
console.info('Succeeded in setting the area to be touchable.');
});
```
### setOutsideTouchable<sup>(deprecated)</sup>
......@@ -6332,7 +6422,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err));
});
```
### setPrivacyMode<sup>(deprecated)</sup>
......@@ -6365,7 +6454,6 @@ windowClass.setPrivacyMode(isPrivacyMode, (err) => {
}
console.info('Succeeded in setting the window to privacy mode.');
});
```
### setPrivacyMode<sup>(deprecated)</sup>
......@@ -6402,7 +6490,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err));
});
```
### setTouchable<sup>(deprecated)</sup>
......@@ -6435,7 +6522,6 @@ windowClass.setTouchable(isTouchable, (err) => {
}
console.info('Succeeded in setting the window to be touchable.');
});
```
### setTouchable<sup>(deprecated)</sup>
......@@ -6472,7 +6558,6 @@ promise.then(()=> {
}).catch((err)=>{
console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err));
});
```
## WindowStageEventType<sup>9+</sup>
......@@ -6542,7 +6627,6 @@ export default class EntryAbility extends UIAbility {
});
}
};
```
### getMainWindow<sup>9+</sup>
......@@ -6590,7 +6674,6 @@ export default class EntryAbility extends UIAbility {
});
}
};
```
### getMainWindowSync<sup>9+</sup>
......@@ -6635,7 +6718,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### createSubWindow<sup>9+</sup>
......@@ -6690,9 +6772,7 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### createSubWindow<sup>9+</sup>
createSubWindow(name: string): Promise&lt;Window&gt;
......@@ -6748,7 +6828,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### getSubWindow<sup>9+</sup>
......@@ -6796,9 +6875,7 @@ export default class EntryAbility extends UIAbility {
});
}
};
```
### getSubWindow<sup>9+</sup>
getSubWindow(): Promise&lt;Array&lt;Window&gt;&gt;
......@@ -6843,9 +6920,7 @@ export default class EntryAbility extends UIAbility {
})
}
};
```
### loadContent<sup>9+</sup>
loadContent(path: string, storage: LocalStorage, callback: AsyncCallback&lt;void&gt;): void
......@@ -6859,9 +6934,9 @@ Loads content from a page associated with a local storage to the main window in
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ |
| path | string | Yes | Path of the page from which the content will be loaded. |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. |
| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
**Error codes**
......@@ -6899,7 +6974,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### loadContent<sup>9+</sup>
......@@ -6915,9 +6989,9 @@ Loads content from a page associated with a local storage to the main window in
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ |
| ------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ |
| path | string | Yes | Path of the page from which the content will be loaded. |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. |
| storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. |
**Return value**
......@@ -6959,7 +7033,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### loadContent<sup>9+</sup>
......@@ -7011,7 +7084,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### on('windowStageEvent')<sup>9+</sup>
......@@ -7061,7 +7133,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### off('windowStageEvent')<sup>9+</sup>
......@@ -7108,7 +7179,6 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
### disableWindowDecor()<sup>9+</sup>
......@@ -7145,7 +7215,6 @@ export default class EntryAbility extends UIAbility {
windowStage.disableWindowDecor();
}
};
```
### setShowOnLockScreen()<sup>9+</sup>
......@@ -7192,9 +7261,7 @@ export default class EntryAbility extends UIAbility {
};
}
};
```
## TransitionContext<sup>9+</sup>
Provides the context for the transition animation.
......@@ -7255,7 +7322,6 @@ controller.animationForShown = (context : window.TransitionContext) => {
}
console.info('complete transition end');
};
```
## TransitionController<sup>9+</sup>
......@@ -7306,7 +7372,6 @@ controller.animationForShown = (context : window.TransitionContext) => {
);
console.info('complete transition end');
};
```
### animationForHidden<sup>9+</sup>
......@@ -7354,3 +7419,5 @@ controller.animationForHidden = (context : window.TransitionContext) => {
console.info('complete transition end');
};
```
<!--no_check-->
\ No newline at end of file
......@@ -25,7 +25,7 @@ Zips a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the folder or file to zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| inFile | string | Yes | Path of the folder or file to zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. |
| options | [Options](#options) | Yes | Optional parameters for the zip operation. |
......@@ -50,9 +50,9 @@ let options = {
};
zlib.zipFile(inFile, outFile, options).then((data) => {
console.log('zipFile result is ' + JSON.Stringify(data));
console.log('zipFile result is ' + JSON.stringify(data));
}).catch((err) => {
console.log('error is ' + JSON.Stringify(err));
console.log('error is ' + JSON.stringify(err));
});
```
......@@ -71,9 +71,9 @@ let options = {
};
zlib.zipFile(inFile , outFile, options).then((data) => {
console.log('zipFile result is ' + JSON.Stringify(data));
console.log('zipFile result is ' + JSON.stringify(data));
}).catch((err)=>{
console.log('error is ' + JSON.Stringify(err));
console.log('error is ' + JSON.stringify(err));
});
```
......@@ -91,7 +91,7 @@ Unzips a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the unzipped file. |
| options | [Options](#options) | Yes | Optional parameters for the unzip operation. |
......@@ -116,9 +116,9 @@ let options = {
strategy: zlib.CompressStrategy.COMPRESS_STRATEGY_DEFAULT_STRATEGY
};
zlib.unzipFile(inFile, outFile, options).then((data) => {
console.log('unzipFile result is ' + JSON.Stringify(data));
console.log('unzipFile result is ' + JSON.stringify(data));
}).catch((err)=>{
console.log('error is ' + JSON.Stringify(err));
console.log('error is ' + JSON.stringify(err));
})
```
......@@ -134,7 +134,7 @@ Compresses a file. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the compressed file. |
| options | [Options](#options) | Yes | Compression parameters. |
| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. |
......@@ -172,6 +172,8 @@ try {
}
```
## zlib.compressFile<sup>9+</sup>
compressFile(inFile: string, outFile: string, options: Options): Promise\<void>;
Compresses a file. This API uses a promise to return the result.
......@@ -182,7 +184,7 @@ Compresses a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the compressed file. |
| options | [Options](#options) | Yes | Compression parameters. |
......@@ -232,8 +234,8 @@ Decompresses a file. This API uses an asynchronous callback to return the result
| Name | Type | Mandatory| Description |
| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
| AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. |
......@@ -253,7 +255,7 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod
// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context.
import zlib from '@ohos.zlib';
let inFile = '/xx/xxx.zip';
let outFile = '/xxx';
let outFileDir = '/xxx';
let options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
......@@ -261,7 +263,7 @@ let options = {
};
try {
zlib.decompressFile(inFile, outFile, options, (errData) => {
zlib.decompressFile(inFile, outFileDir, options, (errData) => {
if (errData !== null) {
console.log(`errData is errCode:${errData.code} message:${errData.message}`);
}
......@@ -271,6 +273,8 @@ try {
}
```
## zlib.decompressFile<sup>9+</sup>
decompressFile(inFile: string, outFile: string, options: Options): Promise\<void>;
Decompresses a file. This API uses a promise to return the result.
......@@ -281,8 +285,8 @@ Decompresses a file. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. |
| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| outFile | string | Yes | Path of the decompressed file. The path must exist in the system. Otherwise, the decompression fails. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model](js-apis-inner-application-context.md).|
| options | [Options](#options) | Yes | Decompression parameters. |
**Error codes**
......@@ -299,7 +303,7 @@ For details about the error codes, see [zlib Error Codes](../errorcodes/errorcod
// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context.
import zlib from '@ohos.zlib';
let inFile = '/xx/xxx.zip';
let outFile = '/xxx';
let outFileDir = '/xxx';
let options = {
level: zlib.CompressLevel.COMPRESS_LEVEL_DEFAULT_COMPRESSION,
memLevel: zlib.MemLevel.MEM_LEVEL_DEFAULT,
......@@ -307,7 +311,7 @@ let options = {
};
try {
zlib.decompressFile(inFile, outFile, options).then((data) => {
zlib.decompressFile(inFile, outFileDir, options).then((data) => {
console.info('decompressFile success');
}).catch((errData) => {
console.log(`errData is errCode:${errData.code} message:${errData.message}`);
......
......@@ -22,7 +22,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| min | number \| string | No| Minimum size of the **\<Blank>** component in the container along the main axis.<br>Default value: **0**|
| min | number \| string | No| Minimum size of the **\<Blank>** component in the container along the main axis.<br>Default value: **0**<br>**NOTE**<br>This parameter cannot be set in percentage. If the value is negative, the default value is used. If the minimum size is larger than the available space of the container, it is used as the component size, and the component extends beyond the container.|
## Attributes
......@@ -30,10 +30,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.<br>Since API version 9, this API is supported in ArkTS widgets.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Color to fill the empty spaces.<br>Default value: **Color.Transparent**<br>Since API version 9, this API is supported in ArkTS widgets. |
## Events
The [universal events](ts-universal-events-click.md) are supported.
## Example
### Example 1
The sample below shows how the **\<Blank>** component fills the empty spaces in the container in landscape and portrait modes.
```ts
......
......@@ -25,8 +25,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ----------- | ---------- | ------------------ |
| vertical | boolean | Whether a vertical divider is used. **false**: A horizontal divider is used.<br>**true**: A vertical divider is used.<br>Default value: **false**<br>Since API version 9, this API is supported in ArkTS widgets.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | number \| string | Width of the divider.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute cannot be set to a percentage.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Color of the divider.<br>Default value: **'\#33182431'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | number \| string | Width of the divider.<br>Default value: **1**<br>Unit: vp<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute cannot be set to a percentage. The priority of this attribute is lower than that of the universal attribute [height](ts-universal-attributes-size.md). If the value of this attribute is greater than that of the universal attribute, cropping is performed based on the universal attribute settings.|
| lineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the divider.<br>Default value: **LineCapStyle.Butt**<br>Since API version 9, this API is supported in ArkTS widgets.|
......
......@@ -9,7 +9,10 @@
## Child Components
Supported
> **NOTE**
>
> - Supported types of child components: built-in components and custom components, with support for ([if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)) rendering control.
> - Number of child components: multiple.
## APIs
......@@ -22,6 +25,10 @@ NavDestination()
In addition to the [backgroundColor](ts-universal-attributes-background.md) attribute, the following attributes are supported.
| Name | Type | Description |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle) | Page title. |
| ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle) | Page title.<br>**NOTE**<br>When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.<br>When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Display the title bar.|
## Events
The [universal events](ts-universal-events-click.md) are supported.
......@@ -31,9 +31,16 @@ Creates a **PluginComponent** to display the UI provided by an external applicat
| source | string | Component template name. |
| bundleName | string | Bundle name of the provider ability.|
## Attributes
The universal attribute [size](ts-universal-attributes-size.md) is supported and must be set.
## Events
Only the [gesture event](ts-gesture-settings.md) can be distributed to the provider page and processed inside the provider page.
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description |
| ------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| onComplete(callback: () =&gt; void) | Triggered when the component loading is complete. |
......
......@@ -55,13 +55,18 @@ Since API version 9, this API is supported in ArkTS widgets.
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Description|
| -------- | -------- | -------- |
| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.<br>Since API version 9, this API is supported in ArkTS widgets.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.<br>Since API version 9, this API is supported in ArkTS widgets.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.<br>Default value: **'\#ff007dff'**<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.<br>Default value: **'\#19182431'**<br><br>Since API version 9, this API is supported in ArkTS widgets.|
| style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.<br>Default value: **4.0Vp**<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>Default value: **120**<br>- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.<br>Default value: **2.0Vp**<br>Since API version 9, this API is supported in ArkTS widgets.|
## Events
The [universal events](ts-universal-events-click.md) are supported.
## Example
......
......@@ -537,7 +537,7 @@ multiWindowAccess(multiWindow: boolean)
Sets whether to enable the multi-window permission.
Enabling the multi-window permission requires implementation of the **onWindowNew** event. For details about the sample code, see [onWindowNew](#onwindownew9).
Enabling the multi-window permission requires implementation of the **onWindowNew** event. For the sample code, see [onWindowNew](#onwindownew9).
**Parameters**
......@@ -703,6 +703,40 @@ Sets the cache mode.
}
```
### textZoomAtio<sup>(deprecated)</sup>
textZoomAtio(textZoomAtio: number)
Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%.
This API is deprecated since API version 9. You are advised to use [textZoomRatio<sup>9+</sup>](#textzoomratio9) instead.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------- | ------ | ---- | ---- | --------------- |
| textZoomAtio | number | Yes | 100 | Text zoom ratio to set.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
@State atio: number = 150
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.textZoomAtio(this.atio)
}
}
}
```
### textZoomRatio<sup>9+</sup>
textZoomRatio(textZoomRatio: number)
......@@ -1937,7 +1971,7 @@ Called when loading of the web page is complete. This API is used by an applicat
| Name | Type | Description |
| ----------- | ------- | ---------------------------------------- |
| url | string | URL to be accessed. |
| isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh](#refresh) API, and **false** means the opposite.|
| isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh<sup>9+</sup>](../apis/js-apis-webview.md#refresh) API, and **false** means the opposite.|
**Example**
......@@ -3099,7 +3133,7 @@ Called when this web page receives a new favicon.
Column() {
Web({ src:'www.example.com', controller: this.controller })
.onFaviconReceived((event) => {
console.log('onFaviconReceived:' + JSON.stringify(event))
console.log('onFaviconReceived');
this.icon = event.favicon;
})
}
......@@ -3221,6 +3255,34 @@ Called when the **\<Web>** component is about to access a URL. This API is used
}
```
### onRequestSelected
onRequestSelected(callback: () => void)
Called when the **\<Web>** component obtains the focus.
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onRequestSelected(() => {
console.log('onRequestSelected')
})
}
}
}
```
## ConsoleMessage
Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole).
......@@ -4145,7 +4207,7 @@ Describes the web-based media playback policy.
| Name | Type | Readable| Writable| Mandatory| Description |
| -------------- | --------- | ---- | ---- | --- | ---------------------------- |
| resumeInterval | number | Yes | Yes | No |Validity period for automatically resuming a paused web audio, in seconds. The maximum validity period is 60 seconds.|
| resumeInterval | number | Yes | Yes | No |Validity period for automatically resuming a paused web audio, in seconds. The maximum validity period is 60 seconds. Due to the approximate value, the validity period may have a deviation of less than 1 second.|
| audioExclusive | boolean | Yes | Yes | No | Whether the audio of multiple **\<Web>** instances in an application is exclusive. |
## DataResubmissionHandler<sup>9+</sup>
......@@ -4228,7 +4290,7 @@ Obtains the cookie management object of the **\<Web>** component.
| Type | Description |
| --------- | ---------------------------------------- |
| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).|
| WebCookie | Cookie management object. For details, see [WebCookie](#webcookiedeprecated).|
**Example**
......@@ -4457,7 +4519,7 @@ This API is deprecated since API version 9. You are advised to use [forward<sup>
deleteJavaScriptRegister(name: string)
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API.
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the[refresh](#refreshdeprecated) API.
This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister<sup>9+</sup>](../apis/js-apis-webview.md#deletejavascriptregister).
......@@ -4738,7 +4800,7 @@ This API is deprecated since API version 9. You are advised to use [refresh<sup>
registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> })
Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refresh) API for the registration to take effect.
Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refreshdeprecated) API for the registration to take effect.
This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy<sup>9+</sup>](../apis/js-apis-webview.md#registerjavascriptproxy).
......
......@@ -4,6 +4,10 @@ SystemCapability (SysCap) is a standalone feature in the OpenHarmony system.
Before using an API for development, you are advised to familiarize yourself with [SysCap](syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type.
> **NOTE**
>
> The **default** device type represents an OpenHarmony device with comprehensive functions and most common capabilities. When you are not sure about the capability set of the target device, you can use the **default** type for development.
## SystemCapability.ArkUI.ArkUI.Full
ArKUI standard system
......
......@@ -6,9 +6,9 @@ If an application or a service module running in the background has a service to
## Background Task Types
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode:
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode — efficiency resources:
- **No background task**: An application or service module does not need further processing when switched to the background.
- **No background task required**: An application or service module does not need further processing when switched to the background.
- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension.
......@@ -16,7 +16,7 @@ For more targeted management of background applications, OpenHarmony classifies
- **Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle.
- **Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including software and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including software and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
## Selecting a Background Task
......@@ -68,7 +68,7 @@ OpenHarmony provides 9 background modes for services that require continuous tas
- If the task is complete, the application should exit the background mode. If the system detects that an application is not using the resources in the corresponding background mode when the application is running in the background, the application is suspended.
- Ensure that the requested continuous task background mode matches the application type. If the background mode does not match the application type, the system will suspend the task once it detects the issue.
- If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue.
- Each ability can request only one continuous task at a time.
- An ability can request only one continuous task at a time. If an application has multiple abilities, you can request a continuous task for each ability.
## Work Scheduler Tasks
The Work Scheduler provides a mechanism for an application to execute a non-real-time task, for example, data learning, when the system is idle. The system places the Work Scheduler tasks requested by applications in a queue and determines the optimal scheduling time of each task based on the storage space, power consumption, temperature, and more. Persistence is supported. This means that a requested Work Scheduler task can be triggered when the application exits or the device restarts.
......
......@@ -80,13 +80,13 @@ To create a WorkScheduler project in DevEco Studio, perform the following steps:
3. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler.
Import the module.
Import the module.
```ts
import { workAbility } from '@ohos/library'
```
Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class WorkTest extends workAbility {
......@@ -175,10 +175,9 @@ To create a WorkScheduler project in DevEco Studio, perform the following steps:
}
```
### Setting the Configuration File
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEntrance** to the code path of the WorkSchedulerExtensionAbility component.
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEnty** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
......@@ -186,7 +185,7 @@ To create a WorkScheduler project in DevEco Studio, perform the following steps:
"extensionAbilities": [
{
"name": "WorkTest",
"srcEntrance": "./ets/workAbility/WorkTest.ets",
"srcEntry": "./ets/workAbility/WorkTest.ets",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
......@@ -195,3 +194,13 @@ To create a WorkScheduler project in DevEco Studio, perform the following steps:
}
}
```
## Restrictions
To minimize the abuse of **WorkSchedulerExtensionAbility** by third-party applications, the following APIs cannot be invoked in **WorkSchedulerExtensionAbility**:
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
......@@ -27,4 +27,9 @@ typedef enum {
### Sequential Loading (Default)
The **priority** field (ranging from 0 to 200) in the configuration file determines the loading sequence of a host and a driver. For the drivers in different hosts, the drivers in the host with a smaller priority value are loaded first. For the drivers in the same host, the driver with a smaller priority value is loaded first.
The **priority** field (ranging from 0 to 200) in the configuration file determines the loading sequence of a host and a driver. For the drivers in different hosts, the driver with a smaller priority value is loaded first. For the drivers in the same host, the driver with a smaller priority value is loaded first.
### Exception Recovery (User-Mode Driver)
The policies for restoring from a driver service exception are as follows:
- If **preload** is set to **0** (**DEVICE_PRELOAD_ENABLE**) or **1** (**DEVICE_PRELOAD_ENABLE_STEP2**) for the driver service, the startup module starts the host and reloads the service.
- If **preload** is set to **2** (**DEVICE_PRELOAD_DISABLE**), the service module needs to register an HDF service status listener. When receiving a notification on service exit, the service module calls **LoadDevice()** to reload the service.
......@@ -62,6 +62,7 @@
- [Dynamic Loading and Linking](kernel-small-bundles-linking.md)
- [Virtual Dynamic Shared Object](kernel-small-bundles-share.md)
- [LiteIPC](kernel-small-bundles-ipc.md)
- [Container](kernel-small-bundles-container.md)
- File Systems
- [Virtual File System](kernel-small-bundles-fs-virtual.md)
- [Supported File Systems](kernel-small-bundles-fs-support.md)
......
# Container
## Overview
Container provides a mechanism to isolate global resources, such as process identifiers (PIDs), host information, and user information. The container mechanism allows the processes in different containers to have independent global resources. Changing system resources in a container does not affect processes in other containers.
The LiteOS-A kernel container isolation function involves seven containers: UTS container, PID container, Mount container, Network container, Time container, IPC container, and User container. The container information is stored in the **container** and **credentials** structs of the process control block (**ProcessCB**) struct.
The following table lists the LiteOS-A containers.
| No. | Name | Macro Definition/Flag | Resource | Data Struct |
| :-------- | :------------- | :------------------- | :----------------------- | :----------------------- |
| 1 | UTS | CLONE_NEWUTS | Host names, domain names, and version information.|struct Container |
| 2 | PID | CLONE_NEWPID | PIDs. |struct Container |
| 3 | Mount | CLONE_NEWNS | File system mount points. |struct Container |
| 4 | Network | CLONE_NEWNET | Network system resources. |struct Container |
| 5 | TIME | CLONE_NEWTIME | Clock resources. |struct Container |
| 6 | IPC | CLONE_NEWIPC | Inter-process communication (IPC) resources. |struct Container |
| 7 | User | CLONE_NEWUSER | Users and user groups. |struct Credentials |
The container-based resource isolation can be further classified into the following types:
- Global isolation: The containers are parallel (without inheritance relationships), and the container resources are invisible to each other.
- Non-global isolation: The containers have parent-child relationships. The resources of containers of the same level are invisible, but the upper-level container can access resources of the lower-level container.
For the PID container, **unshare()** or **setns()** changes the container of the child process (not the process).
You can add a **Container** struct and a **Credentials** struct to the **ProcessCB** of a process to implement container functionalities. You can also enable or disable specific container by using compiler switches.
- The **ProcessCB** struct of each process contains a pointer to the **Container** struct allocated. This allows a process to have an independent **Container** struct or share a **Container** struct. The **Container** struct contains pointers to the UTS, PID, Network, Mount, Time, and IPC containers.
- The **ProcessCB** struct of each process has a **Credentials** struct for independent User container management. This design facilitates modularization and independent processing of the unique logic of the User container.
![Overall Design-Overall Structure-1](figures/container-001.png)
### Containers
#### **UTS Container**
The UTS container isolates information, such as host names, domain names, and version information. The information in different UTS containers is isolated from each other.
#### **Mount Container**
The Mount container isolates file mount points. The mount and unmount operations in a container does not affect other containers.
The Mount container allows processes to use the file mounting system independently. Child processes perform mount operations in independent file mounting containers and have their own file mount structs.
- To implement a Mount container, use **clone()** with the **CLONE_NEWNS** flag to create a process, and change the mount information from global information to the information specific to the Mount container.
- After a Mount container is created, change the implementation of obtaining the mount information to enable the mount information to be obtained from the current Mount container. After that, the mount, unmount, and access to the mounted file system of the process do not affect that of other processes.
#### **PID Container**
The PID container isolates PIDs. Processes of different containers can use the same virtual process ID.
The PID container provides the following features:
- The PIDs of different containers are independent of each other.
- Nested PID containers are supported. The processes in the child PID containers are visible to the parent PID container. For the same process, the PID in the parent PID container is independent from the PID in the child PID container.
- The child PID container cannot view the processes in its parent container.
- All PIDs of the system can be viewed in the root container.
#### **Network Container**
The Network container isolates the system's network devices and network stacks.
The Network container isolates the TCP/IP protocol stacks and network device resources.
- Transport layer isolation: The Network container isolates port numbers. The available port numbers in a Network container range from 0 to 65535. A process is bound to the port number of its own container. Processes of different Network containers can be bound to the same TCP/UDP port number without affecting each other.
- IP layer isolation: The Network container isolates IP resources. Each container has its own IP resources. Changing the IP address in a Network container does not affect other Network containers.
- Network device isolation: The Network container isolates network interface cards (NICs). Each container has its own NICs. The NICs in different Network containers are isolated from each other and cannot communicate with each other. You can configure veth-pair to implement communication between different containers.
#### **User Container**
The User container isolates users and user groups.
The User container isolates management rights by User ID or Group ID (UID/GID) and capability.
- UID/GID
The User container isolates UIDs/GIDs. Different User containers have different UIDs/GIDs. Each User container has independent UIDs/GIDs starting from 0. In this way, the processes in the container can have the **root** permission, which is restricted to the minimum range. Changing the UID/GID of a User container does not affect the processes of other User containers.
- Capability
With the User container, you can set different capabilities for processes.
Each process calls **OsInitCapability()** to initialize its permissions. You can use **SysCapGet()** to obtain the capabilities of a process, and use **SysCapSet()** to modify the process permissions.
The following table describes the capabilities.
| Capability | Description |
| --------------------- | ---------------------------------------------- |
| CAP_CHOWN | Changes the owner of a file. |
| CAP_DAC_EXECUTE | Overrides the Discretionary Access Control (DAC) restriction on file execution. |
| CAP_DAC_WRITE | Overrides the DAC restriction on file write. |
| CAP_DAC_READ_SEARCH | Overrides the DAC restriction on file read or search of a directory. |
| CAP_FOWNER | Overrides the requirement that the file owner ID must match the process user ID.|
| CAP_KILL | Sends a **kill** signal to another process that is not owned by the sender. |
| CAP_SETGID | Changes the GID of a process. |
| CAP_SETUID | Changes the UID of a process. |
| CAP_NET_BIND_SERVICE | Binds a socket to a port whose number is less than 1024. |
| CAP_NET_BROADCAST | Allows network broadcast and multicast access. |
| CAP_NET_ADMIN | Allows network management tasks to be executed. |
| CAP_NET_RAW | Allows the use of raw sockets. |
| CAP_FS_MOUNT | Allows **chroot()**. |
| CAP_FS_FORMAT | Allows the use of the file format. |
| CAP_SCHED_SETPRIORITY | Sets the process scheduling priority. |
| CAP_SET_TIMEOFDAY | Sets the system time. |
| CAP_CLOCK_SETTIME | Sets the clock time. |
| CAP_CAPSET | Sets any capability. |
| CAP_REBOOT | Restarts the system. |
| CAP_SHELL_EXEC | Executes shell. |
#### **Time Container**
The Time container isolates the time maintenance information of the system.
Each process has its own Time container to hold the **CLOCK_MONOTONIC** and **CLOCK_MONOTONIC_RAW** clocks so that the operations on these clocks do not affect the clocks of other processes.
The clock offset in the time_for_children container of the current process is recorded in the **/proc/PID/timens_offsets** file. You can also modify the file to change the offset of the Time container. These offsets indicate the time difference from the clock value in the initial Time container.
Currently, the only way to create a Time container is to call **unshare()** with the **CLONE_NEWTIME** flag. The Time container created holds the child process created by the calling process instead of the calling process.
You need to set the clock offset (**/proc/PID/timens_offsets**) for this container before the first process of the container is created.
#### **IPC Container**
The IPC container isolates IPC objects, including the message queues and shared memory.
Each process has its own IPC container to hold the message queue and shared memory.
As a result, the operations on the message queue and shared memory in different containers do not affect each other.
- Message queue isolation: Change the global variable struct **LosQueueCB** to a local variable in each IPC container to implement the message queue isolation.
- Shared memory isolation: Change the global variables **shmInfo**, **sysvShmMux**, **shmSegs**, and **shmUsedPageCount** to local variables in each IPC container to implement the isolation of the shared memory.
### Working Principles
#### Process of Creating a Container
During the system initialization process, a root container is created for initial processes (processes 0, 1, and 2). The root container types include all of the seven containers.
You can use **clone()** with the container flag specified to create a container for a process. If the container flag is not specified, the process reuses its parent process container.
![ContainerBase](figures/container-002.png)
#### Process of Switching a Container
Use **unshare()** to move a process to a newly created container. The following figure uses the IPC container as an example.
<img src="figures/container-003.png" alt="ContainerBase" style="zoom:80%;" />
## How to Develop
The following describes how to create, switch, and destroy a container.
### Creating a Container
You can create a container when using **clone()** to create a process.
**clone**
A container can be created when you use **clone()** to create a process. The function prototype is as follows:
```
int clone(int (*fn)(void *), void *stack, int flags, void *arg, ...
/* pid_t *parent_tid, void *tls, pid_t *child_tid */ );
```
- When using **clone()** to create a process, you can specify a container to isolate resources (such as the UTS information) for the process.
- If no container flag is specified, the process shares the containers of its parent process.
### Switching a Container
You can use either of the following interfaces to move a process to another container:
- **unshare**
Use **unshare()** to move a process to a newly created container. The function prototype is as follows:
```
int unshare(int flags);
```
**NOTE**<br>For the PID or Time container, **unshare()** moves the child process (not the process itself) to a new container created.
- **setns**
Use **setns()** to move a process to another existing container. The function prototype is as follows:
```
int setns(int fd, int nstype);
```
**NOTE**<br>For the PID or Time container, **setns()** moves the child process (not the process itself) to another container.
### Destroying a Container
When a process is terminated, it exits all containers and the container reference count decrements. When the reference count decrements to 0, you need to destroy the container.
You can use **kill()** to send a specified signal to the process to terminate or exit it. The function prototype is as follows:
```
int kill(pid_t pid, int sig);
```
### Querying Container Information
You can run the **ls** command to view container information in the **/proc/[pid]/container/** directory.
```
ls -l /proc/[pid]/container
```
| Property | User| User Group| File Name | Description |
| :--------- | :------- | :--------- | :--------------------------------------- | :--------------------- |
| lr--r--r-- | u:0 | g:0 | net -> 'net:[4026531847]' | The referenced object is the container with a unique ID.|
| lr--r--r-- | u:0 | g:0 | user -> 'user:[4026531841]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | u:0 | time_for_children -> 'time:[4026531846]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | time -> 'time:[4026531846]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | ipc -> 'ipc:[4026531845]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | mnt -> 'mnt:[4026531844]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | uts -> 'uts:[4026531843]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | pid_for_children -> 'pid:[4026531842]' | The referenced object is the container with a unique ID. |
| lr--r--r-- | u:0 | g:0 | pid -> 'pid:[4026531842]' | The referenced object is the container with a unique ID. |
### plimits
plimits sets resource limits of process groups. **/proc/plimits** is the root directory of plimits.
- The plimits file system is a pseudo file system used to implement mappings between files and plimits variables. With this file system, you can modify kernel variables through operations on files. For example, you can modify the **memory.limit** file to restrict memory allocation.
- In the plimits file system, files can be read and written, and directories can be added or deleted.
- A plimits directory maps a plimits group. When a directory is created, the files (mapped to the control variables of the limiter) in the directory are automatically created.
- Files for a limiter are created by group. For example, when a memory limiter is created, all files required, instead of a single file, are created.
The macro **LOSCFG_PROCESS_LIMITS** specifies the setting of plimits. **y** means to enable plimits, and **n** (default) means the opposite.
If **LOSCFG_PROCESS_LIMITS** is set to **y**, the **/proc/plimits** directory contains the following files:
| Permission | User| User Group| File Name | Description | Remarks |
| ---------- | ---- | ------ | ---------------- | --------------------------------- | ------------------------------------------------------------ |
| -r--r--r-- | u:0 | g:0 | sched.stat | Scheduling statistics information. | Output format: [PID runTime] |
| -r--r--r-- | u:0 | g:0 | sched.period | Scheduling period configuration, in μs. | / |
| -r--r--r-- | u:0 | g:0 | sched.quota | Scheduling quota configuration, in μs. | / |
| -r--r--r-- | u:0 | g:0 | devices.list | List of the devices accessed by processes in plimits. | Output format: [type name access] |
| -r--r--r-- | u:0 | g:0 | devices.deny | Devices that cannot be accessed by the processes in plimits.| Format: ["type name access" >> device.deny] |
| -r--r--r-- | u:0 | g:0 | devices.allow | Devices that can be accessed by the processes in plimits.| Format: ["type name access" >> device.allow] |
| -r--r--r-- | u:0 | g:0 | ipc.stat | Statistics about the IPC objects allocated. | Output format: [mq count: mq failed count:<br> shm size: shm failed count: ] |
| -r--r--r-- | u:0 | g:0 | ipc.shm_limit | Upper limit of the shared memory, in bytes. | / |
| -r--r--r-- | u:0 | g:0 | ipc.mq_limit | Maximum number of messages in a message queue. | 0 to 64-bit positive integer |
| -r--r--r-- | u:0 | g:0 | memory.stat | Memory statistics, in bytes. | / |
| -r--r--r-- | u:0 | g:0 | memory.limit | Total memory limit for a process group, in bytes. | / |
| -r--r--r-- | u:0 | g:0 | pids.max | Maximum number of processes in a group. | / |
| -r--r--r-- | u:0 | g:0 | pids.priority | Highest process priority in a group. | / |
| -r--r--r-- | u:0 | g:0 | plimits.procs | PIDs of all processes in a group. | / |
| -r--r--r-- | u:0 | g:0 | plimits.limiters | Limiters in the plimits group. | / |
The **devices** parameter is described as follows:
| type (Device Type) | name (Device Name)| access (Permission) |
| -------------------------------------------- | ----------------- | ---------------------------------- |
| a - All devices, which can be character devices or block devices.| / | r - Allow the process to read the specified device. |
| b - Block device | / | w - Allow the process to write to the specified device. |
| c - Character device | / | m - Allow the process to generate a file that does not exist.|
## Reference
### Specifications
#### Parameter Settings
**LOSCFG_KERNEL_CONTAINER_DEFAULT_LIMIT** specifies the maximum number of containers of each type supported by the kernel.
The initialization of the **proc/sys/user** directory generates the **max_net_container**, **max_ipc_container**, **max_time_container**, **max_uts_container**, **max_user_container**, **max_pid_container**, and **max_mnt_container** files, and binds the pseudo files and kernel parameters. You can modify the kernel parameters by configuring the pseudo files. New containers can be created if the number of containers is less than the maximum. Otherwise, NULL is returned.
#### **Unique Container ID**
All the containers are uniquely numbered based on a fixed value.
```
#define CONTAINER_IDEX_BASE (0xF0000000)
inum = CONTAINER_IDEX_BASE + (unsigned int)i;
```
#### **Rule Settings**
- The PID container and User container support nesting of up to three layers. Other containers do not support nested containers.
- When **clone()**, **setns()**, and **unshare()** are used, flags complying with POSIX must be passed in. The flags are described as follows:
| Flag | clone | setns | unshare |
| ------------- | ---------------------------- | -------------------------------- | -------------------------------- |
| CLONE_NEWNS | Create a Mount container for a child process. | Move this process to the specified Mount container.| Create a Mount container for this process. |
| CLONE_NEWPID | Create a PID container for a child process. | Move this process to the specified PID container. | Create a PID container for a new child process. |
| CLONE_NEWIPC | Create an IPC container for a child process. | Move this process to the specified IPC container. | Create an IPC container for this process. |
| CLONE_NEWTIME | Create a Time container for the parent process of this process.| Not supported currently | Create a Time container for a new child process.|
| CLONE_NEWUSER | Create a User container for a child process. | Move this process to the specified User container. | Create a User container for this process. |
| CLONE_NEWUTS | Create a UTS container for a child process. | Move this process to the specified UTS container. | Create a UTS container for this process. |
| CLONE_NEWNET | Create a Network container for a child process. | Move this process to the specified Network container.| Create a Network container for this process. |
- The container features are controlled by compiler macros.
- Container compiler macro definition:
```
// Macro of the container feature
LOSCFG_CONTAINER
// Macro of the container of each type
LOSCFG_UTS_CONTAINER
LOSCFG_MNT_CONTAINER
LOSCFG_PID_CONTAINER
LOSCFG_NET_CONTAINER
LOSCFG_USER_CONTAINER
LOSCFG_TIME_CONTAINER
LOSCFG_IPC_CONTAINER
```
### Development Examples
The LiteOS-A smoke test cases contain the examples of the corresponding interfaces. You need to compile and verify the test cases. The recommended test cases are as follows:
[Creating a UTS Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_001.cpp)
[Moving a Process to a New UTS Container Using unshare()](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_004.cpp)
[Moving a Process to the UTS Container of the Child Process Using setns()](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_uts_container_005.cpp)
[Creating a Network Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_net_container_001.cpp)
[Creating a User Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_user_container_001.cpp)
[Creating a PID Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_pid_container_023.cpp)
[Creating a Mount Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_mnt_container_001.cpp)
[Creating an IPC Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_ipc_container_001.cpp)
[Creating a Time Container](https://gitee.com/openharmony/kernel_liteos_a/blob/master/testsuites/unittest/container/smoke/It_time_container_001.cpp)
......@@ -5,10 +5,9 @@
OpenHarmony 3.1.7 Release provides enhanced system security over OpenHarmony 3.1.6 Release by rectifying memory leak issues, certain known vulnerabilities in open-source components such as Linux kernel, and system stability issues. The matching SDK version is also updated.
## Version Mapping
## Mapping relationship
**Table 1** Version mapping of software and tools
**Table 1** Version mapping of software and tools
| Software/Tool | Version | Remarks |
| ------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
......@@ -100,8 +99,6 @@ This version does not involve feature updates.
This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
......@@ -122,8 +119,6 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| DFX subsystem | **libhilog.z.so** crashes in **ohos.samples.distributedmusicplayer**. ([I6DCSL](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I6DCSL))|
### Fixed Security Vulnerabilities
**Table 4** Fixed security vulnerabilities
......@@ -147,7 +142,7 @@ For details about the adaptation status, see [SIG-Devboard](https://gitee.com/op
| I6JH2L | Security vulnerabilities of the kernel_linux_4.19 component: CVE-2023-23559, CVE-2022-47929, CVE-2022-2873, and CVE-2023-23455| [PR](https://gitee.com/openharmony/kernel_linux_4.19/pulls/103) |
| I6LCHO | Security vulnerability of the kernel_linux_4.19 component: CVE-2023-0030 | [PR](https://gitee.com/openharmony/kernel_linux_4.19/pulls/111) |
##
## Known Issues
**Table 5** Known issues
......
# OpenHarmony 3.2 Release
## Version Description
OpenHarmony 3.2 Release provides more comprehensive capabilities for the standard system. It supports the development of large-scale applications and atomic services using the ArkTS programming language and stage model. It has optimized the [ArkCompiler](#arkcompiler) and introduced the task pool mechanism to improve running performance of applications. It has improved the capabilities of ArkUI components, graphics rendering, and system security, supporting more diverse distributed service development. It provides stable APIs of API version 9, which further improves the overall system performance, stability, and security based on OpenHarmony 3.1 Release.
The figure below shows the milestones of OpenHarmony 3.2. Read the content below to learn more about key features and capabilities.
**Figure 1** Milestones of OpenHarmony 3.2
![release](figures/release.png)
## Feature Updates
### ArkUI
**Component capability enhancement**
- The XComponent is supported. This component can be used to write EGL/OpenGL ES data and media data and display the data. It can work with the NDK to support C++/ArkTS hybrid development for gaming and media applications.
- The AbilityComponent is supported. It enables an ability to embed into other applications as a component.
- The basic capabilities for ArkTS widget development are provided. Widget interaction and dynamic content update are supported. A unified paradigm is provided for widget and page development, so that the page layout can be directly reused in the widget layout, improving widget development experience and efficiency.
- The system supports text-only and image-only copy, paste, and drag by default. You do not need to process copy, paste, and drag events.
- Multi-level menus and group menus are supported.
- **You can develop UI at a time that can adapt to screens of different specifications.**
- The interaction normalization capability is enhanced. Unified interaction events are provided for the touch panel, mouse, keyboard, touchpad, and stylus. Native ArkUI components support normalized operations.
- The responsive layout capability is optimized, the media query capability is enhanced, and the grid system is reconstructed and supports interconnection with the free window.
- The focus capability is enhanced. The Tab key and arrow keys can be used to move the focus, and a component can be configured to be focusable.
- The **\<Column>** and **\<SideBarContainer>** components can be automatically hidden when they are dragged to a width that is less than the minimum width.
For details, see [ArkUI Guide](../application-dev/ui/arkui-overview.md).
### Application Framework
- The stage model is introduced in API version 9. It provides mandatory components and running mechanisms for applications. This model makes the development of complex applications simpler and more efficient.
- Abilities are provided in the form of classes, making extension easier.
- VM instances can be shared within a process, reducing memory usage of applications.
- Data objects can be shared within a process, enabling state sharing among multiple modules.
- The ability lifecycle is separated from the window display/focus event, and a unified ability lifecycle is used in multiple device forms, facilitating distributed application development.
- The ability and UI are separated, RPC capabilities are provided, and abilities can be migrated and collaborated across devices, facilitating distributed application development.
- The ExtensionAbility mechanism is provided. With this mechanism, an application can provide custom functions and content for another application or the system during interaction. For example, an application can be displayed as a widget on the home screen or execute background tasks during off-peak hours. Currently, the following ExtensionAbilities are supported: FormExtensionAbility, WorkSchedulerExtensionAbility, InputMethodExtensionAbility, and AccessibilityExtensionAbility.
- Atomic services can be pre-loaded by package, improving the first-time loading performance.
- The Harmony Shared Package (HSP) is used for sharing of code and resources within an application.
For details, see [Application Model Guide](../application-dev/application-models/application-model-composition.md).
### Application Package Management
- A default application can be selected. For example, if a user selects an application as the default application when opening a file or URL, that application will be automatically used to open the file or URL of the same type next time.
- The system can grant permissions (such as location and contact permissions) to certain pre-installed applications, such as **Home Screen**, **SystemUI**, and **Settings**, to simplify the authorization process when the device is powered on for the first time. For details, see [Pre-authorizing user_grant Permissions](../application-dev/security/accesstoken-guidelines.md).
- Permission control on pre-installed applications is enhanced. For example, you can configure whether pre-installed applications can reside permanently, use multiple processes, or use ServiceExtensionAbility. For details, see the [Application Privilege Configuration Guide](../device-dev/subsystems/subsys-app-privilege-config-guide.md).
- Application code can be dynamically updated, and quick fix packages are provided for applications to quickly respond to requirements and fix defects. (This capability requires the device vendor to build an application market and provide the distribution capability.) For details, see [Quick Fix Overview](../application-dev/quick-start/quickfix-principles.md).
- HAP-based isolation is provided for .so files, so you can deploy .so files of the same name in different modules.
### System Applications
**Home Screen enhancement**
Users can hold an application icon (currently **Camera** and **Gallery**) on the home screen to add a service widget.
**SystemUI enhancement**
- Control Panel can be opened and exited.
- Notification Panel can be opened and exited. Notifications can be displayed, deleted, group expanded, and group collapsed. Banner notifications can be displayed and hidden.
**Settings enhancement**
- Users can set permissions on the **Privacy** menu.
- The following debugging switches are added to the developer options: layout boundary, transition animation, and transition drawing.
**Photos enhancement**
- The PhotoPicker capability is added. PhotoPicker is a unified entry for users to select images and videos. It enables users to grant only media file permissions to applications when they try to access images and videos.
- The service widget and browsing capabilities are provided for **Albums**.
- Users can edit images, such as cropping and rotating.
For details, see [Application Photos](https://gitee.com/openharmony/applications_photos).
**FilePicker**
The FilePicker capability is added. FilePicker is a unified entry for users to select files (except media files). It enables users to grant non-media file permissions to applications when they try to access files other than images and videos.
**Browser**
No built-in browser application is available. You can develop a browser application by following the instructions provided in [Browser Application](https://gitee.com/openharmony/applications_app_samples/tree/samples_3.2_Release/code/BasicFeature/Web/Browser).
### Distributed Technology
Abilities and widgets can be queried, added, refreshed, and deleted across devices.
#### DSoftBus
- Files can be transferred over Bluetooth links. Compared with OpenHarmony 3.1, this version provides a 10% increase in the performance of the Bluetooth data transmission channel.
- For each process, two queues are created: a high-priority queue for messages and a low-priority queue for bytes. This ensures that messages can be transmitted in time in the case of byte congestion.
- In addition to raw stream transmission, common stream transmission is provided, which enables DSoftBus to perform encryption and decryption on unencrypted audio and video streams. The caller only needs to transmit raw audio and video streams to DSoftBus, which ensures secure data transmission.
- Transmission links (WLAN/Wi-Fi P2P/Bluetooth BR) can be dynamically selected based on the transmission link supported by the devices and the DSoftBus APIs called (**SendFile**, **SendStream**, **SendMessage**, and **SendBytes**). For example, when stream data needs to be transmitted, a WLAN (5G frequency band) is preferentially selected. If the WLAN is unavailable, another link (for example, Wi-Fi P2P) is selected.
#### Distributed hardware
- The distributed camera allows users to set the location and quality level (which affects the compression ratio and definition of photos).
- The distributed camera supports video recording.
- Users can import account authentication information to the device security authentication system. Devices with the same login account can automatically complete authentication and networking.
#### Distributed data management
**Cross-application data access**
- The proxy mode is used to implement cross-application data access on the same device, avoiding frequent launch of applications that provides the data source.
- Cross-application data access to relational databases and key-value databases on the same device is supported.
**Local database**
- Key-value databases and relational databases are supported.
- Database files can be encrypted for storage.
- Database damage detection and rebuild are supported.
- Applications can back up and restore databases via clients.
- Key-value databases can be automatically backed up.
- Relational database query for the same application across devices is supported.
- Damage detection and rebuild for metadata databases are supported.
- The key-value database is moved from the unified system sandbox to the application-specific sandbox, minimizing the access permission of application data and improving application data security.
**Data synchronization**
- Key-value data can be synchronized based on conditions (time segment, time sorting, and synchronization duration).
- When a device goes online, system data is preferentially synchronized, shortening the device wakeup time.
- Cross-device data synchronization in multi-user scenarios is supported.
**Distributed object**: Objects can be persistent.
**Sandbox application**: Key-value databases, relational databases, and distributed objects can be persistent.
#### Distributed Scheduler
The ability hopping capability is enhanced. The automatic serialization of data structures simplifies application adaptation. The use of distributed objects makes service data migration easier. Atomic services can be used without being installed during ability continuation.
### File Management
- User-level file encryption is supported.
- The APIs for collecting statistics by application space are added. The size of application directories at each level can be obtained.
- Application file sharing is enhanced. Files can be opened across applications.
- Application files can be backed up and restored.
- External storage devices of the file system can be mounted, unmounted, formatted, read, and written.
- The file management I/O interface is enhanced. The **listFile** API is provided for directory traversal.
### Graphics & Window
- The display frame rate in the multi-window scenario is improved.
- The property animation is enhanced, and animations can customize properties.
- The graphics development capability at the native layer is enhanced. The **SurfaceImage** interface supports buffer management, content update, and matrix conversion. The **Vsync** interface supports requesting of the next frame and callbacks. The **HardwareBuffer** interface supports requesting, releasing, obtaining, and accessing capabilities. The **NativeWindow** interface supports scaling mode setting.
- The EGL is constructed to enhance GPU adaptation for devices.
- Visual effects such as window shadow, blur, and rounded corners are added.
- More transitions are supported, such as one-take shooting, input method switching, application switching, and screen rotation.
- Window attributes can be set. The window privacy layer prevents user privacy leakage during screenshotting and screen recording.
### Multimedia
**Audio**
- Bluetooth devices can be selected for audio playback and calling.
- DTMF dial tones can be generated and played.
- The OpenSL ES basic recording APIs are supported.
- An application can query the list of available audio devices and carry device information, such as the sampling rate, number of channels, and channel mask.
- Information about existing playback streams and recording streams in the system can be queried.
**Playback**
- A local media file specified by FD can be played. Network VOD based on HTTPS and HLS is supported HDI-based H.264 hardware decoding and playback are supported.
- Audio and video encoding and decoding based on the codec HDI are supported.
**Camera**
- Users can configure the format, resolution, quality (affecting the compression ratio and definition), and location of photos taken by the camera. Users can record videos and take snapshots during video recording.
- Precise privacy protection is provided. Applications can use the camera only when they are running in the foreground (including the camera floating window scenario). System services can use the camera when they are running in the background, and third-party applications are not allowed to use the camera in silent mode in the background. System interfaces are provided for enabling and disabling the global camera switch.
**Image**: The raw and WebP image formats are supported.
### Common Event and Notification
- Applications can set the number of badges to be displayed on the home screen.
- System applications can remove sticky events. After a sticky event is removed, new subscribers will not receive a notification when the event is triggered.
- Static subscription can be enabled or disabled for system applications. After static subscription is disabled, the StaticSubscriberExtensionAbility component cannot be started by other abilities.
- The capability of **StaticSubscriberExtensionAbility** is supplemented. When the StaticSubscriberExtensionAbility component is running, the static information (such as the bundle path and bundle name) of the installation package can be obtained from the context.
### Web
- The web component can be configured, including network loading interception, font management, scroll bar, and customized interception for fetch.
- A series of web page operations are supported, including obtaining historical records, obtaining the forward and backward lists, obtaining source URLs, scrolling, and determining whether a page contains images.
- Web page event processing is supported, including reporting of page loading events and original input events.
- Interworking between web pages and applications is supported. The ArrayBuffer type can be used for message exchange.
- The web performance is enhanced. Read-only data segments of the rendering process can be shared to save memory. The pre-read dynamic library is supported for faster web page loading.
### Connectivity
- NFC card read and write capabilities are provided.
- Audio calls and video playback over Bluetooth links are supported.
- Multi-network concurrency, enhanced HTTP/HTTPS, and TLS socket ArkTS API capabilities are provided.
- Multi-network concurrency
- Socket-based route binding is supported.
- NIC-based route binding is supported.
- HTTP/HTTPS
- HTTP 2.0 is supported.
- HTTP cache is supported.
- The HTTP concurrency framework is supported.
- Gzip compression and specified format for returned data are supported.
- TLS socket
- The client can specify secure transmission options such as the certificate, key, and CA, to establish a TLS socket connection with the server.
- TLS v1.2 and TLS v1.3 are supported.
- Web socket
- Ethernet connection and network hotspot
- The cellular communication framework capability is provided (If complete cellular communication capabilities are required, the chip vendor must support the HDI):
- Dual-card management and basic capability interfaces and framework such as dual-card calling, messaging, and network search are supported.
- VoLTE voice call interfaces and framework are supported. This requires the chip vendor to implement the IMS service (including HDI).
- The IMS messaging TX and RX interfaces and framework are supported. This requires the chip vendor to implement the IMS service (including HDI).
- Cellular data roaming and cellular data self-healing interfaces and framework are supported.
- The dual-card data switching interfaces and framework are supported.
### Device Management
The location service supports privacy enhancement features such as approximate location and explicit background location.
**DeviceProfile**
The capabilities of saving, querying, and synchronizing key-value data of basic system services are provided as open APIs.
**Power supply**
- The maximum, minimum, and default luminance values of the system can be read from system parameters.
- System APIs are provided for entering and exiting the suspended state.
- APIs related to the battery level are supported.
- System APIs are provided for estimating the remaining charging time, transient current, remaining power, and total power.
- Power consumption statistics for software and hardware features such as camera, audio, calling, and short distance are supported.
- The CPU frequency, volume, and system brightness can be controlled when the device is overheating.
### Security
- System-level certificate management is supported to secure the certificate throughout the lifecycle (generation, storage, use, and destruction).
- The encryption and decryption algorithm library framework, with the OpenSSL encryption and decryption library encapsulated, is provided. Unified ArkTS APIs related to the algorithm library are also provided.
- HUKS supports certain SM2, SM3, and SM4 algorithms.
- Mutual authentication is provided for distributed devices based on account management.
### Ability Access Control
- The permission management framework is implemented for applications and system processes. The following application permission APIs are provided:
- APIs for verifying, granting, and revoking permissions
- APIs for listening for permission grant state changes
- APIs for displaying a dialog box to ask users for certain permissions
- Privacy permission management is provided for the applications that display a permission dialog box as well as the **Settings** application.
- Privacy report is provided, and APIs are provided for adding and querying permission access records and listening for permission usage status changes.
- Privacy protection is enhanced.
- When the camera is used, **systemUI** displays a dot in the upper right corner for notification purposes.
- Users can turn on or off sensitive resources (such as the microphone and camera) with a tap.
- The permissive mode is provided for SELinux.
### ArkCompiler
**Enhanced language feature**: ECMAScript 2021 in strict mode is supported.
**Compiler runtime**
- The es2abc compiler is provided to optimize the bytecode compilation performance and shorten the compilation time.
- An assembly interpreter is provided to improve the running performance of high-level programming languages.
- The host AOT compiler based on the PGO configuration file is provided to improve the high-load performance of high-level programming languages.
- The modularization capability is supported to standardize the development of complex applications.
- The hot patch mechanism is provided.
- Debugging is enhanced to support multi-instance debugging and hot reload debugging.
- CDP-based CPU profiler/heap profiler optimization, application performance optimization, and memory optimization are provided.
**Language base class library**
- The utils capabilities are enhanced. The UUID is used as a universal, unified identifier, and the buffer API is provided to support buffer reading, writing, comparison, and search.
- The basic capabilities of the TaskPool API are provided to support concurrent tasks. The task pool provides a multi-thread running environment for applications, reducing overall resource consumption and improving overall system performance.
**C/C++ toolchain**
- Toolchain upgrade: LLVM is upgraded to 12.0.0 to support the MIPS and RISC-V architectures.
- Functionality enhancement: Stack PageGuard protection, address randomization, namespace isolation, CFI, Fortify, and time zone update are supported to improve security of the C/C++ library.
- Performance optimization: The performance of frequently used functions is optimized to improve the basic performance of the C library, and the linker is optimized to improve the library loading performance.
- The locale module provides the capabilities of setting the time zone.
### Kernel
- ASLR kernel address randomization, KASAN address detection, and CFI are provided to reduce the attack surface of the system and improve kernel security.
- The security of the musl memory allocator and heap memory is enhanced to prevent against risks such as heap overflow, double-free, and UAF.
- Refined memory management is provided. The **OnMemoryLevel** feature enables applications to get a notification about the memory usage so that they can perform different processing. In addition, system resources are managed in a systematic and centralized manner, and application resources are monitored and managed in a timely manner.
- The local storage is enhanced. Performance optimization is performed for F2FS when there is little storage space available. Automatic fragment reclamation when the storage device is idle and hierarchical SSR are used to reduce system fragments and restore system performance.
### Driver
**HDF**
- Dynamic loading of kernel-mode drivers, reporting of plug-and-play events, and configuration of driver security policies are provided, laying a more stable and secure driver platform base.
- The HDI supports two channel modes: IPC invoking and pass-through invoking. You can select either of them based on service requirements.
- Automatic generation of HDI service-oriented code, template-based driver code generation, HCS macro parsing, and visualized editing configuration are supported, lowering the driver development threshold and improving the development efficiency.
- The platform driver supports user-mode interrupts. The CAN bus HDF is added, and MMC driver implementation is optimized.
**Peripheral driver model**
- The camera driver model supports mirror reflection, lens control, adding of location information for JPEG images, sensor angle query, and facial recognition metadata streams.
- Key control capabilities, such as headset access, earpiece and speaker switching, call volume setting, and call muting, are added to the ADM model of the audio module.
- The display driver model supports multi-screen management, software Vsync, compatible FrameBuffer architecture, and efficient access of different display architectures.
- The hardware codec driver model is added for the standard system, and the codec HDI 2.0 interfaces and reference implementation are provided.
- The vibrator drive model is supported, including vibration start/stop and basic vibration effect control.
- The gesture-driven model is supported, including reporting status events and device status events, enabling/disabling gestures, and function status configuration.
- The USB driver model supports the device mode and host mode. The DDK capabilities such as the RNDIS network driver in device mode are added.
- The WLAN driver anti-interference capability is supported and the optimal P2P channel selection capability is provided to continuously improve WLAN signal quality.
### Tool Improvement
**Application development on DevEco Studio**
- The diagnosis feature is provided for the application/service development environment. If the diagnosis result contains failed items, you are advised to adjust the items according to the suggestions.
- Basic templates and widget templates are provided. ArkTS widgets can be added during application development on the stage model.
- The ExtensionAbility template is provided.
- Code errors can be checked based on the new ArkUI syntax and specifications. The Code Linter feature is added for you to configure check rules and rectify errors.
- The basic quick fix capability is provided for C++ code.
- The OpenHarmony Package Manager Command-line Interface (OHPM CLI) is provided for release, installation, and dependency management of OpenHarmony shared packages. Historical projects of API version 9 can be migrated to OHPM projects.
- The closed-source HAR can be constructed, and HAR obfuscation can be configured.
- The AOT compilation mode is supported, providing high-load TS performance selection and build capabilities to improve running performance of applications.
- By default, modular compilation is enabled for projects developed on the stage model using API version 9, which effectively shortens the incremental compilation time and reduces the package size after compilation.
- Concurrent compilation is supported.
**Application debugging and tuning on DevEco Studio**
- Cross-language debugging between ArkTS/JS and C/C++ is supported. In a C/C++ project, ArkTS/JS and C/C++ can be used. C/C++ methods can be called for debugging in ArkTS/JS code.
- Hot reloading is supported. After the code is saved, the latest code can be used on the real device without restarting the application.
- Multi-packet pushing and multi-instance debugging are supported.
- Memory error detection is provided for C/C++ projects developed using API version 9.
- Fault logs can be printed for you to quickly query, locate, and export application fault information.
- The testing framework capability is enhanced. For JS/ArkTS projects using API version 8 or 9, the execution efficiency of the testing framework is greatly improved. In addition, the testing framework template is optimized to improve the readability of the template code.
For details, see [DevEco Studio Version Change History](https://developer.harmonyos.com/en/docs/documentation/doc-releases/release_notes-0000001057597449) and [DevEco Studio User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/tools_overview-0000001053582387).
**Debugging tools**
- HDC file transfer supports directory TX/RX, permission synchronization, and CS file sending within the same network segment, improving the efficiency of debugging, tuning, and automatic test.
### Testing
- The capability of filtering and executing test cases is added. Specified fields such as the case type and level can be configured in test cases. Filtered test cases can be executed using commands. For details, see [How to Use](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md#basic-process-support).
- The test case-driven execution capability is added. Different input and output data with similar test logic can be configured in auxiliary files, helping you reduce the amount of test code. For details, see [Data Driving](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md#data-driving).
- UI scenario simulation capabilities are added, such as multi-window, pinch, and fling. For details, see [API Reference](../application-dev/reference/apis/js-apis-uitest.md).
- The compatibility test specifications are added, covering six aspects of application quality requirements: UX, performance, power consumption, stability, compatibility, and security.
- The [SmartPerf-Host](https://gitee.com/openharmony-sig/smartperf/tree/master) tool provides a performance optimization platform, which provides GUI operations for detailed data analysis.
- Power consumption analysis is provided, which can be used to display the power consumption proportion by application subcategory, resource request and usage records, power consumption exception events, and association between power consumption and system status.
- Traces can be captured on the web side.
- SQL query and metrics description are supported.
- Kernel memory event analysis is supported.
- The [wukong](https://gitee.com/openharmony/ostest_wukong) tool is enhanced as follows:
- Sliding, mouse, character, system key, and control events can be injected to simulate diversified user operations.
- Users can set the total running duration and application trustlist/blocklist.
- Components can be traversed in sequence. Screenshots can be taken during the test. You can perform sleep and wake-up tests.
## Version Mapping
**Table 1** Version mapping of software and tools
| Software/Tool| Version| Remarks|
| -------- | -------- | -------- |
| OpenHarmony | 3.2 Release | NA |
| Public SDK | Ohos_sdk_public 3.2.11.9 (API Version 9 Release) | This toolkit is intended for application developers and does not contain system APIs that require system permissions. It is provided as standard in DevEco Studio.|
| (Optional) HUAWEI DevEco Studio| 3.1 Beta2 | Recommended for developing OpenHarmony applications How to obtain:<br>[Windows(64-bit)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/f3/v3/uJyuq3syQ2ak4hE1QZmAug/devecostudio-windows-3.1.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230408T013335Z&HW-CC-Expire=315360000&HW-CC-Sign=96262721EDC9B34E6F62E66884AB7AE2A94C2A7B8C28D6F7FC891F46EB211A70)<br>[Mac(X86)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/b7/v3/4z3mLQPCQR-g5KlC56SC1w/devecostudio-mac-3.1.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230408T013430Z&HW-CC-Expire=315360000&HW-CC-Sign=93E83FD1F1CE504EF8F098E08955A938FDA4E4926A2555CF1E02DC8D57210D76)<br>[Mac(ARM)](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_package_901_9/2e/v3/Fl9IY6PiQxqc3tnI2cftiw/devecostudio-mac-arm-3.1.0.400.zip?HW-CC-KV=V1&HW-CC-Date=20230408T013540Z&HW-CC-Expire=315360000&HW-CC-Sign=0906243123734033AAD34A7A005ED7671F00CAA693B6E674F81A094A0159ECCE) |
| (Optional) HUAWEI DevEco Device Tool| 3.1 Release | Recommended for developing OpenHarmony smart devices<br>[Click here](https://device.harmonyos.com/cn/develop/ide/).|
## Source Code Acquisition
### Prerequisites
1. Register your account with Gitee.
2. Register an SSH public key for access to Gitee.
3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information.
```
git config --global user.name "yourname"
git config --global user.email "your-email-address"
git config --global credential.helper store
```
4. Run the following commands to install the **repo** tool:
```
curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command.
pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests
```
### Acquiring Source Code Using the repo Tool
**Method 1 (recommended)**
Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.)
- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands:
```
repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.2-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
- Obtain the source code from the version tag, which is the same as that released with the version.
```
repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.2-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
**Method 2**
Use the **repo** tool to download the source code over HTTPS.
- Obtain the source code from the version branch. You can obtain the latest source code of the version branch, which includes the code that has been incorporated into the branch up until the time you run the following commands:
```
repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony-3.2-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
- Obtain the source code from the version tag, which is the same as that released with the version.
```
repo init -u https://gitee.com/openharmony/manifest -b refs/tags/OpenHarmony-v3.2-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
### Acquiring Source Code from Mirrors
**Table 2** Mirrors for acquiring source code
| Source Code | Version| Mirror | SHA-256 Checksum | Software Package Size|
| --------------------------------------- | ------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -------- |
| Full code base (for mini, small, and standard systems) | 3.2 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/code-v3.2-Release.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/code-v3.2-Release.tar.gz.sha256) | 21.8 GB |
| Hi3861 solution (binary) | 3.2 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_pegasus.tar.gz.sha256) | 22.9 MB |
| Hi3516 solution-LiteOS (binary)| 3.2 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_taurus_LiteOS.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_taurus_LiteOS.tar.gz.sha256) | 294.3 MB |
| Hi3516 solution-Linux (binary) | 3.2 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_taurus_Linux.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/hispark_taurus_Linux.tar.gz.sha256) | 174.3 MB |
| RK3568 standard system solution (binary) | 3.2 Release | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/dayu200_standard_arm32.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/dayu200_standard_arm32.tar.gz.sha256) | 3.9 GB |
| Public SDK package for the standard system (macOS) | 3.2.11.9 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/ohos-sdk-mac-public.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/ohos-sdk-mac-public.tar.gz.sha256) | 712.7 MB |
| Public SDK package for the standard system (macOS-M1) | 3.2.11.9 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/L2-SDK-MAC-M1-PUBLIC.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/L2-SDK-MAC-M1-PUBLIC.tar.gz.sha256) | 671.1 MB |
| Public SDK package for the standard system (Windows\Linux) | 3.2.11.9 | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/ohos-sdk-windows_linux-public.tar.gz) | [Download](https://repo.huaweicloud.com/openharmony/os/3.2-Release/ohos-sdk-windows_linux-public.tar.gz.sha256) | 1.6 GB |
## What's New
This version has the following updates to OpenHarmony 3.2 Beta5.
### API
For details about the API changes, see the following:
- [API Differences Between OpenHarmony 3.2 Release and 3.2 Beta5](api-diff/Beta5-to-v3.2-Release)
- [API Differences Between OpenHarmony 3.2 Release and 3.1 Release](api-diff/v3.2-Release)
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig_devboard/sig_devboard.md).
### Samples
**Table 3** New samples
| Subsystem| Name| Introduction| Programming Language|
| -------- | -------- | -------- | -------- |
| Accessibility| [AccessibilityExtensionAbility](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/ApplicationModels/AccessibilityExtAbility)| This sample demonstrates an application developed using the AccessibilityExtensionAbility component. It uses multiple APIs to implement quick interaction.| ArkTS |
| Enterprise management| [Enterprise Device Management ExtensionAbility](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SystemFeature/ApplicationModels/EnterpriseAdminExtensionAbility)| EnterpriseAdminExtensionAbility is a mandatory component for Mobile Device Management (MDM) applications. When developing MDM applications for enterprises, you need to inherit EnterpriseAdminExtensionAbility and implement MDM service logic in the EnterpriseAdminExtensionAbility instance. EnterpriseAdminExtensionAbility implements notifications of system management status changes and defines the callbacks that are triggered when a device administrator application is enabled or disabled or an application is installed or uninstalled.| ArkTS |
| Mission management| [WorkScheduler](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/TaskManagement/WorkScheduler)| This sample uses the APIs **\@ohos.WorkSchedulerExtensionAbility**, **\@ohos.net.http**, **\@ohos.notification**, **\@ohos.bundle**, and **\@ohos.fileio** to implement the functionalities of setting background tasks, downloading, saving, and installing update packages, and sending notifications.| ArkTS |
For more information, visit [Samples](https://gitee.com/openharmony/applications_app_samples).
## Resolved Issues
**Table 4** Resolved issues
| Issue No.| Description|
| -------- | -------- |
| I6ATXO | [RK3568] The execution result of the OpenGL test suite contains failed items during XTS test.|
| I6BJ9Z<br>I6BJ82 | alloc_file_pseudo memory leakage occurs.|
| I6BRTS | Invoking the **rdb::executeSql** interface may cause memory leakage.|
| I6AZ4T | Memory leakage exists for applications with the **\<textInput>** component.|
## Known Issues
**Table 5** Known issues
| Issue No.| Description| Impact| To Be Resolved By|
| -------- | -------- | -------- | -------- |
| I6AB3T | The duration for starting the **Contacts** application for the first time after device boost exceeds the baseline.| The contacts process is a non-resident process. When a user opens the **Contacts** application for the first time after the device is boosted, it takes a long time to start the contacts database process.| Pending|
| I6SMQA | When a user uses a browser application to open a WeiBo page and swipes the screen quickly, jitter occurs during swiping.| The content is not loaded during swiping but will be loaded quickly. User experience is affected.| 2023-05-15|
| I6TRE6 | There is a low probability that libdatashare_consumer.z.so crashes due to the com.ohos.contacts thread in the com.ohos.contacts process.| When a user exits the **Contacts** application within 600 ms after opening it, there is a low probability that the contacts process crashes. The contacts process will be automatically restarted after the crash. The impact is controllable.| 2023-04-30|
| I6SXBI | There is a low probability that a C++ crash occurs in libdistributeddata.z.so of the ohos.samples.distributedcalc process of wukong.| When a user exits the **Calculator** application within 1 second after opening it, there is a low probability that the calculator process encounters a C++ crash. The calculator process will be automatically restarted after the crash. The impact is controllable.| 2023-04-30|
| I6U00Q | When the RK3568 uses a 3.5 mm headset to play audio files, popping sounds occur.| User experience is affected, but the impact is controllable.| 2023-05-30|
| I6TNY9 | When the call log is full, the dialer cannot be hidden if a user swipes up.| User experience is affected.| 2023-04-30|
| I6TOTV | When **tabs_animation** in the **<Tabs\>** component is switched repeatedly, two colors are displayed.| The color display of the **<Tabs\>** component is affected.| 2023-04-30|
| I6TOV2 <br>I6TOYV <br>I6TOQO <br>I6TOK5 | In Wi-Fi or BLE networking, if the P2P channel opens a session whose link type is streams for 100 times, there is a possibility that the operation fails.| In Wi-Fi networking, the success rate is greater than 80%, and there is a high probability that a new round of networking is successful. The impact is controllable.| 2023-05-30|
| I6TMP3 | When a user holds an application to access image preview, swipes backwards about 150 widgets, and touches to add a widget, the widget may not be displayed on the home screen.| User experience is affected, but the impact is controllable.| 2023-04-30|
| I6B4U3 | During the pressure test, app freezing occurs on the com.ohos.launcher process.| When a large number of applications are installed (more than 40 applications in the test scenario) and the memory is small, there is a low probability that app freezing occurs. However, the home screen functions are normal and the overall functions and usage are not affected.| 2023-05-30|
| I64726 <br>I641A2 | When the **bluetooth.pairDevice** API is called, no prompt indicating successful pairing is displayed. The device is paired in silent mode, and the device can be controlled using the Bluetooth keyboard and mouse.| No prompt is displayed, but the pairing is successful. This does not affect the pairing networking of DSoftBus.| 2023-06-30|
| I6U1H9 | The **gridColOffset** attribute of **GridCol** is not included in the previewer.| The attribute display of the preview inspector is affected, but the overall effect of the previewer is not affected.| 2023-04-30|
# OpenHarmony Release Notes
## OpenHarmony 3.x Releases
- [OpenHarmony v3.2 Release (2023-04-09)](OpenHarmony-v3.2-release.md)
- [OpenHarmony v3.2 Beta5 (2023-01-31)](OpenHarmony-v3.2-beta5.md)
- [OpenHarmony v3.2 Beta4 (2022-11-30)](OpenHarmony-v3.2-beta4.md)
- [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md)
- [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md)
- [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md)
- [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md)
- [OpenHarmony v3.1.7 Release (2023-03-22)](OpenHarmony-v3.1.7-release.md)
- [OpenHarmony v3.1.6 Release (2023-01-30)](OpenHarmony-v3.1.6-release.md)
- [OpenHarmony v3.1.5 Release (2022-12-30)](OpenHarmony-v3.1.5-release.md)
- [OpenHarmony v3.1.4 Release (2022-11-02)](OpenHarmony-v3.1.4-release.md)
......
# Ability Framework Changelog
## cl.ability.1 AreaMode APIs Changed
Duplicate **AreaMode** APIs are deleted.
**Change Impact**
......@@ -24,8 +25,6 @@ import contextConstant from '@ohos.app.ability.contextConstant';
let area: contextConstant.AreaMode = contextConstant.AreaMode.EL1;
```
## cl.ability.2 killProcessesBySelf Renamed
The **killProcessesBySelf** API is renamed **killAllProcesses**.
......@@ -64,8 +63,6 @@ let appContext = context.getApplicationContext();
appContext.killAllProcesses()
```
## cl.ability.3 getProcessRunningInformation Renamed
The **getProcessRunningInformation** API is renamed **getRunningProcessInformation**.
......@@ -107,9 +104,7 @@ let appContext = context.getApplicationContext();
appContext.getRunningProcessInformation()
```
## cl.ability.4 WantConstant.Flags API Change
## cl.ability.4 WantConstant.Flags API Changed
**WantConstant.Flags** has multiple invalid flag definitions. These invalid flags are deleted.
......@@ -135,9 +130,7 @@ JS APIs in API version 9 are affected. Your application needs to adapt these API
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_NEW_MISSION | Deleted |
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Flags | FLAG_ABILITY_MISSION_TOP | Deleted |
## cl.ability.5 WantConstant.Action API Change
## cl.ability.5 WantConstant.Action API Changed
**WantConstant.Action** has multiple invalid action definitions. These invalid actions are deleted.
......@@ -157,8 +150,6 @@ JS APIs in API version 9 are affected. Your application needs to adapt these API
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_MODULE_NAME | Deleted |
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Action | DLP_PARAMS_ABILITY_NAME | Deleted |
## cl.ability.6 Caller APIs Changed
Caller APIs use the **Parcelable** and **MessageSequence** objects provided by RPC in API version 9 to replace the deprecated **Sequenceable** and **MessageParcel** object.
......@@ -266,3 +257,27 @@ Code after the change:
}
}
```
## cl.ability.7 WantConstant.Flags API Changed
The **wantConstant** API had two similar enums. Now the two enums are combined into one.
**Change Impact**
JS APIs in API version 9 are affected. Your application needs to adapt these APIs so that it can properly implement features in the SDK environment of the new version.
**Key API/Component Changes**
| Module | Class | Method/Attribute/Enum/Constant | Change Type|
| ----------------------------------- | ---------------------- | ----------------------------------- | -------- |
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Parameter | ABILITY_BACK_TO_OTHER_MISSION_STACK | Deleted |
| @ohos.app.ability.wantConstant.d.ts | wantConstant.Params | ABILITY_BACK_TO_OTHER_MISSION_STACK | Added |
**Adaptation Guide**
Use **ABILITY_BACK_TO_OTHER_MISSION_STACK** in **@ohos.app.ability.wantConstant.d.ts**.
```ts
import wantConstant from '@ohos.app.ability.wantConstant';
let backToOtherMissionStack: wantConstant.Params = wantParam.Params.ABILITY_BACK_TO_OTHER_MISSION_STACK;
```
# HUKS Changelog
## cl.huks.1 Change of the Permission for Using attestKeyItem
The **attestKeyItem** interface attests a key using a public key encapsulated based on the device certificate chain. Any arbitrary export of the device certificate increases the risks on user privacy. Therefore, certain permissions are required for using this interface.
**Change Impact**
Applications without the **ohos.permission.ACCESS_IDS** permission or the system_basic or system_core permission cannot call **attestKeyItem()**.
**Key API/Component Changes**
- Involved APIs:
attestKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult\>): void;
attestKeyItem(keyAlias: string, options: HuksOptions): Promise\<HuksReturnResult\>;
- Before change:
The AccessToken permission is verified only for the applications that pass in a tag related to **ATTESTATION_ID**.
- After change:
**attestKeyItem()** can be called only by a system application with the system_basic or system_core permission or an application with the **ohos.permission.ACCESS_IDS** permission.
**Adaptation Guide**
Applications with the system_basic or system_core permission can call **attestKeyItem()**. If an application with the normal permission needs to call **attestKeyItem()**, it must have the **ohos.permission.ACCESS_IDS** permission. For details about how to apply for the permission, see [ACL](../../../application-dev/security/accesstoken-overview.md#acl).
......@@ -4,7 +4,7 @@
任务管理相关的基本概念如下:
- AbilityRecord:系统服务侧管理一个UIAbility实例的最小单元,对应一个应用侧的UIAbility组件实例。
- AbilityRecord:系统服务侧管理一个UIAbility实例的最小单元,对应一个应用侧的UIAbility组件实例。系统服务侧管理UIAbility实例数量上限为512个。
- MissionRecord:任务管理的最小单元。一个MissionRecord中仅有一个AbilityRecord,即一个UIAbility组件实例对应一个单独的任务。
......
# ServiceExtensionAbility
- [ServiceExtensionAbility](#serviceextensionability)
- [概述](#概述)
- [生命周期](#生命周期)
- [实现一个后台服务(仅对系统应用开放)](#实现一个后台服务仅对系统应用开放)
- [开发准备](#开发准备)
- [定义IDL接口](#定义idl接口)
- [创建ServiceExtensionAbility](#创建serviceextensionability)
- [启动一个后台服务(仅对系统应用开放)](#启动一个后台服务仅对系统应用开放)
- [连接一个后台服务](#连接一个后台服务)
- [客户端与服务端通信](#客户端与服务端通信)
- [服务端对客户端身份校验](#服务端对客户端身份校验)
- [相关示例](#相关示例)
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)是SERVICE类型的ExtensionAbility组件,提供后台服务相关扩展能力。
## 概述
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)是SERVICE类型的ExtensionAbility组件,提供后台服务能力,其内部持有了一个[ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md),通过[ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md)提供了丰富的接口供外部使用。
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)可以被其他组件启动或连接,并根据调用者的请求信息在后台处理相关事务。[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)支持以启动和连接两种形式运行,系统应用可以调用[startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability)方法启动后台服务,也可以调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability)方法连接后台服务,而三方应用只能调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability)方法连接后台服务。启动和连接后台服务的差别:
本文描述中称被启动的ServiceExtensionAbility为服务端,称启动ServiceExtensionAbility的组件为客户端。
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)可以被其他组件启动或连接,并根据调用者的请求信息在后台处理相关事务。[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)支持以启动和连接两种形式运行,系统应用可以调用[startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability)方法启动后台服务,也可以调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)方法连接后台服务,而三方应用只能调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)方法连接后台服务。启动和连接后台服务的差别:
- 启动:AbilityA启动ServiceB,启动后AbilityA和ServiceB为弱关联,AbilityA退出后,ServiceB可以继续存在。
- **启动**:AbilityA启动ServiceB,启动后AbilityA和ServiceB为弱关联,AbilityA退出后,ServiceB可以继续存在。
- 连接:AbilityA绑定ServiceB,绑定后AbilityA和ServiceB为强关联,AbilityA退出后,ServiceB也一起退出。
- **连接**:AbilityA连接ServiceB,连接后AbilityA和ServiceB为强关联,AbilityA退出后,ServiceB也一起退出。
此处有如下细节需要注意:
每个类型的ExtensionAbility都有自己的Context,ServiceExtensionAbility通过[ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md)提供相关能力。本文描述中称被启动的ServiceExtensionAbility为服务端,称启动ServiceExtensionAbility的组件为客户端。
本章节将从如下场景来介绍ServiceExtensionAbility的基本使用。
- [实现一个后台服务(仅对系统应用开放)](#实现一个后台服务仅对系统应用开放)
- [启动一个后台服务(仅对系统应用开放)](#启动一个后台服务仅对系统应用开放)
- [连接一个后台服务](#连接一个后台服务)
- 若Service只通过connect的方式被拉起,那么该Service的生命周期将受客户端控制,当客户端调用一次[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)方法,将建立一个连接,当客户端退出或者调用[disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectserviceextensionability)方法,该连接将断开。当所有连接都断开后,Service将自动退出。
- Service一旦通过start的方式被拉起,将不会自动退出,系统应用可以调用[stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability)方法将Service退出。
> **说明:**
> 1. OpenHarmony当前不支持三方应用实现ServiceExtensionAbility。如果三方开发者想要实现后台处理相关事务的功能,可以使用后台任务,具体请参见[后台任务](../task-management/background-task-overview.md)。
>
> 1. OpenHarmony当前不支持三方应用实现ServiceExtensionAbility。如果三方开发者想要实现后台处理相关事务的功能,可以使用后台任务,具体请参见[后台任务](../task-management/background-task-overview.md)。
> 2. 三方应用的UIAbility组件可以通过Context连接系统提供的ServiceExtensionAbility。
>
> 3. 三方应用需要在前台获焦的情况下才能连接系统提供的ServiceExtensionAbility。
## 实现一个后台服务(仅对系统应用开放)
## 生命周期
[ServiceExtensionAbility](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md)提供了onCreate()、onRequest()、onConnect()、onDisconnect()和onDestory()生命周期回调,根据需要重写对应的回调方法。下图展示了ServiceExtensionAbility的生命周期。
......@@ -47,73 +51,108 @@
> 如果服务已创建,再次启动该ServiceExtensionAbility不会触发onCreate()回调。
- **onRequest**
当另一个组件调用startServiceExtensionAbility()方法启动该服务组件时,触发该回调。执行此方法后,服务会启动并在后台运行
当另一个组件调用[startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability)方法启动该服务组件时,触发该回调。执行此方法后,服务会启动并在后台运行。每调用一次[startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartserviceextensionability)方法均会触发该回调
- **onConnect**
当另一个组件调用connectServiceExtensionAbility()方法与该服务连接时,触发该回调。开发者在此方法中,返回一个远端代理对象(IRemoteObject),客户端拿到这个对象后可以通过这个对象与服务端进行RPC通信
当另一个组件调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)方法与该服务连接时,触发该回调。开发者在此方法中,返回一个远端代理对象(IRemoteObject),客户端拿到这个对象后可以通过这个对象与服务端进行RPC通信,同时系统侧也会将该远端代理对象(IRemoteObject)储存。后续若有组件再调用[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability)方法,系统侧会直接将所保存的远端代理对象(IRemoteObject)返回,而不再触发该回调
- **onDisconnect**
其他组件调用disconnectServiceExtensionAbility()方法时,如果没有任何其他组件连接该服务,触发该回调
当最后一个连接断开时,将触发该回调。客户端死亡或者调用[disconnectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextdisconnectserviceextensionability)方法可以使连接断开
- **onDestroy**
当不再使用服务且准备将其销毁该实例时,触发该回调。开发者可以在该回调中清理资源,如注销监听等。
## 实现一个后台服务(仅对系统应用开放)
## 开发步骤
### 开发准备
开发者在实现一个后台服务时,需要在DevEco Studio工程中手动新建一个ServiceExtensionAbility,具体步骤如下。
只有系统应用才允许实现ServiceExtensionAbility,因此开发者在开发之前需做如下准备:
1. 在工程Module对应的ets目录下,右键选择“New &gt; Directory”,新建一个目录并命名为serviceextability
- **替换Full SDK**:ServiceExtensionAbility相关接口都被标记为System-API,默认对开发者隐藏,因此需要手动从镜像站点获取Full SDK,并在DevEco Studio中替换,具体操作可参考[替换指南](../quick-start/full-sdk-switch-guide.md)
2. 在serviceextability目录,右键选择“New &gt; TypeScript File”,新建一个TypeScript文件并命名为ServiceExtAbility.ts
- **申请AllowAppUsePrivilegeExtension特权**:只有具有AllowAppUsePrivilegeExtension特权的应用才允许开发ServiceExtensionAbility,具体申请方式可参考[应用特权配置指南](../../device-dev/subsystems/subsys-app-privilege-config-guide.md)
3. 打开ServiceExtAbility.ts文件,导入[RPC通信模块](../reference/apis/js-apis-rpc.md),重载onRemoteMessageRequest()方法,接收客户端传递过来的消息,并将处理的结果返回给客户端。REQUEST_VALUE用于校验客户端发送的服务请求码。
### 定义IDL接口
```ts
import rpc from '@ohos.rpc';
ServiceExtensionAbility作为后台服务,需要向外部提供可调用的接口,开发者可将接口定义在idl文件中,并使用[IDL工具](../IDL/idl-guidelines.md)生成对应的proxy、stub文件。此处定义一个名为IIdlServiceExt.idl的文件作为示例:
const REQUEST_CODE = 99;
```cpp
interface OHOS.IIdlServiceExt {
int ProcessData([in] int data);
void InsertDataToMap([in] String key, [in] int val);
}
```
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
在DevEco Studio工程Module对应的ets目录下手动新建名为IdlServiceExt的目录,将[IDL工具](../IDL/idl-guidelines.md)生成的文件复制到该目录下,并创建一个名为idl_service_ext_impl.ts的文件,作为idl接口的实现:
// 接收客户端传递过来的消息处理,以及将处理的结果返回给客户端
onRemoteMessageRequest(code, data, reply, option) {
if (code === REQUEST_CODE) {
// 接收客户端传递过来的数据
// 客户端使用多次调用data.writeInt()写入多个数据时,服务端可以通过多次调用data.readInt()方法接收对应的数据
let optFir = data.readInt();
let optSec = data.readInt();
// 服务端将数据的处理结果返回给客户端
// 示例中为接收了两个数据,并将两个数据的求和返回给客户端
reply.writeInt(optFir + optSec);
}
return true;
}
```
├── ets
│ ├── IdlServiceExt
│ │ ├── i_idl_service_ext.ts # 生成文件
│ │ ├── idl_service_ext_proxy.ts # 生成文件
│ │ ├── idl_service_ext_stub.ts # 生成文件
│ │ ├── idl_service_ext_impl.ts # 开发者自定义文件,对idl接口的具体实现
│ └
```
idl_service_ext_impl.ts实现如下:
```ts
import {processDataCallback} from './i_idl_service_ext';
import {insertDataToMapCallback} from './i_idl_service_ext';
import IdlServiceExtStub from './idl_service_ext_stub';
const ERR_OK = 0;
const TAG: string = "[IdlServiceExtImpl]";
// 以同步或异步方式向客户端发送消息
sendRequest(code, data, reply, options) {
return null;
// 开发者需要在这个类型里对接口进行实现
export default class ServiceExtImpl extends IdlServiceExtStub {
processData(data: number, callback: processDataCallback): void {
// 开发者自行实现业务逻辑
console.info(TAG, `processData: ${data}`);
callback(ERR_OK, data + 1);
}
insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
// 开发者自行实现业务逻辑
console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`);
callback(ERR_OK);
}
}
```
### 创建ServiceExtensionAbility
在DevEco Studio工程中手动新建一个ServiceExtensionAbility,具体步骤如下:
1. 在工程Module对应的ets目录下,右键选择“New &gt; Directory”,新建一个目录并命名为ServiceExtAbility。
2. 在ServiceExtAbility目录,右键选择“New &gt; TypeScript File”,新建一个TypeScript文件并命名为ServiceExtAbility.ts。
```
├── ets
│ ├── IdlServiceExt
│ │ ├── i_idl_service_ext.ts # 生成文件
│ │ ├── idl_service_ext_proxy.ts # 生成文件
│ │ ├── idl_service_ext_stub.ts # 生成文件
│ │ ├── idl_service_ext_impl.ts # 开发者自定义文件,对idl接口的具体实现
│ ├── ServiceExtAbility
│ │ ├── ServiceExtAbility.ts
```
4. 在ServiceExtAbility.ts文件中,增加导入ServiceExtensionAbility的依赖包,自定义类继承ServiceExtensionAbility并加上需要的生命周期回调
3. 在ServiceExtAbility.ts文件中,增加导入ServiceExtensionAbility的依赖包,自定义类继承ServiceExtensionAbility并实现生命周期回调,在onConnect生命周期回调里,需要将之前定义的ServiceExtImpl对象返回
```ts
import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility';
import rpc from '@ohos.rpc';
import ServiceExtImpl from '../IdlServiceExt/idl_service_ext_impl';
const TAG: string = "[Example].[Entry].[ServiceExtAbility]";
const REQUEST_CODE = 99;
class StubTest extends rpc.RemoteObject {
// ...
}
const TAG: string = "[ServiceExtAbility]";
export default class ServiceExtAbility extends ServiceExtensionAbility {
serviceExtImpl = new ServiceExtImpl("ExtImpl");
onCreate(want) {
console.info(TAG, `onCreate, want: ${want.abilityName}`);
}
......@@ -124,7 +163,8 @@
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
// 返回ServiceExtImpl对象,客户端获取后便可以与ServiceExtensionAbility进行通信
return this.serviceExtImpl;
}
onDisconnect(want) {
......@@ -137,7 +177,7 @@
}
```
5. 在工程Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册ServiceExtensionAbility,type标签需要设置为“service”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。
4. 在工程Module对应的[module.json5配置文件](../quick-start/module-configuration-file.md)中注册ServiceExtensionAbility,type标签需要设置为“service”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。
```json
{
......@@ -150,14 +190,13 @@
"description": "service",
"type": "service",
"exported": true,
"srcEntry": "./ets/serviceextability/ServiceExtAbility.ts"
"srcEntry": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}
]
}
}
```
## 启动一个后台服务(仅对系统应用开放)
系统应用通过[startServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartserviceextensionability)方法启动一个后台服务,服务的[onRequest()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonrequest)回调就会被调用,并在该回调方法中接收到调用者传递过来的want对象。后台服务启动后,其生命周期独立于客户端,即使客户端已经销毁,该后台服务仍可继续运行。因此,后台服务需要在其工作完成时通过调用ServiceExtensionContext的[terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)来自行停止,或者由另一个组件调用[stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability)来将其停止。
......@@ -206,17 +245,13 @@
})
```
> **说明:**
> 后台服务可以在后台长期运行,为了避免资源浪费,需要对后台服务的生命周期进行管理。即一个后台服务完成了请求方的任务,需要及时销毁。销毁已启动的后台服务有两种方式:
>
> - 后台服务自身调用[terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)方法来自行停止。
>
> - 由其他组件调用[stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability)方法来停止。
>
> 调用[terminateSelf()](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextterminateself)或[stopServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstopserviceextensionability)方法之后,系统将销毁后台服务。
## 连接一个后台服务
系统应用或者三方应用可以通过[connectServiceExtensionAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextconnectserviceextensionability)连接一个服务(在Want对象中指定启动的目标服务),服务的[onConnect()](../reference/apis/js-apis-app-ability-serviceExtensionAbility.md#serviceextensionabilityonconnect)就会被调用,并在该回调方法中接收到调用者传递过来的Want对象,从而建立长连接。
......@@ -226,14 +261,54 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
- 使用connectServiceExtensionAbility()建立与后台服务的连接。示例中的context的获取方式请参见[获取UIAbility的上下文信息](uiability-usage.md#获取uiability的上下文信息)
```ts
import rpc from '@ohos.rpc';
const REQUEST_CODE = 99;
let want = {
"deviceId": "",
"bundleName": "com.example.myapplication",
"abilityName": "ServiceExtAbility"
};
let options = {
onConnect(elementName, remote) {
/* 此处的入参remote为ServiceExtensionAbility在onConnect生命周期回调中返回的对象,
* 开发者通过这个对象便可以与ServiceExtensionAbility进行通信,具体通信方式见下文
*/
console.info('onConnect callback');
if (remote === null) {
console.info(`onConnect remote is null`);
return;
}
},
onDisconnect(elementName) {
console.info('onDisconnect callback')
},
onFailed(code) {
console.info('onFailed callback')
}
}
// 建立连接后返回的Id需要保存下来,在解绑服务时需要作为参数传入
let connectionId = this.context.connectServiceExtensionAbility(want, options);
```
- 使用disconnectServiceExtensionAbility()断开与后台服务的连接。
```ts
// connectionId为调用connectServiceExtensionAbility接口时的返回值,需开发者自行维护
this.context.disconnectServiceExtensionAbility(connectionId).then((data) => {
console.info('disconnectServiceExtensionAbility success');
}).catch((error) => {
console.error('disconnectServiceExtensionAbility failed');
})
```
## 客户端与服务端通信
客户端在onConnect()中获取到[rpc.RemoteObject](../reference/apis/js-apis-rpc.md#iremoteobject)对象后便可与Service进行通信,有如下两种方式:
- 使用服务端提供的IDL接口进行通信(推荐)
```ts
// 客户端需要将服务端对外提供的idl_service_ext_proxy.ts导入到本地工程中
import IdlServiceExtProxy from '../IdlServiceExt/idl_service_ext_proxy';
let options = {
onConnect(elementName, remote) {
console.info('onConnect callback');
......@@ -241,23 +316,54 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
console.info(`onConnect remote is null`);
return;
}
let serviceExtProxy = new IdlServiceExtProxy(remote);
// 通过接口调用的方式进行通信,屏蔽了RPC通信的细节,简洁明了
serviceExtProxy.processData(1, (errorCode, retVal) => {
console.log(`processData, errorCode: ${errorCode}, retVal: ${retVal}`);
});
serviceExtProxy.insertDataToMap('theKey', 1, (errorCode) => {
console.log(`insertDataToMap, errorCode: ${errorCode}`);
})
},
onDisconnect(elementName) {
console.info('onDisconnect callback')
},
onFailed(code) {
console.info('onFailed callback')
}
}
```
- 直接使用[sendMessageRequest](../reference/apis/js-apis-rpc.md#sendmessagerequest9)接口向服务端发送消息(不推荐)
```ts
import rpc from '@ohos.rpc';
const REQUEST_CODE = 1;
let options = {
onConnect(elementName, remote) {
console.info('onConnect callback');
if (remote === null) {
console.info(`onConnect remote is null`);
return;
}
// 直接调用rpc的接口向服务端发送消息,客户端需自行对入参进行序列化,对返回值进行反序列化,操作繁琐
let option = new rpc.MessageOption();
let data = new rpc.MessageParcel();
let reply = new rpc.MessageParcel();
let data = new rpc.MessageSequence();
let reply = new rpc.MessageSequence();
data.writeInt(100);
data.writeInt(200);
// @param code 表示客户端发送的服务请求代码。
// @param data 表示客户端发送的{@link MessageParcel}对象。
// @param data 表示客户端发送的{@link MessageSequence}对象。
// @param reply 表示远程服务发送的响应消息对象。
// @param options 指示操作是同步的还是异步的。
//
// @return 如果操作成功返回{@code true}; 否则返回 {@code false}。
remote.sendRequest(REQUEST_CODE, data, reply, option).then((ret) => {
remote.sendMessageRequest(REQUEST_CODE, data, reply, option).then((ret) => {
let msg = reply.readInt();
console.info(`sendRequest ret:${ret} msg:${msg}`);
console.info(`sendMessageRequest ret:${ret} msg:${msg}`);
}).catch((error) => {
console.info('sendRequest failed');
console.info('sendMessageRequest failed');
});
},
onDisconnect(elementName) {
......@@ -267,21 +373,92 @@ ServiceExtensionAbility服务组件在[onConnect()](../reference/apis/js-apis-ap
console.info('onFailed callback')
}
}
// 建立连接后返回的Id需要保存下来,在解绑服务时需要作为参数传入
let connectionId = this.context.connectServiceExtensionAbility(want, options);
```
- 使用disconnectServiceExtensionAbility()断开与后台服务的连接。
## 服务端对客户端身份校验
部分开发者需要使用ServiceExtension提供一些较为敏感的服务,因此需要对客户端身份进行校验,开发者可在IDL接口的stub端进行校验,IDL接口实现详见上文[定义IDL接口](#定义idl接口),此处推荐两种校验方式:
- **通过callerUid识别客户端应用**
通过调用[getCallingUid()](../reference/apis/js-apis-rpc.md#getcallinguid)接口获取客户端的uid,再调用[getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid)接口获取uid对应的bundleName,从而识别客户端身份。此处需要注意的是[getBundleNameByUid()](../reference/apis/js-apis-bundleManager.md#bundlemanagergetbundlenamebyuid)是一个异步接口,因此服务端无法将校验结果返回给客户端,这种校验方式适合客户端向服务端发起执行异步任务请求的场景,示例代码如下:
```ts
let connectionId = 1 // 在通过connectServiceExtensionAbility绑定服务时返回的Id
this.context.disconnectServiceExtensionAbility(connectionId).then((data) => {
console.info('disconnectServiceExtensionAbility success');
}).catch((error) => {
console.error('disconnectServiceExtensionAbility failed');
})
import rpc from '@ohos.rpc';
import bundleManager from '@ohos.bundle.bundleManager';
import {processDataCallback} from './i_idl_service_ext';
import {insertDataToMapCallback} from './i_idl_service_ext';
import IdlServiceExtStub from './idl_service_ext_stub';
const ERR_OK = 0;
const ERR_DENY = -1;
const TAG: string = "[IdlServiceExtImpl]";
export default class ServiceExtImpl extends IdlServiceExtStub {
processData(data: number, callback: processDataCallback): void {
console.info(TAG, `processData: ${data}`);
let callerUid = rpc.IPCSkeleton.getCallingUid();
bundleManager.getBundleNameByUid(callerUid).then((callerBundleName) => {
console.info(TAG, 'getBundleNameByUid: ' + callerBundleName);
// 对客户端包名进行识别
if (callerBundleName != 'com.example.connectextapp') { // 识别不通过
console.info(TAG, 'The caller bundle is not in whitelist, reject');
return;
}
// 识别通过,执行正常业务逻辑
}).catch(err => {
console.info(TAG, 'getBundleNameByUid failed: ' + err.message);
});
}
insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
// 开发者自行实现业务逻辑
console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`);
callback(ERR_OK);
}
}
```
- **通过callerTokenId对客户端进行鉴权**
通过调用[getCallingTokenId()](../reference/apis/js-apis-rpc.md#getcallingtokenid)接口获取客户端的tokenID,再调用[verifyAccessTokenSync()](../reference/apis/js-apis-abilityAccessCtrl.md#verifyaccesstokensync)接口判断客户端是否有某个具体权限,由于OpenHarmony当前不支持自定义权限,因此只能校验当前[系统所定义的权限](../security/permission-list.md)。示例代码如下:
```ts
import rpc from '@ohos.rpc';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import {processDataCallback} from './i_idl_service_ext';
import {insertDataToMapCallback} from './i_idl_service_ext';
import IdlServiceExtStub from './idl_service_ext_stub';
const ERR_OK = 0;
const ERR_DENY = -1;
const TAG: string = "[IdlServiceExtImpl]";
export default class ServiceExtImpl extends IdlServiceExtStub {
processData(data: number, callback: processDataCallback): void {
console.info(TAG, `processData: ${data}`);
let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();
let accessManger = abilityAccessCtrl.createAtManager();
// 所校验的具体权限由开发者自行选择,此处ohos.permission.SET_WALLPAPER只作为示例
let grantStatus =
accessManger.verifyAccessTokenSync(callerTokenId, "ohos.permission.SET_WALLPAPER");
if (grantStatus === abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
console.info(TAG, `PERMISSION_DENIED`);
callback(ERR_DENY, data); // 鉴权失败,返回错误
return;
}
callback(ERR_OK, data + 1); // 鉴权通过,执行正常业务逻辑
}
insertDataToMap(key: string, val: number, callback: insertDataToMapCallback): void {
// 开发者自行实现业务逻辑
console.log(TAG, `insertDataToMap, key: ${key} val: ${val}`);
callback(ERR_OK);
}
}
```
## 相关示例
......
......@@ -12,7 +12,7 @@
文件URI的格式为:
格式为file://&lt;bundleName&gt;/&lt;path&gt;/\#networkid=&lt;networkid&gt;
格式为file://&lt;bundleName&gt;/&lt;path&gt;
- file:文件URI的标志。
......@@ -20,8 +20,6 @@
- path:文件资源在应用沙箱中的路径。
- networkid:为可选项,用于分布式文件系统标志该文件资源所归属的设备;当不需要区分文件位置时,该选项可不填写。
## 分享文件给其他应用
在分享文件给其他应用前,开发者需要先[获取应用文件路径](../application-models/application-context-stage.md#获取应用开发路径)
......
......@@ -8,7 +8,7 @@
- [AudioRenderer](using-audiorenderer-for-playback.md):用于音频输出的的ArkTS/JS API,仅支持PCM格式,需要应用需要持续写入音频数据进行工作。应用可以在输入前添加数据预处理,如设定音频文件的采样率、位宽等,要求开发者具备音频处理的基础知识,适用于更专业、更多样化的媒体播放应用开发。
- [OpenSLES](using-opensl-es-for-playback.md):一套跨平台标准化的音频Native API,目前阶段唯一的音频类Native API,同样提供音频输出能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输出功能的播放应用使用。
- [OpenSL ES](using-opensl-es-for-playback.md):一套跨平台标准化的音频Native API,目前阶段唯一的音频类Native API,同样提供音频输出能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输出功能的播放应用使用。
- [TonePlayer](using-toneplayer-for-playback.md):拨号和回铃音播放ArkTS/JS API,只能在固定的类型范围内选择播放内容,无需输入媒体资源或音频数据,适用于拨号盘按键和通话回铃音的特定场景。该功能当前仅对系统应用开放。
......
......@@ -8,7 +8,7 @@
- [AudioCapturer](using-audiocapturer-for-recording.md):用于音频输入的的ArkTS/JS API,仅支持PCM格式,需要应用持续读取音频数据进行工作。应用可以在音频输出后添加数据处理,要求开发者具备音频处理的基础知识,适用于更专业、更多样化的媒体录制应用开发。
- [OpenSLES](using-opensl-es-for-recording.md):一套跨平台标准化的音频Native API,目前阶段唯一的音频类Native API,同样提供音频输入原子能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输入功能的录音应用使用。
- [OpenSL ES](using-opensl-es-for-recording.md):一套跨平台标准化的音频Native API,目前阶段唯一的音频类Native API,同样提供音频输入原子能力,仅支持PCM格式,适用于从其他嵌入式平台移植,或依赖在Native层实现音频输入功能的录音应用使用。
## 开发音频录制应用须知
......
......@@ -2,7 +2,7 @@
## 媒体系统架构
媒体系统提供用户视觉、听觉信息的处理能力,如音视频信息的采集、压缩存储、解压播放等。 在操作系统实现中,通常基于不同的媒体信息处理内容,将媒体划分为音频子系统、视频子系统(也称播放录制子系统)、相机子系统、图片子系统或服务等。
媒体系统提供用户视觉、听觉信息的处理能力,如音视频信息的采集、压缩存储、解压播放等。 在操作系统实现中,通常基于不同的媒体信息处理内容,将媒体划分为不同的模块,包括:音频、视频(也称播放录制)、相机、图片等。
如下图所示,媒体系统面向应用开发提供音视频应用、相机应用、图库应用的编程框架接口;面向设备开发提供对接不同硬件芯片适配加速功能;中间以服务形态提供媒体核心功能和管理机制。
......@@ -10,10 +10,10 @@
![Media system framework](figures/media-system-framework.png)
- 音频子系统(audio):提供音量管理、音频路由管理、混音管理接口与服务。
- 音频(audio):提供音量管理、音频路由管理、混音管理接口与服务。
- 视频子系统(media):提供音视频解压播放、压缩录制接口与服务。
- 视频(media):提供音视频解压播放、压缩录制接口与服务。
- 相机子系统(camera):提供精确控制相机镜头,采集视觉信息的接口与服务。
- 相机(camera):提供精确控制相机镜头,采集视觉信息的接口与服务。
- 图片子系统(image):提供图片编解码、图片处理接口与服务。
- 图片(image):提供图片编解码、图片处理接口与服务。
......@@ -2,7 +2,7 @@
HAR(Harmony Archive)是静态共享包,可以包含代码、C++库、资源和配置文件。通过HAR可以实现多个模块或多个工程共享ArkUI组件、资源等相关代码。HAR不同于HAP,不能独立安装运行在设备上,只能作为应用模块的依赖项被引用。
## 创建HAR模块
HAR对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/ohos-adding-deleting-module-0000001218760594-V3),可以通过DevEco Studio创建一个HAR模块。HAR模块默认不开启混淆能力,开启混淆能力,需要把HAR模块的build-profile.json5文件中的artifactType字段设置为obfuscation,配置如下所示:
HAR对应DevEco Studio工程中的“Library”类型的[Module](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/add_new_module-0000001053223741-V3),可以通过DevEco Studio创建一个HAR模块。HAR模块默认不开启混淆能力,开启混淆能力,需要把HAR模块的build-profile.json5文件中的artifactType字段设置为obfuscation,配置如下所示:
```json
{
......
......@@ -61,7 +61,8 @@
]
},
"targetModuleName": "feature",
"targetPriority": 50
"targetPriority": 50,
"isolationMode": "nonisolationFirst"
}
```
......@@ -94,6 +95,7 @@ module.json5配置文件包含以下标签。
| targetModuleName | 标识当前包所指定的目标module, 标签值采用字符串表示(最大长度31个字节),该名称在指定的应用中要唯一。|字符串|该标签可缺省,缺省时当前包为非overlay特性的Module。|
| targetPriority | 标识当前Module的优先级, 当targetModuleName字段配置之后,当前Module为overlay特征的Module, 该标签的额取值范围为1~100|数值|该标签可缺省, 缺省值为1。|
| [proxyDatas](#proxydatas标签) | 标识当前Module提供的数据代理列表。| 对象数组 | 该标签可缺省,缺省值为空。|
| isolationMode | 标识当前Module的多进程配置项。类型有4种,分别:<br/>-&nbsp;nonisolationFirst:优先在非独立进程中运行。<br/>-&nbsp;isolationFirst:优先在独立进程中运行。<br/>-&nbsp;isolationOnly:只在独立进程中运行。<br/>-&nbsp;nonisolationOnly:只在非独立进程中运行。 |字符串|该标签可缺省, 缺省值为nonisolationFirst。|
## deviceTypes标签
......
......@@ -46,7 +46,7 @@ $ diff.exe -s Example.z.so -d Example.z.so -p Example.z.so.diff
基于上述的patch.json、.abc快速修复文件和.so快速修复文件,可以通过本地OpenHarmony SDK路径的`toolchains`文件夹下的`app_packing_tool.jar`生成.hqf包,执行打包命令如下:
```shell
$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-patch patchs --out-path entry-default-unsigned.hqf --force true
$ java -jar app_packing_tool.jar --mode hqf --json-path patch.json --lib-path libs --ets-path patchs --out-path entry-default-unsigned.hqf --force true
```
命令行参数介绍:
......
......@@ -35,9 +35,9 @@
![zh-cn_image_0000001364054489](figures/zh-cn_image_0000001364054489.png)
- **AppStore > app.json5**:应用的全局配置信息。
- **AppScope > app.json5**:应用的全局配置信息。
- **entry**:OpenHarmony工程模块,编译构建生成一个[HAP](../../glossary.md#hap)包。
- **oh_modules**:用于存放三方库依赖信息。关于原npm工程适配ohpm操作,请参考[历史工程手动迁移](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212)
- **oh_modules**:用于存放三方库依赖信息。关于原npm工程适配ohpm操作,请参考[历史工程手动迁移](https://developer.harmonyos.com/cn/docs/documentation/doc-guides-V3/project_overview-0000001053822398-V3#section108143331212)
- **src &gt; main &gt; ets**:用于存放ArkTS源码。
- **src &gt; main &gt; ets &gt; entryability**:应用/服务的入口。
- **src &gt; main &gt; ets &gt; pages**:应用/服务包含的页面。
......
......@@ -798,102 +798,102 @@ Wi-Fi P2P群组信息已更改。
- 值:usual.event.DOMAIN_ACCOUNT_STATUS_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIM_STATE_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIM_STATE_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示SIM卡状态更新。
- 值:usual.event.SIM_STATE_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SMS_RECEIVED_COMPLETED<sup>10+<sup>
## [COMMON_EVENT_SMS_RECEIVED_COMPLETED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示短信接收完成。
- 值:usual.event.SMS_RECEIVED_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
## COMMON_EVENT_SMS_EMERGENCY_CB_RECEIVE_COMPLETED<sup>10+<sup>
## [COMMON_EVENT_SMS_EMERGENCY_CB_RECEIVE_COMPLETED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示紧急小区广播短信接收完成。
- 值:usual.event.SMS_EMERGENCY_CB_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
## COMMON_EVENT_SMS_CB_RECEIVE_COMPLETED<sup>10+<sup>
## [COMMON_EVENT_SMS_CB_RECEIVE_COMPLETED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示小区广播短信接收完成。
- 值:usual.event.SMS_CB_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
## COMMON_EVENT_STK_COMMAND<sup>10+<sup>
## [COMMON_EVENT_STK_COMMAND<sup>10+<sup>](./common_event/commonEvent-telephony.md)
(预留事件,暂未支持)提示STK命令。
- 值:usual.event.STK_COMMAND
- 订阅者所需权限:无
## COMMON_EVENT_STK_SESSION_END<sup>10+<sup>
## [COMMON_EVENT_STK_SESSION_END<sup>10+<sup>](./common_event/commonEvent-telephony.md)
(预留事件,暂未支持)提示STK会话结束。
- 值:usual.event.STK_SESSION_END
- 订阅者所需权限:无
## COMMON_EVENT_STK_CARD_STATE_CHANGED<sup>10+<sup>
## [COMMON_EVENT_STK_CARD_STATE_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
(预留事件,暂未支持)提示STK卡状态已更新。
- 值:usual.event.STK_CARD_STATE_CHANGED
- 订阅者所需权限:ohos.permission.
- 订阅者所需权限:
## COMMON_EVENT_STK_ALPHA_IDENTIFIER<sup>10+<sup>
## [COMMON_EVENT_STK_ALPHA_IDENTIFIER<sup>10+<sup>](./common_event/commonEvent-telephony.md)
(预留事件,暂未支持)提示STK ALPHA标识符。
- 值:usual.event.STK_ALPHA_IDENTIFIER
- 订阅者所需权限:无
## COMMON_EVENT_SMS_WAPPUSH_RECEIVE_COMPLETED<sup>10+<sup>
## [COMMON_EVENT_SMS_WAPPUSH_RECEIVE_COMPLETED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示服务信息短信接收完成。
- 值:usual.event.SMS_WAPPUSH_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
## COMMON_EVENT_OPERATOR_CONFIG_CHANGED<sup>10+<sup>
## [COMMON_EVENT_OPERATOR_CONFIG_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示运营商配置已更新。
- 值:usual.event.OPERATOR_CONFIG_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示SIM卡默认短信主卡已更新。
- 值:usual.event.DEFAULT_SMS_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示SIM卡默认数据主卡已更新。
- 值:usual.event.DEFAULT_DATA_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示SIM卡默认主卡已更新。
- 值:usual.event.SIM.DEFAULT_MAIN_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示SIM卡默认语音主卡已更新。
- 值:usual.event.DEFAULT_VOICE_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_CALL_STATE_CHANGED<sup>10+<sup>
## [COMMON_EVENT_CALL_STATE_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示呼叫状态更新。
- 值:usual.event.CALL_STATE_CHANGED
- 订阅者所需权限:ohos.permission.GET_TELEPHONY_STATE
## COMMON_EVENT_CELLULAR_DATA_STATE_CHANGED<sup>10+<sup>
## [COMMON_EVENT_CELLULAR_DATA_STATE_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示蜂窝数据状态更新。
- 值:usual.event.CELLULAR_DATA_STATE_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_NETWORK_STATE_CHANGED<sup>10+<sup>
## [COMMON_EVENT_NETWORK_STATE_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示网络状态更新。
- 值:usual.event.NETWORK_STATE_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_SIGNAL_INFO_CHANGED<sup>10+<sup>
## [COMMON_EVENT_SIGNAL_INFO_CHANGED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示信号信息更新。
- 值:usual.event.SIGNAL_INFO_CHANGED
- 订阅者所需权限:无
## COMMON_EVENT_INCOMING_CALL_MISSED<sup>10+<sup>
## [COMMON_EVENT_INCOMING_CALL_MISSED<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示未接来电。
- 值:usual.event.INCOMING_CALL_MISSED
- 订阅者所需权限:ohos.permission.GET_TELEPHONY_STATE
## COMMON_EVENT_RADIO_STATE_CHANGE<sup>10+<sup>
## [COMMON_EVENT_RADIO_STATE_CHANGE<sup>10+<sup>](./common_event/commonEvent-telephony.md)
提示设备modem上下电状态变化。
- 值:usual.event.RADIO_STATE_CHANGE
......
# 电话服务子系统公共事件定义
电话服务子系统面向应用发布如下系统公共事件。
## COMMON_EVENT_SIM_STATE_CHANGED
提示SIM卡状态更新。
- 值:usual.event.SIM_STATE_CHANGED
- 订阅者所需权限:无
在设备上面的SIM卡状态发生变化时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SMS_RECEIVED_COMPLETED
提示短信接收完成。
- 值:usual.event.SMS_RECEIVED_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
在设备接收到短信时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SMS_EMERGENCY_CB_RECEIVE_COMPLETED
提示紧急小区广播短信接收完成。
- 值:usual.event.SMS_EMERGENCY_CB_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
在设备接收到紧急小区广播短信时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SMS_CB_RECEIVE_COMPLETED
提示小区广播短信接收完成。
- 值:usual.event.SMS_CB_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
在设备接收到小区广播短信时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_STK_COMMAND
(预留事件,暂未支持)提示STK命令。
- 值:usual.event.STK_COMMAND
- 订阅者所需权限:无
在发送STK命令时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_STK_SESSION_END
(预留事件,暂未支持)提示STK会话结束。
- 值:usual.event.STK_SESSION_END
- 订阅者所需权限:无
在STK会话结束时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_STK_CARD_STATE_CHANGED
(预留事件,暂未支持)提示STK卡状态已更新。
- 值:usual.event.STK_CARD_STATE_CHANGED
- 订阅者所需权限:无
在STK卡状态更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_STK_ALPHA_IDENTIFIER
(预留事件,暂未支持)提示STK ALPHA标识符。
- 值:usual.event.STK_ALPHA_IDENTIFIER
- 订阅者所需权限:无
在发送STK ALPHA标识符时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SMS_WAPPUSH_RECEIVE_COMPLETED
提示服务信息短信接收完成。
- 值:usual.event.SMS_WAPPUSH_RECEIVE_COMPLETED
- 订阅者所需权限:ohos.permission.RECEIVE_SMS
在设备接收短信完成时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_OPERATOR_CONFIG_CHANGED
提示运营商配置已更新。
- 值:usual.event.OPERATOR_CONFIG_CHANGED
- 订阅者所需权限:无
在设备运营商配置更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED
提示SIM卡默认短信主卡已更新。
- 值:usual.event.DEFAULT_SMS_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
在设备SIM卡默认短信主卡更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED
提示SIM卡默认数据主卡已更新。
- 值:usual.event.DEFAULT_DATA_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
在设备SIM卡默认数据主卡更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED
提示SIM卡默认主卡已更新。
- 值:usual.event.SIM.DEFAULT_MAIN_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
在设备SIM卡默认主卡更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED
提示SIM卡默认语音主卡已更新。
- 值:usual.event.DEFAULT_VOICE_SUBSCRIPTION_CHANGED
- 订阅者所需权限:无
在设备SIM卡默认语音主卡更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_CALL_STATE_CHANGED
提示呼叫状态更新。
- 值:usual.event.CALL_STATE_CHANGED
- 订阅者所需权限:ohos.permission.GET_TELEPHONY_STATE
在设备呼叫状态更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_CELLULAR_DATA_STATE_CHANGED
提示蜂窝数据状态更新。
- 值:usual.event.CELLULAR_DATA_STATE_CHANGED
- 订阅者所需权限:无
在设备蜂窝数据状态更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_NETWORK_STATE_CHANGED
提示网络状态更新。
- 值:usual.event.NETWORK_STATE_CHANGED
- 订阅者所需权限:无
在设备网络状态更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_SIGNAL_INFO_CHANGED
提示信号信息更新。
- 值:usual.event.SIGNAL_INFO_CHANGED
- 订阅者所需权限:无
在设备信号信息更新时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_INCOMING_CALL_MISSED
提示未接来电。
- 值:usual.event.INCOMING_CALL_MISSED
- 订阅者所需权限:ohos.permission.GET_TELEPHONY_STATE
在设备有未接来电时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_RADIO_STATE_CHANGE
提示设备modem上下电状态变化。
- 值:usual.event.RADIO_STATE_CHANGE
- 订阅者所需权限:无
在设备modem上下电状态变化时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_DIALER_SPECIAL_CODE
提示暗码发送成功。
- 值:usual.event.DIALER_SPECIAL_CODE
- 订阅者所需权限:无
在设备上发送暗码成功时,将会触发事件通知服务发布该系统公共事件。
## COMMON_EVENT_AUDIO_QUALITY_CHANGE
提示音频质量发生变化。
- 值:usual.event.AUDIO_QUALITY_CHANGE
- 订阅者所需权限:无
在设备音频质量发送变化时,将会触发事件通知服务发布该系统公共事件。
......@@ -400,7 +400,6 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\<
| 错误码ID | 错误信息 |
| -------- | ------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**示例:**
......@@ -445,7 +444,7 @@ getBundleInfo(bundleName: string, bundleFlags: [number](#bundleflag), userId?: n
| ----------- | ------ | ---- | ---------------------------- |
| bundleName | string | 是 | 表示要查询的应用Bundle名称。 |
| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息。 |
| userId | number | 否 | 表示用户ID。 |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -586,7 +585,6 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), cal
| 错误码ID | 错误信息 |
| -------- | --------------------------------------|
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**示例:**
......@@ -630,7 +628,7 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use
| ---------- | ------ | ---- | ---------------------------- |
| bundleName | string | 是 | 表示要查询的应用Bundle名称。 |
| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息。 |
| userId | number | 否 | 表示用户ID。 |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -736,14 +734,6 @@ getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback<Arr
| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息。 |
| callback | AsyncCallback<Array\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\<BundleInfo>;否则为错误对象。 |
**错误码:**
错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)
| 错误码ID | 错误信息 |
| -------- | ---------------------------------- |
| 17700004 | The specified user ID is not found. |
**示例:**
```ts
......@@ -781,7 +771,7 @@ getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise<A
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | -------------------------------------------------- |
| bundleFlags | [number](#bundleflag) | 是 | 指定返回的BundleInfo所包含的信息。 |
| userId | number | 否 | 表示用户ID |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -883,14 +873,6 @@ getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallb
| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息。 |
| callback | AsyncCallback<Array\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)>> | 是 | 回调函数,当获取成功时,err为null,data为获取到的Array\<ApplicationInfo>;否则为错误对象。 |
**错误码:**
错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)
| 错误码ID | 错误信息 |
| -------- | ---------------------------------- |
| 17700004 | The specified user ID is not found. |
**示例:**
```ts
......@@ -928,7 +910,7 @@ getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Pr
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------ | ---- | ---------------------------------------------------------- |
| appFlags | [number](#applicationflag) | 是 | 指定返回的ApplicationInfo所包含的信息。 |
| userId | number | 否 | 表示用户ID |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -1049,7 +1031,6 @@ queryAbilityInfo(want: Want, abilityFlags: [number](#abilityflag), callback: Asy
| -------- | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700003 | The specified ability is not found. |
| 17700004 | The specified userId is invalid. |
| 17700026 | The specified bundle is disabled. |
| 17700029 | The specified ability is disabled. |
......@@ -1095,7 +1076,7 @@ queryAbilityInfo(want: Want, abilityFlags: [number](#abilityflag), userId?: numb
| ------------ | ------ | ---- | ------------------------------------------------------- |
| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 |
| abilityFlags | [number](#abilityflag) | 是 | 表示指定返回的AbilityInfo所包含的信息。 |
| userId | number | 否 | 表示用户ID |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -1246,7 +1227,6 @@ queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityTyp
| -------- | -------------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700003 | The specified extensionAbility is not found. |
| 17700004 | The specified userId is invalid. |
| 17700026 | The specified bundle is disabled. |
**示例:**
......@@ -1293,7 +1273,7 @@ queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityTyp
| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 |
| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型。 |
| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志。 |
| userId | number | 否 | 表示用户ID。 |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -2170,7 +2150,6 @@ getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\<Want>): void
| 错误码ID | 错误信息 |
| -------- | --------------------------------------|
| 17700001 | The specified bundleName is not found. |
| 17700004 | The specified user ID is not found. |
| 17700026 | The specified bundle is disabled. |
**示例:**
......@@ -2210,7 +2189,7 @@ getLaunchWantForBundle(bundleName: string, userId?: number): Promise\<Want>;
| 参数名 | 类型 | 必填 | 说明 |
| ---------- | ------ | ---- | ------------------------- |
| bundleName | string | 是 | 表示应用程序的bundleName。 |
| userId | number | 否 | 表示用户ID |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
**返回值:**
......@@ -2312,7 +2291,7 @@ getProfileByAbility(moduleName: string, abilityName: string, metadataName?: stri
| ------------ | ------ | ---- | -------------------------- |
| moduleName | string | 是 | 表示应用程序的moduleName。 |
| abilityName | string | 是 | 表示应用程序的abilityName。 |
| metadataName | string | 否 | 表示应用程序的metadataName。 |
| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 |
**返回值:**
......@@ -2432,7 +2411,7 @@ getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, m
| -------------------- | ------ | ---- | ---------------------------------- |
| moduleName | string | 是 | 表示应用程序的moduleName。 |
| extensionAbilityName | string | 是 | 表示应用程序的extensionAbilityName。 |
| metadataName | string | 否 | 表示应用程序的metadataName。 |
| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 |
**返回值:**
......@@ -3185,7 +3164,7 @@ getAppProvisionInfo(bundleName: string, userId?: number): Promise\<[AppProvision
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 指定的bundleName。 |
| userId | number | 否 | 指定的用户ID,可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 |
| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0,可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 |
**返回值:**
......
......@@ -81,7 +81,7 @@ off(type: BundleChangedEvent, callback?: Callback\<BundleChangedInfo>): void;
| 参数名 | 类型 | 必填 | 说明 |
| ---------------------------- | -------- | ---- | ---------------------------------------------------------- |
| type| BundleChangedEvent| 是 | 注销监听的事件类型。 |
| callback | callback\<BundleChangedInfo>| 否 | 注销监听的回调函数,当为空时表示注销当前事件的所有callback。 |
| callback | callback\<BundleChangedInfo>| 否 | 注销监听的回调函数,默认值:注销当前事件的所有callback。 |
**示例:**
......
......@@ -203,7 +203,7 @@ Curves.responsiveSpringMotion() // 创建一个默认弹性跟手动画曲线
```
##  Curves.interpolatingSpringCurve<sup>10+</sup>
##  Curves.interpolatingSpring<sup>10+</sup>
interpolatingSpring(velocity: number, mass: number, stiffness: number, damping: number):ICurve
......@@ -215,7 +215,7 @@ interpolatingSpring(velocity: number, mass: number, stiffness: number, damping:
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ----- |
| velocity | number | 是 | 初始速度。外部因素对弹性动效产生的影响参数,目的是保证对象从之前的运动状态平滑过渡到弹性动效。该速度是归一化速度,其值等于动画开始时的实际速度除以动画属性改变值。 |
| velocity | number | 是 | 初始速度。外部因素对弹性动效产生的影响参数,目的是保证对象从之前的运动状态平滑过渡到弹性动效。该速度是归一化速度,其值等于动画开始时的实际速度除以动画属性改变值。 |
| mass | number | 是 | 质量。弹性系统的受力对象,会对弹性系统产生惯性影响。质量越大,震荡的幅度越大,恢复到平衡位置的速度越慢。 |
| stiffness | number | 是 | 刚度。表示物体抵抗施加的力而形变的程度。刚度越大,抵抗变形的能力越强,恢复到平衡位置的速度越快。 |
| damping | number | 是 | 阻尼。是一个纯数,无真实的物理意义,用于描述系统在受到扰动后震荡及衰减的情形。阻尼越大,弹性运动的震荡次数越少、震荡幅度越小。 |
......@@ -334,7 +334,7 @@ spring(velocity: number, mass: number, stiffness: number, damping: number): stri
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------ | ---- | ----- |
| velocity | number | 是 | 初始速度。是由外部因素对弹性动效产生的影响参数,其目的是保证对象从之前的运动状态平滑过渡到弹性动效。 |
| velocity | number | 是 | 初始速度。是由外部因素对弹性动效产生的影响参数,其目的是保证对象从之前的运动状态平滑过渡到弹性动效。 |
| mass | number | 是 | 质量。弹性系统的受力对象,会对弹性系统产生惯性影响。质量越大,震荡的幅度越大,恢复到平衡位置的速度越慢。 |
| stiffness | number | 是 | 刚度。是物体抵抗施加的力而形变的程度。在弹性系统中,刚度越大,抵抗变形的能力越强,恢复到平衡位置的速度就越快。 |
| damping | number | 是 | 阻尼。是一个纯数,无真实的物理意义,用于描述系统在受到扰动后震荡及衰减的情形。阻尼越大,弹性运动的震荡次数越少、震荡幅度越小。 |
......
......@@ -232,7 +232,6 @@ getDefaultApplication(type: string, callback: AsyncCallback\<BundleInfo>) : void
| 错误码ID | 错误信息 |
| -------- | ----------------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700023 | The specified default app does not exist. |
| 17700025 | The specified type is invalid. |
......@@ -415,7 +414,6 @@ setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCal
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700025 | The specified type is invalid. |
| 17700028 | The specified ability does not match the type. |
......@@ -574,7 +572,6 @@ resetDefaultApplication(type: string, callback: AsyncCallback\<void>) : void;
| 错误码ID | 错误信息 |
| -------- | ----------------------------------- |
| 17700004 | The specified user ID is not found. |
| 17700025 | The specified type is invalid. |
**示例:**
......
......@@ -121,6 +121,7 @@ install(hapFilePaths: Array&lt;string&gt;, installParam: InstallParam, callback:
| 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700044 | Failed to install because the isolationMode does not match the system. |
**示例:**
......@@ -184,6 +185,7 @@ install(hapFilePaths: Array&lt;string&gt;, callback: AsyncCallback&lt;void&gt;):
| 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700044 | Failed to install because the isolationMode does not match the system. |
**示例:**
......@@ -225,7 +227,7 @@ install(hapFilePaths: Array\<string\>, installParam?: InstallParam) : Promise\<v
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| hapFilePaths | Array\<string\> | 是 | 存储应用程序包的路径。路径应该是当前应用程序中存放HAP的数据目录。当传入的路径是一个目录时, 该目录下只能放同一个应用的HAP,且这些HAP的签名需要保持一致。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数,默认值:参照[InstallParam](#installparam)的默认值。 |
**返回值:**
......@@ -251,6 +253,7 @@ install(hapFilePaths: Array\<string\>, installParam?: InstallParam) : Promise\<v
| 17700036 | Failed to install the HSP because lacks appropriate permissions. |
| 17700039 | Failed to install because disallow install a shared bundle by hapFilePaths. |
| 17700041 | Failed to install because enterprise device management disallow install. |
| 17700044 | Failed to install because the isolationMode does not match the system. |
**示例:**
......@@ -406,7 +409,7 @@ uninstall(bundleName: string, installParam?: InstallParam) : Promise\<void\>;
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 待卸载应用的包名。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数,默认值:参照[InstallParam](#installparam)的默认值。 |
**返回值:**
......@@ -421,7 +424,7 @@ uninstall(bundleName: string, installParam?: InstallParam) : Promise\<void\>;
| 错误码ID | 错误信息 |
| -------- | ------------------------------------------------------------ |
| 17700001 | The specified bundle name is not found. |
| 17700004 | The specified userId is not existed. |
| 17700004 | The specified user ID is not found. |
| 17700020 | The specified bundle is pre-installed bundle which cannot be uninstalled. |
| 17700040 | The specified bundle is a shared bundle which cannot be uninstalled. |
......@@ -576,7 +579,7 @@ recover(bundleName: string, installParam?: InstallParam) : Promise\<void\>;
| 参数名 | 类型 | 必填 | 说明 |
| ------------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 待卸载应用的包名。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数。 |
| installParam | [InstallParam](#installparam) | 否 | 指定安装所需的其他参数,默认值:参照[InstallParam](#installparam)的默认值。 |
**返回值:**
......@@ -754,12 +757,12 @@ try {
| 名称 | 类型 | 必填 | 说明 |
| ------------------------------ | ------------------------------ | ------------------ | ------------------ |
| userId | number | 否 | 指示用户id,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId)获取当前进程所在用户。 |
| installFlag | number | 否 | 指示安装标志,枚举值:0:应用初次安装,1:应用覆盖安装 |
| isKeepData | boolean | 否 | 卸载时是否保留数据目录。 |
| hashParams | Array<[HashParam](#hashparam)> | 否 | 哈希值参数。 |
| crowdtestDeadline| number | 否 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期。 |
| sharedBundleDirPaths<sup>10+</sup> | Array\<String> | 否 |共享包文件所在路径。 |
| userId | number | 否 | 指示用户id,默认值:调用方所在用户,取值范围:大于等于0,可使用[queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#getOsAccountLocalId)获取当前进程所在用户。 |
| installFlag | number | 否 | 指示安装标志,枚举值:0:应用初次安装,1:应用覆盖安装,默认值为应用初次安装 |
| isKeepData | boolean | 否 | 卸载时是否保留数据目录,默认值为false。 |
| hashParams | Array<[HashParam](#hashparam)> | 否 | 哈希值参数,默认值为空。 |
| crowdtestDeadline| number | 否 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期,默认值为-1。 |
| sharedBundleDirPaths<sup>10+</sup> | Array\<String> | 否 |共享包文件所在路径,默认值为空。 |
## UninstallParam<sup>10+</sup>
......@@ -772,4 +775,4 @@ try {
| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | ------------------------------------------------------------ |
| bundleName | string | 是 | 共享包包名。 |
| versionCode | number | 否 | 指示共享包的版本号。如果不填写versionCode,则卸载该包名的所有共享包。 |
\ No newline at end of file
| versionCode | number | 否 | 指示共享包的版本号。默认值:如果不填写versionCode,则卸载该包名的所有共享包。 |
\ No newline at end of file
......@@ -954,7 +954,7 @@ avPlayer.getTrackDescription((error, arrList) => {
getTrackDescription(): Promise\<Array\<MediaDescription>>
通过Promise方式获取音频轨道信息,可以在prepared/playing/paused状态调用。
通过Promise方式获取音频轨道信息,可以在prepared/playing/paused状态调用。
**系统能力:** SystemCapability.Multimedia.Media.AVPlayer
......@@ -1011,7 +1011,7 @@ seek(timeMs: number, mode?:SeekMode): void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, [duration](#avplayer_duration)]。 |
| mode | [SeekMode](#seekmode8) | 否 | 基于视频I帧的跳转模式,**仅在视频资源播放时设置** |
| mode | [SeekMode](#seekmode8) | 否 | 基于视频I帧的跳转模式,默认为SEEK_PREV_SYNC模式,**仅在视频资源播放时设置** |
**示例:**
......@@ -1138,7 +1138,7 @@ setBitrate(bitrate: number): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------------------------------------------------------------ |
| bitrate | number | 是 | 指定比特率,可以通过[availableBitrates](#availableBitrates_on)事件获得当前HLS协议流可用的比特率,如果用户指定的比特率不在此列表中,则播放器将从可用比特率列表中选择最小和最接近的比特率。如果通过availableBitrates时间获得的比特率列表长度为0,则不支持指定比特率,也不会产生bitrateDone回调。 |
| bitrate | number | 是 | 指定比特率,可以通过[availableBitrates](#availableBitrates_on)事件获得当前HLS协议流可用的比特率,如果用户指定的比特率不在此列表中,则播放器将从可用比特率列表中选择最小和最接近的比特率。如果通过availableBitrates事件获得的比特率列表长度为0,则不支持指定比特率,也不会产生bitrateDone回调。 |
**示例:**
......@@ -1289,7 +1289,7 @@ off(type: 'volumeChange'): void
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | string | 是 | setVolume生效的事件回调类型,取消注册的事件:'availableBitrates'。 |
| type | string | 是 | setVolume生效的事件回调类型,取消注册的事件:'volumeChange'。 |
**示例:**
......@@ -2520,8 +2520,8 @@ avRecorder.off('error');
| videoSourceType | [VideoSourceType](#videosourcetype9) | 否 | 选择录制的视频源类型。选择视频录制时必填。 |
| profile | [AVRecorderProfile](#avrecorderprofile9) | 是 | 录制的profile,必要参数。 |
| url | string | 是 | 录制输出URL:fd://xx (fd number) ![img](figures/zh-cn_image_url.png),必要参数。 |
| rotation | number | 否 | 录制的视频旋转角度,仅支持0,90,180,270 |
| location | [Location](#location) | 否 | 录制的地理位置 |
| rotation | number | 否 | 录制的视频旋转角度,仅支持0,90,180,270,默认值为0。 |
| location | [Location](#location) | 否 | 录制的地理位置,默认不记录地理位置信息。 |
通过audioSourceType和videoSourceType区分纯音频录制、纯视频录制或音视频录制。纯音频录制时,仅需要设置audioSourceType;纯视频录制时,仅需要设置videoSourceType;音视频录制时,audioSourceType和videoSourceType均需要设置。
......@@ -3357,8 +3357,8 @@ videoRecorder.on('error', (error) => { // 设
| audioSourceType | [AudioSourceType](#audiosourcetype9) | 是 | 视频录制的音频源类型。 |
| videoSourceType | [VideoSourceType](#videosourcetype9) | 是 | 视频录制的视频源类型。 |
| profile | [VideoRecorderProfile](#videorecorderprofile9) | 是 | 视频录制的profile。 |
| rotation | number | 否 | 录制视频的旋转角度。 |
| location | [Location](#location) | 否 | 录制视频的地理位置 |
| rotation | number | 否 | 录制的视频旋转角度,仅支持0,90,180,270,默认值为0。 |
| location | [Location](#location) | 否 | 录制视频的地理位置,默认不记录地理位置信息。 |
| url | string | 是 | 视频输出URL:fd://xx&nbsp;(fd&nbsp;number)<br/>![](figures/zh-cn_image_url.png) |
## VideoRecorderProfile<sup>9+</sup>
......@@ -4321,7 +4321,7 @@ seek(timeMs: number, mode?:SeekMode): Promise\<number>
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ---------------------- | ---- | ------------------------------------------------------------ |
| timeMs | number | 是 | 指定的跳转时间节点,单位毫秒(ms),取值范围为[0, duration]。 |
| mode | [SeekMode](#seekmode8) | 否 | 跳转模式。 |
| mode | [SeekMode](#seekmode8) | 否 | 基于视频I帧的跳转模式,默认为SEEK_PREV_SYNC模式。 |
**返回值:**
......
......@@ -52,11 +52,11 @@ try {
overlay.setOverlayEnabled(moduleName, isEnabled)
.then(() => {
console.info('setOverlayEnabled success');
}).catch((error) => {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
}).catch((err) => {
console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
});
} catch (error) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
} catch (err) {
console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}
```
......@@ -92,15 +92,15 @@ var moduleName = "feature";
var isEnabled = false;
try {
overlay.setOverlayEnabled(moduleName, isEnabled, (error, data) => {
if (error) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
overlay.setOverlayEnabled(moduleName, isEnabled, (err, data) => {
if (err) {
console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
return;
}
console.info('setOverlayEnabled success');
});
} catch (error) {
console.info('setOverlayEnabled failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
} catch (err) {
console.info('setOverlayEnabled failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}
```
......@@ -152,11 +152,11 @@ try {
overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled)
.then((data) => {
console.info('setOverlayEnabledByBundleName successfully');
}).catch((error) => {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
}).catch((err) => {
console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
});
} catch (error) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
} catch (err) {
console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}
```
......@@ -200,15 +200,15 @@ var moduleName = "feature"
var isEnabled = false;
try {
overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (error, data) => {
if (error) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
overlay.setOverlayEnabledByBundleName(bundleName, moduleName, isEnabled, (err, data) => {
if (err) {
console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
return;
}
console.info('setOverlayEnabledByBundleName successfully');
});
} catch (error) {
console.info('setOverlayEnabledByBundleName failed due to error code: ' + err.code + ' ' + 'message:' + err.message);
} catch (err) {
console.info('setOverlayEnabledByBundleName failed due to err code: ' + err.code + ' ' + 'message:' + err.message);
}
```
......@@ -252,7 +252,7 @@ var moduleName = "feature"
let overlayModuleInfo = await overlay.getOverlayModuleInfo(moduleName);
console.log('overlayModuleInfo is ' + JSON.stringify(overlayModuleInfo));
} catch(err) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
})();
```
......@@ -279,7 +279,7 @@ getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\<OverlayModuleI
| 错误码ID | 错误信息 |
| ------ | -------------------------------------- |
| 17700002 | The specified module name is not found. |
| 17700032 | he specified bundle does not contain any overlay module. |
| 17700032 | The specified bundle does not contain any overlay module. |
| 17700033 | The specified module is not an overlay module. |
**示例:**
......@@ -287,15 +287,15 @@ getOverlayModuleInfo(moduleName: string, callback: AsyncCallback\<OverlayModuleI
```ts
var moduleName = "feature"
try {
overlay.getOverlayModuleInfo(moduleName, (error, data) => {
if (error) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getOverlayModuleInfo(moduleName, (err, data) => {
if (err) {
console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getOverlayModuleInfo failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getOverlayModuleInfo failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
......@@ -338,7 +338,7 @@ var targetModuleName = "feature"
let overlayModuleInfos = await overlay.getTargetOverlayModuleInfos(targetModuleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
})();
```
......@@ -372,15 +372,15 @@ getTargetOverlayModuleInfos(targetModuleName: string, callback: AsyncCallback\<A
```ts
var targetModuleName = "feature"
try {
overlay.getTargetOverlayModuleInfos(targetModuleName, (error, data) => {
if (error) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getTargetOverlayModuleInfos(targetModuleName, (err, data) => {
if (err) {
console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
......@@ -401,7 +401,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promi
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
| bundleName | string | 是 | 指定应用的bundle名称。 |
| moduleName | string | 否 | 指定应用中的overlay module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module的OverlayModuleInfo信息。 |
| moduleName | string | 否 | 指定应用中的overlay module的HAP名称。默认值:缺省该字段时,查询接口将查询指定应用中所有module的OverlayModuleInfo信息。 |
**返回值:**
......@@ -431,7 +431,7 @@ var moduleName = "feature"
let overlayModuleInfos = await overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) {
console.log('getTargetOverlayModuleInfos failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
console.log('getTargetOverlayModuleInfos failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
})();
```
......@@ -474,15 +474,15 @@ var bundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature"
try {
overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (error, data) => {
if (error) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getOverlayModuleInfoByBundleName(bundleName, moduleName, (err, data) => {
if (err) {
console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
......@@ -512,9 +512,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\<Ar
| 错误码ID | 错误信息 |
| ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. |
| 17700032 | The specified bundle does not contain any overlay module. |
| 17700033 | The specified module is not an overlay module. |
**示例:**
......@@ -522,15 +520,15 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\<Ar
var bundleName = "com.example.myapplication_xxxxx";
try {
overlay.getOverlayModuleInfoByBundleName(bundleName, (error, data) => {
if (error) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getOverlayModuleInfoByBundleName(bundleName, (err, data) => {
if (err) {
console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getOverlayModuleInfoByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getOverlayModuleInfoByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
......@@ -551,7 +549,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: s
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
| targetBundleName | string | 是 | 指定目标应用的bundle名称。 |
| moduleName | string | 否 | 指定应用中的目标module的HAP名称。缺省该字段时,查询接口将查询指定应用中所有module所关联的OverlayModuleInfo信息。 |
| moduleName | string | 否 | 指定应用中的目标module的HAP名称。默认值:缺省该字段时,查询接口将查询指定应用中所有module所关联的OverlayModuleInfo信息。 |
**返回值:**
......@@ -581,14 +579,14 @@ var moduleName = "feature"
let overlayModuleInfos = await overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName);
console.log('overlayModuleInfos are ' + JSON.stringify(overlayModuleInfos));
} catch(err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
})();
```
## overlay.getTargetOverlayModuleInfosByBundleName
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback\<Array<OverlayModuleInfo>>): void;
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: string, callback: AsyncCallback&lt;Array&lt;OverlayModuleInfo&gt;&gt;): void;
以异步方法获取指定应用中指定module关联的所有OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。
......@@ -624,21 +622,21 @@ var targetBundleName = "com.example.myapplication_xxxxx";
var moduleName = "feature"
try {
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (error, data) => {
if (error) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, moduleName, (err, data) => {
if (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
## overlay.getTargetOverlayModuleInfosByBundleName
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback\<Array<OverlayModuleInfo>>): void;
getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: AsyncCallback&lt;Array&lt;OverlayModuleInfo&gt;&gt;): void;
以异步方法获取指定应用中所有module关联的所有OverlayModuleInfo信息。使用callback异步回调,成功返回null,失败返回对应错误信息。
......@@ -662,8 +660,6 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn
| 错误码ID | 错误信息 |
| ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. |
| 17700034 | The specified module is an overlay module. |
| 17700035 | The specified bundle is an overlay bundle. |
**示例:**
......@@ -672,15 +668,15 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn
var targetBundleName = "com.example.myapplication_xxxxx";
try {
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (error, data) => {
if (error) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
overlay.getTargetOverlayModuleInfosByBundleName(targetBundleName, (err, data) => {
if (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
return;
}
console.log('overlayModuleInfo is ' + JSON.stringify(data));
});
} catch (error) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to error code : ' + err.code + ' ' + 'message :' + err.message);
} catch (err) {
console.log('getTargetOverlayModuleInfosByBundleName failed due to err code : ' + err.code + ' ' + 'message :' + err.message);
}
```
......
......@@ -14,12 +14,6 @@ request部件主要给应用提供上传下载文件、后台传输代理的基
import request from '@ohos.request';
```
## 限制与约束
上传目前仅支持HTTP请求,不支持HTTPS。
下载服务器需要支持HTTP协议的head方法,能够通过Content-length获取下载数据大小,否则下载任务失败,可通过[on('fail')<sup>7+</sup>](#onfail7)查看失败原因。
## 常量
**需要权限**:ohos.permission.INTERNET
......@@ -35,7 +29,7 @@ import request from '@ohos.request';
| NETWORK_WIFI | number | 0x00010000 | 使用WLAN时允许下载的位标志。 |
### 下载任务的错误码
下载相关[on('fail')<sup>7+</sup>](#onfail7)/[off('fail')<sup>7+</sup>](#offfail7)/[getTaskInfo<sup>9+</sup>](#gettaskinfo9)接口可能返回的错误码
下载[on('fail')<sup>7+</sup>](#onfail7)事件callback的错误参数、[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的failedReason字段取值
| 名称 | 参数类型 | 数值 | 说明 |
| -------- | -------- | -------- | -------- |
......@@ -53,7 +47,7 @@ import request from '@ohos.request';
### 下载任务暂停原因
下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)接口可能返回的任务暂停原因
下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的pausedReason字段取值。
| 名称 | 参数类型 | 数值 | 说明 |
| -------- | -------- | -------- | -------- |
......@@ -64,7 +58,7 @@ import request from '@ohos.request';
| PAUSED_UNKNOWN<sup>7+</sup> | number | 4 | 未知原因导致暂停下载。 |
### 下载任务状态码
下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)接口可能返回的任务状态码
下载相关[getTaskInfo<sup>9+</sup>](#gettaskinfo9)返回值的status字段取值。
| 名称 | 参数类型 | 数值 | 说明 |
| -------- | -------- | -------- | -------- |
......@@ -274,7 +268,7 @@ upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; void): void
开启上传任务监听,异步方法,使用callback形式返回结果。
订阅上传任务进度监听,同步方法,使用callback形式返回结果。
**需要权限**:ohos.permission.INTERNET
......@@ -297,10 +291,10 @@ on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; vo
**示例:**
```js
uploadTask.on('progress', function callback(uploadedSize, totalSize) {
let upProgressCallback = (uploadedSize, totalSize) => {
console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize);
}
);
};
uploadTask.on('progress', upProgressCallback);
```
......@@ -308,7 +302,7 @@ on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; vo
on(type: 'headerReceive', callback: (header: object) =&gt; void): void
开启上传任务监听,异步方法,使用callback形式返回结果。
订阅上传任务HTTP标头监听,同步方法,使用callback形式返回结果。
**需要权限**:ohos.permission.INTERNET
......@@ -330,10 +324,10 @@ on(type: 'headerReceive', callback: (header: object) =&gt; void): void
**示例:**
```js
uploadTask.on('headerReceive', function callback(headers){
let headerCallback = (headers) => {
console.info("upOnHeader headers:" + JSON.stringify(headers));
}
);
};
uploadTask.on('headerReceive', headerCallback);
```
......@@ -341,7 +335,7 @@ on(type: 'headerReceive', callback: (header: object) =&gt; void): void
on(type:'complete' | 'fail', callback: Callback&lt;Array&lt;TaskState&gt;&gt;): void;
开启上传任务监听,异步方法,使用callback形式返回结果。
订阅上传任务完成或失败监听,同步方法,使用callback形式返回结果。
**需要权限**:ohos.permission.INTERNET
......@@ -363,19 +357,19 @@ on(type: 'headerReceive', callback: (header: object) =&gt; void): void
**示例:**
```js
uploadTask.on('complete', function callback(taskStates) {
let upCompleteCallback = (taskStates) => {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
}
}
);
};
uploadTask.on('complete', upComplete);
uploadTask.on('fail', function callback(taskStates) {
let upFailCallback = (taskStates) => {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
}
}
);
};
uploadTask.on('fail', upFailCallback);
```
......@@ -383,7 +377,7 @@ on(type: 'headerReceive', callback: (header: object) =&gt; void): void
off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&gt; void): void
关闭上传任务监听,异步方法,使用callback形式返回结果
删除上传任务进度监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -394,22 +388,12 @@ off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&g
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消订阅的事件类型,取值为'progress'(上传的进度信息)。 |
| callback | function | 否 | 上传任务的回调函数。 |
回调函数的参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uploadedSize | number | 是 | 当前已上传文件的大小,单位为B。 |
| totalSize | number | 是 | 上传文件的总大小,单位为B。 |
| callback | function | 否 | 需要删除的上传任务进度的回调函数。<br/>uploadedSize:当前已上传文件的大小,单位为B。<br/>totalSize:上传文件的总大小,单位为B。 |
**示例:**
```js
uploadTask.off('progress', function callback(uploadedSize, totalSize) {
console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize);
}
);
uploadTask.off('progress', upProgressCallback);
```
......@@ -417,7 +401,7 @@ off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&g
off(type: 'headerReceive', callback?: (header: object) =&gt; void): void
关闭上传任务监听,异步方法,使用callback形式返回结果
删除上传任务HTTP标头监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -428,28 +412,19 @@ off(type: 'headerReceive', callback?: (header: object) =&gt; void): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消订阅的事件类型,取值为'headerReceive'(接收响应头)。 |
| callback | function | 否 | HTTP&nbsp;Response&nbsp;Header事件的回调函数。 |
回调函数的参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| header | object | 是 | HTTP&nbsp;Response&nbsp;Header。 |
| callback | function | 否 | HTTP&nbsp;Response&nbsp;需要删除的Header事件的回调函数。<br/>header:HTTP&nbsp;Response&nbsp;Header。 |
**示例:**
```js
uploadTask.off('headerReceive', function callback(headers) {
console.info("upOnHeader headers:" + JSON.stringify(headers));
}
);
uploadTask.off('headerReceive', headerCallback);
```
### off('complete' | 'fail')<sup>9+</sup>
off(type:'complete' | 'fail', callback?: Callback&lt;Array&lt;TaskState&gt;&gt;): void;
关闭上传任务监听,异步方法,使用callback形式返回结果
删除上传任务完成或失败监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -460,30 +435,14 @@ off(type: 'headerReceive', callback?: (header: object) =&gt; void): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 订阅的事件类型,取值为'complete',表示上传任务完成;取值为'fail',表示上传任务失败。|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | 否 | 上传任务完成或失败的回调函数。 |
回调函数的参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| taskstates | Array&lt;[TaskState](#taskstate9)&gt; | 是 | 上传任务返回结果 |
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | 否 | 需要删除的上传任务完成或失败的回调函数。<br/>taskstates:上传任务返回结果 |
**示例:**
```js
uploadTask.off('complete', function callback(taskStates) {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
}
}
);
uploadTask.off('complete', upCompleteCallback);
uploadTask.off('fail', function callback(taskStates) {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnFail taskState:" + JSON.stringify(taskStates[i]));
}
}
);
uploadTask.off('fail', upFailCallback);
```
### delete<sup>9+</sup>
......@@ -848,7 +807,7 @@ download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): v
on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; void): void
开启下载任务监听,异步方法,使用callback形式返回结果。
订阅下载任务进度监听,同步方法,使用callback形式返回结果。
**需要权限**:ohos.permission.INTERNET
......@@ -859,7 +818,7 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; vo
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 订阅的事件类型,取值为'progress'(下载的进度信息)。 |
| callback | function | 是 | 下载的回调函数。 |
| callback | function | 是 | 下载任务进度的回调函数。 |
回调函数的参数:
......@@ -871,10 +830,10 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; vo
**示例:**
```js
downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
let progresCallbanck = (receivedSize, totalSize) => {
console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
}
);
};
downloadTask.on('progress', progresCallbanck);
```
......@@ -882,7 +841,7 @@ on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; vo
off(type: 'progress', callback?: (receivedSize: number, totalSize: number) =&gt; void): void
关闭下载任务监听,异步方法,使用callback形式返回结果
删除下载任务进度监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -893,22 +852,12 @@ off(type: 'progress', callback?: (receivedSize: number, totalSize: number) =&gt;
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消订阅的事件类型,取值为'progress'(下载的进度信息)。 |
| callback | function | 否 | 下载任务的回调函数。 |
回调函数的参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| receivedSize | number | 是 | 当前下载的进度,单位为B。|
| totalSize | number | 是 | 下载文件的总大小,单位为B。|
| callback | function | 否 | 需要删除的下载任务进度的回调。 <br/>receivedSize:当前下载任务的进度;<br/>totalSize:下载文件的总大小。 |
**示例:**
```js
downloadTask .off('progress', function download_callback(receivedSize, totalSize) {
console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
}
);
downloadTask .off('progress',progresCallbanck);
```
......@@ -916,7 +865,7 @@ off(type: 'progress', callback?: (receivedSize: number, totalSize: number) =&gt;
on(type: 'complete'|'pause'|'remove', callback:() =&gt; void): void
开启下载任务相关的监听,异步方法,使用callback形式返回。
订阅下载任务相关的监听,异步方法,使用callback形式返回。
**需要权限**:ohos.permission.INTERNET
......@@ -927,15 +876,15 @@ on(type: 'complete'|'pause'|'remove', callback:() =&gt; void): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 订阅的事件类型。<br>- 取值为'complete',表示下载任务完成;<br/>- 取值为'pause',表示下载任务暂停;<br/>- 取值为'remove',表示下载任务移除。 |
| callback | function | 是 | 回调函数。 |
| callback | function | 是 | 下载任务相关的回调函数。|
**示例:**
```js
downloadTask.on('complete', function callback() {
let completeCallback = () => {
console.info('Download task completed.');
}
);
};
downloadTask.on('complete', completeCallback);
```
......@@ -943,7 +892,7 @@ on(type: 'complete'|'pause'|'remove', callback:() =&gt; void): void
off(type: 'complete'|'pause'|'remove', callback?:() =&gt; void): void
取消下载任务相关的监听,异步方法,使用callback形式返回
删除下载任务相关的监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -954,15 +903,12 @@ off(type: 'complete'|'pause'|'remove', callback?:() =&gt; void): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消订阅的事件类型。<br/>- 取值为'complete',表示下载任务完成;<br/>- 取值为'pause',表示下载任务暂停;<br/>- 取值为'remove',表示下载任务移除。 |
| callback | function | 否 | 回调函数。 |
| callback | function | 否 | 需要删除的下载任务相关的回调。 |
**示例:**
```js
downloadTask.off('complete', function callback() {
console.info('Download task completed.');
}
);
downloadTask.off('complete', completeCallback);
```
......@@ -970,7 +916,7 @@ off(type: 'complete'|'pause'|'remove', callback?:() =&gt; void): void
on(type: 'fail', callback: (err: number) =&gt; void): void
开启下载任务失败监听,异步方法,使用callback形式返回结果。
订阅下载任务失败监听,同步方法,使用callback形式返回结果。
**需要权限**:ohos.permission.INTERNET
......@@ -992,10 +938,10 @@ on(type: 'fail', callback: (err: number) =&gt; void): void
**示例:**
```js
downloadTask.on('fail', function callBack(err) {
let failCallback = (err) => {
console.info('Download task failed. Cause:' + err);
}
);
};
downloadTask.on('fail', failCallback);
```
......@@ -1003,7 +949,7 @@ on(type: 'fail', callback: (err: number) =&gt; void): void
off(type: 'fail', callback?: (err: number) =&gt; void): void
取消下载任务失败监听,异步方法,使用callback形式返回结果
删除下载任务失败监听,同步方法
**需要权限**:ohos.permission.INTERNET
......@@ -1014,21 +960,12 @@ off(type: 'fail', callback?: (err: number) =&gt; void): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| type | string | 是 | 取消订阅的事件类型,取值为'fail'(下载失败)。 |
| callback | function | 否 | 取消下载失败的回调函数。 |
回调函数的参数
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| err | number | 是 | 下载失败的错误码。错误原因见[下载任务的错误码](#下载任务的错误码)。 |
| callback | function | 否 | 需要删除的下载失败的回调函数。<br/>err:下载失败的错误码。 |
**示例:**
```js
downloadTask.off('fail', function callBack(err) {
console.info('Download task failed. Cause:' + err);
}
);
downloadTask.off('fail', failCallback);
```
### delete<sup>9+</sup>
......@@ -1673,34 +1610,33 @@ resume(callback: AsyncCallback&lt;void&gt;): void
| -------- | -------- | -------- | -------- |
| url | string | 是 | 资源地址。 |
| header | Object | 否 | 添加要包含在下载请求中的HTTPS标志头。<br/>开发者可以通过header的X-TLS-Version参数指定需要使用的TLS版本(如果不指定,则默认使用CURL_SSLVERSION_TLSv1_2版本,指定则使用指定版本。)<br/>CURL_SSLVERSION_TLSv1_0<br/>CURL_SSLVERSION_TLSv1_1<br/>CURL_SSLVERSION_TLSv1_2<br/>CURL_SSLVERSION_TLSv1_3<br/>通过header的X-Cipher-List参数指定需要使用的密码套件(如果不指定,则默认使用安全密码套件,指定则使用指定密码套件。)<br/>-1.2允许使用的密码套件白名单:<br/>TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,<br/>TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,<br/>TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,<br/>TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,<br/>TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,<br/>TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,<br/>TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,<br/>TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,<br/>TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,<br/>TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,<br/>TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,<br/>TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,<br/>TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256<br/>-1.3允许使用的密码套件白名单:<br/>TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256<br/>-1.3新增国密算法套:<br/>TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 |
| enableMetered | boolean | 否 | 设置是否允许在按流量计费的连接下下载。<br/>-&nbsp;true:是<br/>-&nbsp;false:否 |
| enableRoaming | boolean | 否 | 设置是否允许在漫游网络中下载。 <br/>-&nbsp;true:是<br/>-&nbsp;false:否|
| enableMetered | boolean | 否 | 设置是否允许在按流量计费的连接下下载(默认使用false)<br/>-&nbsp;true:是<br/>-&nbsp;false:否 |
| enableRoaming | boolean | 否 | 设置是否允许在漫游网络中下载(默认使用false)<br/>-&nbsp;true:是<br/>-&nbsp;false:否|
| description | string | 否 | 设置下载会话的描述。 |
| filePath<sup>7+</sup> | string | 否 | 设置下载路径。<br/>-&nbsp;filePath:'/data/storage/el2/base/haps/entry/files/test.txt':将文件存储在绝对路径下。<br/>-&nbsp;FA模型下使用[context](js-apis-inner-app-context.md#contextgetcachedir) 获取应用存储路径,比如:\`${featureAbility.getContext().getFilesDir()}/test.txt\`,并将文件存储在此路径下。<br/>-&nbsp;Stage模型下使用[AbilityContext](js-apis-inner-application-context.md) 类获取文件路径,比如:\`${globalThis.abilityContext.tempDir}/test.txt\`,并将文件存储在此路径下。|
| networkType | number | 否 | 设置允许下载的网络类型。<br/>-&nbsp;NETWORK_MOBILE:0x00000001<br/>-&nbsp;NETWORK_WIFI:0x00010000|
| networkType | number | 否 | 设置允许下载的网络类型(默认使用NETWORK_MOBILE&NETWORK_WIFI)。<br/>-&nbsp;NETWORK_MOBILE:0x00000001<br/>-&nbsp;NETWORK_WIFI:0x00010000|
| title | string | 否 | 设置下载任务名称。 |
| background<sup>9+</sup> | boolean | 否 | 后台任务通知开关,开启后可在通知中显示下载状态。 |
| background<sup>9+</sup> | boolean | 否 | 后台任务通知开关,开启后可在通知中显示下载状态(默认使用false)。 |
## DownloadInfo<sup>7+</sup>
下载任务信息,[query<sup>(deprecated)</sup>](#querydeprecated-1)接口的回调参数。
下载任务信息,[getTaskInfo<sup>9+</sup>](#gettaskinfo9)接口的回调参数。
**需要权限**:ohos.permission.INTERNET
**系统能力**: SystemCapability.MiscServices.Download
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| downloadId | number | 是 | 下载的文件ID。 |
| failedReason | number | 否 | 下载失败原因,可以是任何[下载任务的错误码](#下载任务的错误码)常量。 |
| fileName | string | 是 | 下载的文件名。 |
| filePath | string | 是 | 存储文件的URI。 |
| pausedReason | number | 否 | 会话暂停的原因,可以是任何[下载任务暂停原因](#下载任务暂停原因)常量。 |
| status | number | 是 | 下载状态码,可以是任何[下载任务状态码](#下载任务状态码)常量。 |
| targetURI | string | 是 | 下载文件的URI。 |
| downloadTitle | string | 是 | 下载任务名称。 |
| downloadTotalBytes | number | 是 | 下载的文件的总大小(int&nbsp;bytes)。 |
| description | string | 是 | 待下载文件的描述信息。 |
| downloadedBytes | number | 是 | 实时下载大小(int&nbsp;&nbsp;bytes)。 |
| 名称 | 类型 | 说明 |
| -------- | ------ |---------------- |
| downloadId | number | 下载任务ID。 |
| failedReason | number | 下载失败原因,可以是任何[下载任务的错误码](#下载任务的错误码)常量。 |
| fileName | string | 下载的文件名。 |
| filePath | string | 存储文件的URI。 |
| pausedReason | number | 会话暂停的原因,可以是任何[下载任务暂停原因](#下载任务暂停原因)常量。 |
| status | number | 下载状态码,可以是任何[下载任务状态码](#下载任务状态码)常量。 |
| targetURI | string | 下载文件的URI。 |
| downloadTitle | string | 下载任务名称。 |
| downloadTotalBytes | number | 下载的文件的总大小(int&nbsp;bytes)。 |
| description | string | 待下载任务的描述信息。 |
| downloadedBytes | number | 实时下载大小(int&nbsp;&nbsp;bytes)。 |
<!--no_check-->
\ No newline at end of file
......@@ -94,7 +94,7 @@ unlock(callback: AsyncCallback&lt;boolean&gt;): void
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
......@@ -130,7 +130,7 @@ unlock(): Promise&lt;boolean&gt;
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
......@@ -166,7 +166,7 @@ lock(callback: AsyncCallback&lt;boolean&gt;): void
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
......@@ -204,7 +204,7 @@ lock(): Promise&lt;boolean&gt;
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
......@@ -246,7 +246,7 @@ onSystemEvent(callback: Callback&lt;SystemEvent&gt;): boolean
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
......@@ -286,7 +286,7 @@ sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback&lt
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | The screenlock management service is abnormal. |
| 13200002 |the screenlock management service is abnormal. |
**示例:**
......@@ -325,6 +325,14 @@ sendScreenLockEvent(event: String, parameter: number): Promise&lt;boolean&gt;
| ----------------- | ---------------------------------------------- |
| Promise\<boolean> | Promise对象。返回true表示发送事件成功;返回false表示发送事件失败。 |
**错误码**
以下错误码的详细介绍请参见[锁屏服务错误码](../errorcodes/errorcode-screenlock.md)
| 错误码ID | 错误信息 |
| -------- | ---------------------------------------- |
| 13200002 | the screenlock management service is abnormal. |
**示例:**
```js
......
......@@ -89,7 +89,7 @@ sensor.unsubscribeAccelerometer();
```js
sensor.subscribeCompass({
success: function(ret) {
console.log('get data direction:' + ret.direction);
console.log('Get data direction:' + ret.direction);
},
fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -133,7 +133,7 @@ sensor.unsubscribeCompass();
```js
sensor.subscribeProximity({
success: function(ret) {
console.log('get data distance:' + ret.distance);
console.log('Get data distance:' + ret.distance);
},
fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -177,7 +177,7 @@ sensor.unsubscribeProximity();
```js
sensor.subscribeLight({
success: function(ret) {
console.log('get data intensity:' + ret.intensity);
console.log('Get data intensity:' + ret.intensity);
},
fail: function(data, code) {
console.error('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -223,7 +223,7 @@ sensor.unsubscribeLight();
```js
sensor.subscribeStepCounter({
success: function(ret) {
console.log('get step value:' + ret.steps);
console.log('Get step value:' + ret.steps);
},
fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -255,7 +255,7 @@ sensor.unsubscribeStepCounter();
subscribeBarometer(options: SubscribeBarometerOptions): void
订阅气压传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。
订阅气压传感器数据变化。针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效。
**系统能力**:SystemCapability.Sensors.Sensor
......@@ -270,7 +270,7 @@ subscribeBarometer(options: SubscribeBarometerOptions): void
```js
sensor.subscribeBarometer({
success: function(ret) {
console.log('get data value:' + ret.pressure);
console.log('Get data value:' + ret.pressure);
},
fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -286,7 +286,7 @@ sensor.subscribeBarometer({
unsubscribeBarometer(): void
取消订阅气压传感器。
取消订阅气压传感器。
**系统能力**:SystemCapability.Sensors.Sensor
......@@ -318,7 +318,7 @@ sensor.unsubscribeBarometer();
```js
sensor.subscribeHeartRate({
success: function(ret) {
console.log('get heartrate value:' + ret.heartRate);
console.log('Get heartrate value:' + ret.heartRate);
},
fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -334,7 +334,7 @@ sensor.subscribeHeartRate({
unsubscribeHeartRate(): void
取消订阅心率。
取消订阅心率传感器
**系统能力**:SystemCapability.Sensors.Sensor
......@@ -365,7 +365,7 @@ sensor.unsubscribeHeartRate();
```js
sensor.subscribeOnBodyState({
success: function(ret) {
console.log('get on-body state value:' + ret.value);
console.log('Get on-body state value:' + ret.value);
},
fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -409,7 +409,7 @@ sensor.unsubscribeOnBodyState();
```js
sensor.getOnBodyState({
success: function(ret) {
console.log('on body state: ' + ret.value);
console.log('On body state: ' + ret.value);
},
fail: function(data, code) {
console.log('Subscription failed. Code: ' + code + '; Data: ' + data);
......@@ -470,7 +470,7 @@ sensor.unsubscribeDeviceOrientation();
subscribeGyroscope(options: SubscribeGyroscopeOptions): void
观察陀螺仪数据变化。
观察陀螺仪传感器数据变化。
针对同一个应用,多次点击调用时,会覆盖前面的调用效果,即仅最后一次调用生效;针对同一个方法内,不支持多次调用。
......@@ -507,7 +507,7 @@ sensor.subscribeGyroscope({
unsubscribeGyroscope(): void
取消订阅陀螺仪数据。
取消订阅陀螺仪传感器数据。
**系统能力**:SystemCapability.Sensors.Sensor
......@@ -643,12 +643,12 @@ sensor.unsubscribeGyroscope();
| 名称 | 类型 | 必填 | 说明 |
| ------- | --------------------------------------- | ---- | -------------------------------- |
| success | [BarometerResponse](#barometerresponse) | 是 | 气压传感器数据改变后的回调函数。 |
| success | [BarometerResponse](#barometerresponse) | 是 | 气压传感器数据改变后的回调函数。 |
| fail | Function | 否 | 接口调用失败的回调函数。 |
## BarometerResponse
气压传感器数据改变后的回调函数。
气压传感器数据改变后的回调函数。
**系统能力**:SystemCapability.Sensors.Sensor
......@@ -710,7 +710,7 @@ sensor.unsubscribeGyroscope();
| 名称 | 类型 | 必填 | 说明 |
| -------- | ------------------------------------------- | ---- | ------------------------ |
| success | [OnBodyStateResponse](#onbodystateresponse) | | 接口调用成功的回调函数。 |
| success | [OnBodyStateResponse](#onbodystateresponse) | | 接口调用成功的回调函数。 |
| fail | Function | 否 | 接口调用失败的回调函数。 |
| complete | Function | 否 | 接口调用结束的回调函数。 |
......@@ -754,7 +754,7 @@ sensor.unsubscribeGyroscope();
## GyroscopeResponse<sup>6+</sup>
感应到陀螺仪数据变化后的回调函数。
感应到陀螺仪传感器数据变化后的回调函数。
**需要权限**:ohos.permission.GYROSCOPE
......
......@@ -135,7 +135,7 @@ compressFile(inFile: string, outFile: string, options: Options, callback: AsyncC
| 参数名 | 类型 | 必填 | 说明 |
| ----------------------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,路径必须为沙箱路径,沙箱路径可以通过context获取,可参考[FA模型](js-apis-inner-app-context.md)[Stage模型](js-apis-inner-application-context.md)。 |
| outFile | string | 是 | 指定的解压文件路径。 |
| outFile | string | 是 | 指定的压缩结果的文件路径。 |
| options | [Options](#options) | 是 | 压缩的配置参数。 |
| AsyncCallback<**void**> | callback | 否 | 压缩时的回调函数。 |
......@@ -185,7 +185,7 @@ compressFile(inFile: string, outFile: string, options: Options): Promise\<void>;
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| inFile | string | 是 | 指定压缩的文件夹路径或者文件路径,路径必须为沙箱路径,沙箱路径可以通过context获取,可参考[FA模型](js-apis-inner-app-context.md)[Stage模型](js-apis-inner-application-context.md)。 |
| outFile | string | 是 | 指定的解压文件路径。 |
| outFile | string | 是 | 指定的压缩结果的文件路径。 |
| options | [Options](#options) | 是 | 压缩的配置参数。 |
**相关错误码**
......
......@@ -544,4 +544,17 @@ The specified bundle is a shared bundle which cannot be uninstalled.
1. 通过-s参数指定卸载的应用为共享库应用。
2. 通过UninstallParam参数的bundleName及versionCode指定卸载的共享库的包名及版本。
## 17700044 安装包设置的多进程配置项与系统配置项设置矛盾
**错误信息**<br/>
Failed to install because the isolationMode does not match the system.
**错误描述**<br/>
安装应用时,设置的isolationMode与系统配置项所允许的系统配置项矛盾。
**可能原因**<br/>
1. 设备支持隔离模式,即supportIsolationMode为true时,HAP配置的isolationMode为nonisolationOnly。
2. 设备不支持隔离模式,即supportIsolationMode为false时,HAP配置的isolationMode为isolationOnly。
**处理步骤**<br/>
1. 按照设备的隔离模式正确配置HAP字段isolationMode。
<!--no_check-->
\ No newline at end of file
......@@ -1857,3 +1857,23 @@
**授权方式**:system_grant
**ACL使能**:TURE
## ohos.permission.READ_HIVIEW_SYSTEM
允许应用访问hiview的数据。
**权限级别**:system_basic
**授权方式**:system_grant
**ACL使能**:TRUE
## ohos.permission.WRITE_HIVIEW_SYSTEM
允许应用修改hiview的数据。
**权限级别**:system_basic
**授权方式**:system_grant
**ACL使能**:TRUE
\ No newline at end of file
......@@ -6,7 +6,7 @@
## 接口说明
以下仅列举本指导使用的接口,更多说明可以查阅[API参考](../reference/apis/js-apis-abilityAccessCtrl)
以下仅列举本指导使用的接口,更多说明可以查阅[API参考](../reference/apis/js-apis-abilityAccessCtrl.md)
checkAccessToken(tokenID: number, permissionName: Permissions): Promise&lt;GrantStatus&gt;
......
......@@ -155,7 +155,7 @@ WorkSchedulerExtensionAbility类拥有如下API接口,具体的API介绍详见
import { workAbility } from '@ohos/library';
```
增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中bilityName为WorkTest。
增加“升级”按钮,调用library封装的延迟任务注册接口,传入bundleName和abilityName,其中abilityName为WorkTest。
```ts
Button($r('app.string.upgrade'))
......
......@@ -26,7 +26,7 @@ LiteOS-A内核容器隔离功能包含7个容器:UTS容器、PID容器、Mount
PID容器通过 unshare/setns 切换时,切换子进程的容器,而本进程容器不变。
通过在进程ProcessCB中添加对应容器集合Container和用户容器,完成对容器功能的支持,并通过编译开关控制特性的开启和关闭。
通过在进程ProcessCB中添加对应容器集合Container和用户容器,完成对容器功能的支持,并通过编译开关控制特性的开启和关闭。
- 每个进程ProcessCB包含一个Container指针,该指针指向真正分配的Container结构。通过这种方式,进程可单独拥有一个Container结构,也可共享同一个Container结构。 进一步分解,在Container结构中,包含各容器指针,分别指向UTS容器、PID容器、Network容器、Mount容器、TIME容器、IPC容器。
......@@ -40,9 +40,7 @@ PID容器通过 unshare/setns 切换时,切换子进程的容器,而本进
#### **UTS容器**
UTS 容器用于对主机名和域名进行隔离。
每一个进程对应有一个自己的UTS Container,用来隔离容器的内核名称、版本等信息,不同容器查看到的都是属于自己的信息,相互间不能查看。
UTS 容器用于对主机名和域名、版本等信息进行隔离,不同UTS容器内查看到的都是属于自己的信息,相互间不能查看。
#### **Mount容器**
......@@ -52,7 +50,7 @@ UTS 容器用于对主机名和域名进行隔离。
- 文件挂载容器的基础实现,创建进程时根据clone传入的参数flag在各自进程创建文件挂载容器,将挂载信息从全局更改为与文件挂载容器相关联。
- 创建容器后,修改获取当前挂载信息的实现,将从全局或者更改为当前文件挂载容器中获取,使进程挂载、卸载或者访问挂载文件操作不会对其他进程挂载信息产生影响或者访问到其他进程的文件挂载信息。
- 创建容器后,修改获取当前挂载信息的实现,将从全局更改为当前文件挂载容器中获取,使进程挂载、卸载或者访问挂载文件操作不会对其他进程挂载信息产生影响或者访问到其他进程的文件挂载信息。
#### **PID容器**
......@@ -61,7 +59,7 @@ UTS 容器用于对主机名和域名进行隔离。
进程容器主要用于进程的隔离,特点如下:
- 容器间的进程ID相互独立。
-容器可以看到子容器中的进程,且同一个进程在父容器中的进程ID和子容器中的进程ID相互独立。
-PID容器可以看到子PID容器中的进程,且同一个进程在父PID容器中的进程ID和子PID容器中的进程ID相互独立。
- 子容器无法看到父容器中的进程。
- 在根容器下可以看到系统的所有进程。
......@@ -124,9 +122,9 @@ Capabilities的类型如下表:
容器(当前进程的time_for_children容器)中时钟的偏移量记录在`/proc/PID/timens_offsets`文件中,通过修改该文件,可以对应修改TIME容器的偏移信息。这些偏移是相对于初始时间容器中的时钟值表示的。
当前,创建TIME Container的唯一方法是通过使用`CLONE_NEWTIME`标志调用`unshare`。该调用将创建一个新的TIME Container,但不会将调用过程放在新的容器中。而是调用进程的随后创建的子级将放置在新的容器中。
当前,创建TIME Container的唯一方法是通过使用`CLONE_NEWTIME`标志调用`unshare`。该调用将创建一个新的TIME Container,但不会将调用进程放在新的容器中,而是调用进程随后创建的子进程放置在新的容器中。
允许时钟偏移,用于新的容器的第一进程被放置在容器之前进行设置`/proc/PID/timens_offsets`文件
个容器的时钟偏移(/proc/PID/timens_offsets),需要在新的容器的第一个进程创建前进行设置
#### **IPC容器**
......@@ -186,28 +184,23 @@ int clone(int (*fn)(void *), void *stack, int flags, void *arg, ...
- **unshare 接口**
通过 unshare接口,将当前进程脱离当前所属容器,并转移到一个新建的容器。函数原型:
```
int unshare(int flags);
```
参考其他内核的实现,PID容器特殊处理,PID容器通过 unshare/setns 切换时, 是切换子进程的容器,而本进程容器仍然保持不变。
方法是,本进程将新建的容器记录下来,创建子进程时再根据记录信息进行容器归属。
这一点上,与其他容器(如Network容器)有区别,其他容器的setns、unshare操作是直接对已有进程生效。
可以一句话总结为: PID容器的setns和unshare操作,是针对后代进程的PID容器。
说明:PID容器和TIME容器调用unshare时,当前进程的容器不会发生变化,当前进程创建的子进程会被放到新的容器中。
- **setns接口**
通过 setns接口,将当前进程脱离当前所属容器,并转移到一个已有的容器。便于灵活切换进程容器。
PID容器通过 setns 转移时, 是切换子进程的容器,而本进程容器仍然保持不变。同上文。函数原型:
通过 setns接口,将当前进程脱离当前所属容器,并转移到一个已有的容器。便于灵活切换进程容器。函数原型:
```
int setns(int fd, int nstype);
```
说明:PID容器和TIME容器调用setns时,当前进程的容器不会发生变化,当前进程创建的子进程会被放到新的容器中。
### 销毁容器
进程终止时会退出所属容器,并对引用计数进行递减。引用计数减为0的对象,需要进行销毁。
......@@ -220,7 +213,7 @@ int kill(pid_t pid, int sig);
### 查询容器信息
容器隔离之后,系统用户可使用 ls 命令访问 /proc/[pid]/container/ 目录进行查看和确认。
系统用户可使用 ls 命令访问 /proc/[pid]/container/ 目录进行查看和确认。
```
ls -l /proc/[pid]/container
......@@ -257,8 +250,8 @@ ls -l /proc/[pid]/container
| -r--r--r-- | u:0 | g:0 | sched.period | 调度周期配置 | 单位:us |
| -r--r--r-- | u:0 | g:0 | sched.quota | 调度配额配置 | 单位:us |
| -r--r--r-- | u:0 | g:0 | devices.list | 报告plimits中的进程访问的设备 | 输出格式:[type name access] |
| -r--r--r-- | u:0 | g:0 | devices.deny | 指定plimits中的进程可以访问的设备 | 写入格式:["type name access" >> device.deny] |
| -r--r--r-- | u:0 | g:0 | devices.allow | 报告plimits中的进程不能访问的设备 | 写入格式:["type name access" >> device.allow] |
| -r--r--r-- | u:0 | g:0 | devices.deny | 指定plimits中的进程不能访问的设备 | 写入格式:["type name access" >> device.deny] |
| -r--r--r-- | u:0 | g:0 | devices.allow | 报告plimits中的进程可以访问的设备 | 写入格式:["type name access" >> device.allow] |
| -r--r--r-- | u:0 | g:0 | ipc.stat | ipc对象申请统计信息 | 输出格式:[mq count: mq failed count: <br/> shm size: shm failed count: ] |
| -r--r--r-- | u:0 | g:0 | ipc.shm_limit | 共享内存大小上限 | 单位:byte |
| -r--r--r-- | u:0 | g:0 | ipc.mq_limit | 消息个数上限 | 0~最大64位正整数 |
......@@ -312,9 +305,7 @@ inum = CONTAINER_IDEX_BASE + (unsigned int)i;
| CLONE_NEWUTS | 为子进程新建UTSNAME容器 | 将当前进程转移到指定UTSNAME容器 | 为本进程新建UTSNAME容器 |
| CLONE_NEWNET | 为子进程新建Network容器 | 将当前进程转移到指定Network容器 | 为本进程新建Network容器 |
- 容器功能采用编译宏、编译脚本中参数结合,完成特性的开关控制。
- 容器编译宏定义:
- 容器功能采用编译宏,完成特性的开关控制。
```
// 容器功能总编译宏
......@@ -329,15 +320,6 @@ inum = CONTAINER_IDEX_BASE + (unsigned int)i;
LOSCFG_IPC_CONTAINER
```
- 测试用例编译宏定义: enable打开,disable关闭,默认关闭。
```
LOSCFG_USER_TEST_MNT_CONTAINER
LOSCFG_USER_TEST_PID_CONTAINER
LOSCFG_USER_TEST_NET_CONTAINER
LOSCFG_USER_TEST_USER_CONTAINER
LOSCFG_USER_TEST_TIME_CONTAINER
LOSCFG_USER_TEST_IPC_CONTAINER
```
### 开发实例
......
......@@ -132,17 +132,15 @@ static u32 sk_ehashfn(const struct sock *sk)
&sk->sk_v6_daddr, sk->sk_dport);
#endif
#if IS_ENABLED(CONFIG_NEWIP_HOOKS)
if (trace_vendor_ninet_ehashfn_enabled()) {
if (sk->sk_family == AF_NINET) {
u32 ret = 0;
/* New IP注册的ehash函数 */
trace_ninet_ehashfn_hook(sock_net(sk), &sk->sk_nip_rcv_saddr, sk->sk_num,
&sk->sk_nip_daddr, sk->sk_dport, &ret);
trace_vendor_ninet_ehashfn(sk, &ret);
return ret;
}
#endif
}
/* IPv4 */
return inet_ehashfn(sock_net(sk),
sk->sk_rcv_saddr, sk->sk_num,
......@@ -246,7 +244,7 @@ struct sockaddr_nin {
![zh-cn_image-20221009112548444](figures/zh-cn_image-20221009112548444.png)
上图中New IP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony/kernel_common_modules_newip/tree/master/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置New IP地址和路由。
上图中New IP地址,路由配置程序可以参考[代码仓examples代码](https://gitee.com/openharmony/kernel_linux_common_modules/tree/master/newip/examples),根据CPU硬件差异更改Makefile中CC定义编译成二级制文件后推送到开发板,参考上图命令给设备配置New IP地址和路由。
| 文件名 | 功能 |
| ------------------ | -------------------------------------------------------- |
......@@ -276,7 +274,7 @@ struct sockaddr_nin {
## New IP收发包代码示例
New IP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,New IP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony/kernel_common_modules_newip/tree/master/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。
New IP可变长地址配置,路由配置,UDP/TCP收发包demo代码链接如下,New IP协议栈用户态接口使用方法可以参考[代码仓examples代码](https://gitee.com/openharmony/kernel_linux_common_modules/tree/master/newip/examples)。demo代码内配置固定地址和路由,执行编译后二进制程序时不需要人工指定地址和路由。
| 文件名 | 功能 |
| --------------------- | ------------------------------ |
......@@ -375,7 +373,7 @@ allowxperm thread_xxx thread_xxx:socket ioctl { 0x8933 0x8916 0x890B };
## WireShark报文解析模板
Wireshark默认报文解析规则无法解析New IP报文,在WireShark配置中添加New IP报文解析模板可以实现New IP报文解析,[New IP报文解析模板](https://gitee.com/openharmony/kernel_common_modules_newip/blob/master/tools/wireshark_cfg_for_newip.lua)详见代码仓。
Wireshark默认报文解析规则无法解析New IP报文,在WireShark配置中添加New IP报文解析模板可以实现New IP报文解析,[New IP报文解析模板](https://gitee.com/openharmony/kernel_linux_common_modules/blob/master/newip/tools/wireshark_cfg_for_newip.lua)详见代码仓。
报文解析模板配置文件的方法:
......
# 包管理子系统ChangeLog
## cl.bundlemanager.1 底层能力变更,安装hap时,hap中的文件不再解压到安装目录。
安装hap后,安装目录下只会存在hap文件,应用不能再使用拼接路径访问解压后的资源文件,应用想要访问资源文件,需要使用标准的资源管理接口。
**变更影响**<br>
如果应用使用拼接路径的形式访问资源文件,会访问失败。需要修改成使用资源管理接口访问资源文件。
**关键的接口/组件变更**<br>
不涉及接口及组件变更
**适配指导**<br>
资源管理子系统提供Js接口访问资源文件。参考[访问资源文件](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-resource-manager.md#getrawfilecontent9)
# ArkUI子系统ChangeLog
修复问题:[Stack](../../../application-dev/reference/arkui-ts/ts-container-stack.md)设置alignContent,在子组件超出父组件的场景中,子组件未按照alignContent布局
示例:
```ts
@Entry
@Component
struct StackExample {
build() {
Stack({alignContent:Alignment.TopEnd}){
Text('First child, show in bottom')
.width(200).height(200).backgroundColor(0xd2cab3).margin(10)
}.width(150).height(150).backgroundColor(Color.Pink).margin(100)
}
}
```
修复前:子组件未能按照alignContent:Alignment.TopEnd布局
![stack](figures/stack_before.jpg)
修复后:子组件可以按照alignContent:Alignment.TopEnd布局
![stack](figures/stack_after.jpg)
**变更影响**
1. 如果应用中有子组件大小大于父组件Stack的场景,需要应用进行适配。
2. 应用之前可能采用的规避方案:给子组件设置Offset或者translate
**适配指导**
去掉之前给子组件设置的Offset或者translate,使用alignContent实际布局方式进行布局。
\ No newline at end of file
# 开发案例
## 案例介绍
本目录为社区开发者提供OpenHarmony开发典型案例,包括应用开发案例和设备开发案例,主要面向开发者在开发过程中经常使用的功能及其开发场景,提供对应的经验总结、指导教程等。
关于案例的引用规范和声明,请参考[案例库说明](operation-regulations.md)
## 案例目录
## 案例索引
我们通过目录中的Index.md对本目录以及三方网站的开发案例进行链接索引。
## 贡献案例
我们鼓励您积极参与案例贡献。您可以:
* 针对已有案例进行优化提升。
* 贡献全新的案例。
在参与贡献时,您需要注意:
- 您提交的内容、图片必须是原创内容,不得侵犯他人知识产权。
- 对于采纳的内容,OpenHarmony有权根据相关规范修改您提交的内容。
## 案例采纳/退出原则
### 采纳原则
* 案例完整,逻辑清晰。
* 案例具有实际指导意义。
* 案例阅读体验良好。
### 退出原则
* 案例内容陈旧,涉及不再推荐使用的技术方案或接口。
* 案例内容侵犯他人知识产权。
## 三方网站链接说明
本部分含有其他独立第三方网站的链接,该类链接仅供开发者进行开发参考。OpenHarmony开源项目不对链接网站的内容、服务、信息等提供任何明示和暗示的保证,此类链接也不视为OpenHarmony开源项目对链接网站的推荐或授权。您需自行独立判断您与链接网站的互动行为, OpenHarmony开源项目对此不承担任何责任。
## License
Creative Commons License version 4.0
### ArkUI
- [如何按字母分组展示联系人](how-to-group-contacts-with-alphabet.md)
- [如何实现列表项的新增和删除](how-to-add-delete-listitems.md)
- [如何通过显示动画实现书籍翻页动效](book-flip-animation.md)
- [如何为同一组件在不同场景下绑定不同的业务逻辑](different-operations-for-one-component.md)
......
# 如何通过显示动画实现书籍翻页动效
## 场景介绍
翻页动效是应用开发中常见的动效场景,常见的如书籍翻页、日历翻页等。本文就为大家举例讲解如何通过ArkUI提供的显示动画接口[animateTo](../application-dev/reference/arkui-ts/ts-explicit-animation.md)实现书籍翻页的效果。
## 效果呈现
本例最终实现效果如下:
![翻页动效示例图](figures/book-flip-animation.gif)
## 环境要求
- IDE:DevEco Studio 3.1 Beta1
- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
## 实现思路
如图,我们分上下两层、左右两侧建立4个文本组件(下文用A、B、C、D代称),左右两侧分别代表打开书籍的左右两面,上下两层堆叠放置。
当B沿旋转轴旋转180度覆盖在A上时,就体现为翻页效果。一个翻页动作的完成包括以下几步:
1. B沿旋转轴旋转180度。
2. B旋转时,D会在右侧显示出来,作为书籍的下一页,此时D承载的内容要变为下一页的内容。
3. B旋转到左侧后,A承载的内容变为B的内容。
4. 由于A和B互为镜像,所以A显示为B的内容后,需要以A的中间为轴旋转180度。
5. B重新旋转到右边,其承载的内容变为下一页的内容。
***说明:C用来占位,不需要做动作。***
连续重复上述动作即可实现连续翻页动效。
![翻页动效](figures/book-flip-logic.png)
## 开发步骤
1. 创建文本组件
首先,我们看到动效中用到了4个文本组件,我们可以定义一个文本组件,然后对其进行重复调用。创建时我们为其添加[rotate](../application-dev/reference/arkui-ts/ts-universal-attributes-transformation.md)属性,用来控制组件的旋转。
由于各组件旋转的角度和旋转中心不同,需要父组件在调用时传入对应的参数,所以我们为对应变量添加[@Prop](../application-dev/quick-start/arkts-prop.md)装饰器,用来控制变量传递。具体代码如下:
```
@Component
struct BookCard{
// 为变量添加@Prop装饰器,用于接收父组件的动态传参
@Prop num:number
@Prop y_position:string
@Prop x_position:string
@Prop rotate_angle:number
build(){
Text(`${this.num}`)
.fontWeight(FontWeight.Bold)
.backgroundColor('#18183C')
.fontColor('white')
.fontSize(80)
.width('25%')
.height('30%')
.fontFamily('Monospace')
.textAlign(TextAlign.Center)
.borderRadius(20)
// 使用rotate属性控制旋转
.rotate({
x: 0,
y: 1,
z: 0,
angle: this.rotate_angle,
centerY: this.y_position,
centerX: this.x_position
})
}
}
```
2. 创建父组件框架
由于文本组件分为上下两层,所以我们在父组件中采用[Stack](../application-dev/reference/arkui-ts/ts-container-stack.md)组件进行层叠布局。同时使用[Divider](../application-dev/reference/arkui-ts/ts-basic-components-divider.md)组件作为书籍两个页面间的分隔线。具体代码如下:
```
@Entry
@Component
struct BookAnimation {
build(){
Stack(){
Row(){
// 组件C
BookCard()
// 组件D
BookCard()
}
Row(){
// 组件A
BookCard()
// 组件B
BookCard()
}
// 添加两个页面间的分隔线
Divider()
.strokeWidth(5)
.color('white')
.height('26%')
.vertical(true)
}
.width('100%')
.height('100%')
.backgroundColor('#A4AE77')
}
}
```
3. 添加翻页动效
最后我们通过以下几点来为静态的组件添加动效:
- 根据**实现思路**章节的分析,在父组件中定义对应的变量,并在调用子组件时分别传入子组件。
- 自定义book_animate函数,在其中使用animateTo方法添加动画效果,同时控制动画的时长,以及动画过程中各元素状态的改变。
- 在[aboutToAppear](../application-dev/reference/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear)方法中,使用[setInterval](../application-dev/reference/apis/js-apis-timer.md)方法重复调用book_animate函数,以实现连续翻页动效。
具体代码如下:
```
@Entry
@Component
struct BookAnimation {
// 父组件变量设置,注意使用@State做状态管理
@State rotate_angle1:number = 0
@State rotate_angle2:number = 0
@State rotate_angle3:number = 0
@State num_before: number = 0;
@State num: number = 1;
@State num_next: number = 0;
@State y_center1:string = '50%'
@State x_center1:string = '50%'
@State y_center2:string = '0%'
@State x_center2:string = '0%'
// 在UI显示前,传入各项变量的具体值
aboutToAppear() {
// 通过setInterval函数每秒调用一次动画效果,实现连续翻页
setInterval(() => {
this.book_animate()
}, 1000)//函数调用周期要大于每次动画持续的时长
}
private book_animate(){
// 通过animateTo方法为组件添加动效,动效时长要小于setInterval函数调用周期
animateTo({ duration:700,onFinish:()=>{
// 动画结束时,A显示的数字跟B显示的数字相等
this.num_before = this.num
// 动画结束时,A以中心线为轴旋转180度
this.rotate_angle3 = 180
// 动画结束时,B返回至初始状态
this.rotate_angle1 = 0
// 动画结束时,B显示的数字加1
this.num = (this.num + 1) % 10
}
},()=>{
// 动画开始,B的旋转角度变为180度
this.rotate_angle1 = 180
// 动画开始,D的数字加1
this.num_next = this.num+1
})
}
build() {
Stack(){
Row(){
// C组件的引用配置
BookCard({num:0,rotate_angle:this.rotate_angle2,
y_position:this.y_center2,x_position:this.x_center2})
// D组件的引用配置
BookCard({num:this.num_next,rotate_angle:this.rotate_angle2,
y_position:this.y_center2,x_position:this.x_center2})
}
Row(){
// A组件的引用配置
BookCard({num:this.num_before,rotate_angle:this.rotate_angle3,
y_position:this.y_center1,x_position:this.x_center1})
// B组件的引用配置
BookCard({num:this.num,rotate_angle:this.rotate_angle1,
y_position:this.y_center2,x_position:this.x_center2})
}
Divider().strokeWidth(5).color('white').height('26%').vertical(true)
}.width('100%').height('50%').backgroundColor('#A4AE77')
}
}
```
通过以上步骤我们就可以实现翻页动效了。
## 完整代码
示例完整代码如下:
```
@Component
struct BookCard{
@Prop num:number
@Prop y_position:string
@Prop x_position:string
@Prop rotate_angle:number
build(){
Text(`${this.num}`)
.fontWeight(FontWeight.Bold)
.backgroundColor('#18183C')
.fontColor('white')
.fontSize(80)
.width('25%')
.height('30%')
.fontFamily('Monospace')
.textAlign(TextAlign.Center)
.borderRadius(20)
.rotate({
x: 0,
y: 1,
z: 0,
angle: this.rotate_angle,
centerY: this.y_position,
centerX: this.x_position
})
}
}
@Entry
@Component
struct BookAnimation {
@State rotate_angle1:number = 0
@State rotate_angle2:number = 0
@State rotate_angle3:number = 0
@State num_before: number = 0;
@State num: number = 1;
@State num_next: number = 0;
@State y_center1:string = '50%'
@State x_center1:string = '50%'
@State y_center2:string = '0%'
@State x_center2:string = '0%'
aboutToAppear() {
setInterval(() => {
this.book_animate()
}, 1000)
}
private book_animate(){
animateTo({ duration:700,onFinish:()=>{
this.num_before = this.num
this.rotate_angle3 = 180
this.rotate_angle1 = 0
this.num = (this.num + 1) % 10
}
},()=>{
this.rotate_angle1 = 180
this.num_next = this.num+1
})
}
build() {
Stack(){
Row(){
BookCard({num:0,rotate_angle:this.rotate_angle2,y_position:this.y_center2,
x_position:this.x_center2})
BookCard({num:this.num_next,rotate_angle:this.rotate_angle2,y_position:this.y_center2,
x_position:this.x_center2})
}
Row(){
BookCard({num:this.num_before,rotate_angle:this.rotate_angle3,y_position:this.y_center1,
x_position:this.x_center1})
BookCard({num:this.num,rotate_angle:this.rotate_angle1,y_position:this.y_center2,
x_position:this.x_center2})
}
Divider().strokeWidth(5).color('white').height('26%').vertical(true)
}.width('100%').height('50%').backgroundColor('#A4AE77')
}
}
```
# 如何为同一组件在不同场景下绑定不同的业务逻辑
## 场景介绍
我们在应用开发过程中经常遇到这样的场景:在不同的地方需要呈现同样的UI效果,为了简化处理,我们往往会把对应的UI元素封装成自定义组件,然后在用到的地方进行调用。但是,通常情况下,UI展示往往伴随着动态交互,而且在不同场景下需要做不同的交互处理。
*比如:A、B两个页面都有返回按钮,但是在A页面中点击返回按钮是返回上一页,在B页面点击返回按钮是直接退出当前应用。同样是点击返回按钮,但是业务处理逻辑是不同的。*
那么在不同场景下调用同一组件的时候如何实现不同的交互逻辑呢?这就引出了本文要讲的内容。
## 实现思路
要使同一组件实现不同效果,我们很容易就想到通过变量传参进行控制,而不是直接在程序中采用固定值,这样我们就可以根据不同场景传入不同参数从而实现不同效果。
我们通常使用传参的方式改变组件的属性,比如:大小、边框、背景色、字体等等,同样的,我们也可以通过传参的方式改变组件绑定的业务逻辑,只不过,此时我们传入的是方法,然后在对应方法中写入具体的业务逻辑。
接下来我们用一个简单的例子讲解如何实现。
## 开发示例
本示例将在一个页面中两次引用同一个按钮,然后为两次引用加入不同的处理逻辑,第一次引用中,点击按钮跳转到‘’Hello World!’‘页面;第二次引用中,点击按钮跳转到’‘Hello ArkTS!’‘页面。
### 环境要求
- IDE:DevEco Studio 3.1 Beta1
- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
### 开发步骤
1. 创建按钮组件
首先,让我们创建被引用的按钮组件。
这里需要注意的是,由于按钮要绑定不同的处理逻辑,所以我们在点击事件中不要写入固定的处理逻辑,而是传入一个自定义的空方法,该方法的逻辑在父组件中实现,然后传入。具体代码如下:
```ts
@Component
struct ChildComponent{
@State button_text:string = 'hi'
// 定义一个空函数
child_func:()=>void
build(){
Button(`${this.button_text}`)
.height(100)
.width(200)
.onClick(() => {
// 在组件的点击事件中绑定之前定义的空函数
this.child_func()
})
}
}
```
2. 在父组件中引用按钮组件
接下来,我们在父组件中引用两次第1步中创建的按钮组件。具体代码如下:
```ts
@Entry
@Component
struct FuncTransition{
build() {
Column(){
// 引用按钮组件
ChildComponent({button_text:'Hello World'})
.margin(50)
ChildComponent({button_text:'Hello ArkTS'})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
3. 在父组件中传入处理逻辑
以上两步已经把我们的页面框架搭好了,接下来就是给按钮组件传入处理逻辑了,这也是最重要的一步。
我们在第1步中为按钮组件的点击事件绑定了一个空函数,现在我们在父组件中创建一个带有具体处理逻辑的函数,并将其传入按钮组件中。在父组件中可以通过为同一函数传入不同参数来为两个按钮组件绑定不同逻辑,也可以通过不同函数来实现,本例中采用前者进行实现。具体代码如下:
```ts
import router from '@ohos.router'
@Entry
@Component
struct FuncTransition{
// 在父组件中创建逻辑处理函数,此处逻辑为页面跳转。
parent_func(page_url){
router.pushUrl({
url:page_url
})
}
build() {
Column(){
// 在第1处引用的子组件中传入父组件中定义的函数,此处为跳转到''Hello World!''页面
ChildComponent({child_func:()=>{this.parent_func('pages/HelloWorld')},button_text:'Hello World'})
.margin(50)
// 在第2处引用的子组件中传入父组件中定义的函数,此处为跳转到''Hello ArkTS!''页面
ChildComponent({child_func:()=>{this.parent_func('pages/HelloArkTS')},button_text:'Hello ArkTS'})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
通过以上步骤我们实现了在为同一按钮组件绑定不同的业务处理逻辑,接下来就让我们看下效果吧!
注意:文中的‘’Hello World!’‘页面和’‘Hello ArkTS!’‘页面不是本文说明的重点,所以本文中不做开发介绍。
![相同子组件不同业务逻辑](figures/different-operations-one-component.gif)
## 完整代码
示例完整代码如下:
```ts
import router from '@ohos.router'
@Entry
@Component
struct FuncTransition{
parent_func(page_url){
router.pushUrl({
url:page_url
})
}
build() {
Column(){
ChildComponent({child_func:()=>{this.parent_func('pages/HelloWorld')},button_text:'Hello World'})
.margin(50)
ChildComponent({child_func:()=>{this.parent_func('pages/HelloArkTS')},button_text:'Hello ArkTS'})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
@Component
struct ChildComponent{
@State button_text:string = 'hi'
child_func:()=>void
build(){
Button(`${this.button_text}`)
.height(100)
.width(200)
.onClick(() => {
this.child_func()
})
}
}
```
\ No newline at end of file
# 如何实现列表项的新增和删除
## 场景介绍
列表的编辑模式用途十分广泛,常见于待办事项管理、文件管理、备忘录的记录管理等应用场景。在列表的编辑模式下,新增和删除列表项是最基础的功能,其核心是对列表项对应的数据集合进行数据添加和删除。
下面以待办事项管理为例,介绍如何快速实现新增和删除列表项功能。
## 环境要求
- IDE:DevEco Studio 3.1 Beta1
- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
## 新增列表项
如下图所示,当用户点击添加按钮时,将弹出列表项选择界面,用户点击确定后,列表中新增对应项目。
**图17** 新增待办  
![新增列表](figures/add-item.gif)
### 开发步骤
1. 定义列表项数据结构和初始化列表数据,构建列表整体布局和列表项。
以待办事项管理为例,首先定义待办事项的数据结构:
```ts
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true);
name: string;
constructor(name: string) {
this.name = name;
}
}
```
2. 然后,初始化待办事项列表和可选事项列表:
```ts
@State toDoData: ToDo[] = [];
private availableThings: string[] = ['读书', '运动', '旅游', '听音乐', '看电影', '唱歌'];
```
3. 构建UI界面。
初始界面包含“待办”和新增按钮“+”:
```ts
Text('待办')
.fontSize(36)
.margin({ left: 40})
Blank()
Text('+')
.fontWeight(FontWeight.Lighter)
.fontSize(40)
.margin({ right: 30 })
```
构建列表布局并通过ForEach循环渲染列表项:
```ts
List({ space: 10 }) {
ForEach(this.toDoData, (toDoItem) => {
ListItem() {
...
}
}, toDoItem => toDoItem.key)
}
```
4. 为新增按钮绑定点击事件,并在事件中通过TextPickerDialog.show添加新增列表项的逻辑:
```ts
Text('+')
.onClick(() => {
TextPickerDialog.show({
range: this.availableThings, // 将可选事项列表配置到选择对话框中
onAccept: (value: TextPickerResult) => {
this.toDoData.push(new ToDo(this.availableThings[value.index])); // 用户点击确认,将选择的数据添加到待办列表toDoData中
},
})
})
```
## 删除列表项
如下图所示,当用户长按列表项进入删除模式时,提供用户删除列表项选择的交互界面,用户勾选完成后点击删除按钮,列表中删除对应的项目。
**图18** 长按删除待办事项
![删除列表](figures/delete-item.gif)
### 开发步骤
1. 列表的删除功能一般进入编辑模式后才可使用,所以需要提供编辑模式的入口。
以待办列表为例,通过LongPressGesture()监听列表项的长按事件,当用户长按列表项时,进入编辑模式。
```ts
// ToDoListItem.ets
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
...
}
.gesture(
GestureGroup(GestureMode.Exclusive,
LongPressGesture() // 监听长按事件
.onAction(() => {
if (!this.isEditMode) {
this.isEditMode = true; //进入编辑模式
this.selectedItems.push(this.toDoItem); // 记录长按时选中的列表项
}
})
)
)
```
2. 需要响应用户的选择交互,记录要删除的列表项数据。
在待办列表中,通过勾选框的勾选或取消勾选,响应用户勾选列表项变化,记录所有选择的列表项。
```ts
// ToDoListItem.ets
if (this.isEditMode) {
Checkbox()
.onChange((isSelected) => {
if (isSelected) {
this.selectedItems.push(this.toDoItem) // 勾选时,记录选中的列表项
} else {
let index = this.selectedItems.indexOf(this.toDoItem)
if (index !== -1) {
this.selectedItems.splice(index, 1) // 取消勾选时,则将此项从selectedItems中删除
}
}
})
...
}
```
3. 需要响应用户点击删除按钮事件,删除列表中对应的选项。
```ts
// ToDoList.ets
Button('删除')
.onClick(() => {
// 删除选中的列表项对应的toDoData数据
let leftData = this.toDoData.filter((item) => {
return this.selectedItems.find((selectedItem) => selectedItem !== item);
})
this.toDoData = leftData;
this.isEditMode = false;
})
...
```
## 完整示例代码
新增和删除列表项的实现共涉及三个文件,各文件完整代码如下:
1. 待办事项数据结构代码(ToDo.ets):
```ts
// ToDo.ets
import util from '@ohos.util';
export class ToDo {
key: string = util.generateRandomUUID(true)
name: string;
constructor(name: string) {
this.name = name;
}
}
```
2. 待办事项列表代码(ToDoList.ets):
```ts
// ToDoList.ets
import { ToDo } from '../model/ToDo';
import { ToDoListItem } from './ToDoListItem';
@Entry
@Component
struct ToDoList {
@State toDoData: ToDo[] = []
@Watch('onEditModeChange') @State isEditMode: boolean = false
@State selectedItems: ToDo[] = []
private availableThings: string[] = ["读书", "运动", "旅游", '听音乐', '看电影', '唱歌']
saveData(value: string) {
this.toDoData.push(new ToDo(value))
}
onEditModeChange() {
if (!this.isEditMode) {
this.selectedItems = []
}
}
build() {
Column() {
Row() {
if (this.isEditMode) {
Text('X')
.fontSize(20)
.onClick(() => {
this.isEditMode = false;
})
.margin({ left: 20, right: 20 })
Text('已选择' + this.selectedItems.length + '')
.fontSize(24)
} else {
Text('待办')
.fontSize(36)
.margin({ left: 40})
Blank()
Text('+')
.fontWeight(FontWeight.Lighter)
.fontSize(40)
.margin({ right: 30 })
.onClick(() => {
TextPickerDialog.show({
range: this.availableThings,
onAccept: (value: TextPickerResult) => {
this.toDoData.push(new ToDo(this.availableThings[value.index]))
console.info('to do data: ' + JSON.stringify(this.toDoData))
},
})
})
}
}
.height('12%')
.width('100%')
List({ initialIndex: 0, space: 10 }) {
ForEach(this.toDoData, toDoItem => {
ListItem() {
ToDoListItem({
isEditMode: $isEditMode,
toDoItem: toDoItem,
selectedItems: $selectedItems
})
}.padding({ left: 24, right: 24, bottom: 12 })
}, toDoItem => toDoItem.key)
}
.height('73%')
.listDirection(Axis.Vertical)
.edgeEffect(EdgeEffect.Spring)
if (this.isEditMode) {
Row() {
Button('删除')
.width('80%')
.onClick(() => {
let leftData = this.toDoData.filter((item) => {
return this.selectedItems.find((selectedItem) => selectedItem != item)
})
console.log('leftData: ' + leftData);
this.isEditMode = false;
this.toDoData = leftData;
})
.backgroundColor('#ffd75d5d')
}
.height('15%')
}
}
.backgroundColor('#fff1f3f5')
.width('100%')
.height('100%')
}
}
```
3. 待办事项代码(ToDoListItem.ets):
```ts
// ToDoListItem.ets
import { ToDo } from '../model/ToDo';
@Component
export struct ToDoListItem {
@Link isEditMode: boolean
@Link selectedItems: ToDo[]
private toDoItem: ToDo;
hasBeenSelected(): boolean {
return this.selectedItems.indexOf(this.toDoItem) != -1
}
build() {
Flex({ justifyContent: FlexAlign.SpaceBetween, alignItems: ItemAlign.Center }) {
Row({ space: 4 }) {
Circle()
.width(24)
.height(24)
.fill(Color.White)
.borderWidth(3)
.borderRadius(30)
.borderColor('#ffdcdfdf')
.margin({ right: 10 })
Text(`${this.toDoItem.name}`)
.maxLines(1)
.fontSize(24)
.textOverflow({ overflow: TextOverflow.Ellipsis })
}
.padding({ left: 12 })
if (this.isEditMode) {
Checkbox()
.select(this.hasBeenSelected() ? true : false)
.onChange((isSelected) => {
if (isSelected) {
this.selectedItems.push(this.toDoItem)
} else {
let index = this.selectedItems.indexOf(this.toDoItem)
if (index != -1) {
this.selectedItems.splice(index, 1)
}
}
})
.width(24)
.height(24)
}
}
.width('100%')
.height(80)
.padding({
left: 16,
right: 12,
top: 4,
bottom: 4
})
.borderRadius(24)
.linearGradient({
direction: GradientDirection.Right,
colors: this.hasBeenSelected() ? [[0xffcdae, 0.0], [0xFfece2, 1.0]] : [[0xffffff, 0.0], [0xffffff, 1.0]]
})
.gesture(
GestureGroup(GestureMode.Exclusive,
LongPressGesture()
.onAction(() => {
if (!this.isEditMode) {
this.isEditMode = true
this.selectedItems.push(this.toDoItem)
}
})
)
)
}
}
```
\ No newline at end of file
# 如何按字母分组展示联系人(仅UI)
## 场景说明
在通讯录中,需要将联系人按照姓氏的首字母进行分组排列,从而更方便联系人的查找;联系人列表右侧的字母导航可以随列表的滑动而定位到对应字母处;同时,也可以通过字母导航控制列表跳到指定联系人分组。
本例即为大家介绍如何通过实现上述场景。
## 效果呈现
本示例最终效果如下:
![contactlist](figures/contactlist.gif)
## 环境要求
- IDE:DevEco Studio 3.1 Beta1
- SDK:Ohos_sdk_public 3.2.11.9 (API Version 9 Release)
## 实现思路
本例涉及的四个关键特性及其实现方案如下:
- 联系人按字母分组展示:通过List组件显示联系人列表,通过ListItemGroup组件实现联系人分组。
- 联系人右侧呈现字母导航:使用AlphabetIndexer组件实现字母导航,同时通过Stack组件使字母导航浮在联系人列表右侧。
- 滑动联系人列表,右侧字母导航随之变动:通过List组件的onScrollIndex事件获取到联系人列表的滑动位置,并将该位置索引传递给字母导航的selected属性,作为字母导航的被选中项。
- 通过右侧字母导航控制联系人列表滑动到指定分组:通过字母导航的onSelected事件获取选中字母的索引,并将该索引传递给联系人列表的控制器,控制列表滑动到指定分组。
## 开发步骤
针对上述关键特性,具体实现步骤如下:
1、先通过Stack、List、ListItemGroup、AlphabetIndexer等关键组件将UI框架搭建起来。
先构建列表数据,其中Contact为联系人数据类。
```ts
contactGroups: object[] = [
...
{
title: 'D',
contacts: [
new Contact('Donna', $r('app.media.contact6')),
new Contact('朵朵', $r('app.media.contact1')),
],
},
...
{
title: 'K',
contacts: [
new Contact('孔孔', $r('app.media.contact2')),
new Contact('康康', $r('app.media.contact3')),
],
},
{
title: 'L',
contacts: [
new Contact('Lisa', $r('app.media.contact4')),
new Contact('玲玲', $r('app.media.contact5')),
],
},
{
title: 'N',
contacts: [
new Contact('牛牛', $r('app.media.contact6')),
new Contact('Natasha', $r('app.media.contact1')),
],
},
...
]
```
有了列表数据后,我们来构建UI框架,关键代码如下:
```ts
@Entry
@Component
struct ContactList{
...
// 自定义组件groupHeader,作为ListItemGroup的头部组件,即A、B、C等字母列表项
@Builder groupHeader(titleLetter:string){
Text(titleLetter)
.fontSize(20)
.backgroundColor('#fff1f3f5')
.width('100%')
.padding(5)
}
// 创建字母列表作为字母导航的内容
private alphabets:string[] = [ 'A', 'B', 'D', 'G', 'K', 'L', 'N', 'X'];
build() {
Stack({alignContent:Alignment.End}){
List(){
// 循环渲染列表内容
ForEach(this.contactGroups,contactGroup=>{
// 采用ListItemGroup对联系人进行分组,将groupHeader作为ListItemGroup的头部组件
ListItemGroup({header:this.groupHeader(contactGroup.title)}){
ForEach(contactGroup.contacts,contact=>{
ListItem(){
Column(){
Row(){
Image(contact.icon)
...
Text(contact.name)
}
...
Divider().color('#fff1f3f5')
}
...
}
})
}
})
}
...
// 使用AlphabetIndexer组件实现右侧字母导航
AlphabetIndexer({arrayValue:this.alphabets,selected:0})
...
}
}
}
```
完成上述代码,我们的框架就搭建起来了,如图:
![contactframe](figures/contactframe.PNG)
2、接下来我们为UI框架添加逻辑控制。首先,通过List的onScrollIndex事件获取到列表滑动位置的索引,并将索引同步给右侧字母表的selected属性,从而在滑动联系人时,使右侧字母导航随之变动,关键代码如下:
```ts
...
// 创建动态变量,用于指定字母导航的选择项
@State selectedIndex:number = 0;
...
build() {
Stack({alignContent:Alignment.End}){
List({scroller:this.listScroller}){
ForEach(this.contactGroups,contactGroup=>{
ListItemGroup({header:this.groupHeader(contactGroup.title)}){
ForEach(contactGroup.contacts,contact=>{
ListItem(){
...
}
})
}
})
}
...
// 获取联系人列表滑动位置的索引,并将索引通过selectedIndex同步给右侧字母导航
.onScrollIndex((firstIndex:number)=>{
this.selectedIndex = firstIndex
})
AlphabetIndexer({arrayValue:this.alphabets,selected:0})
...
// 指定字母导航的选择项为selectedIndex,完成跟联系人列表的同步
.selected(this.selectedIndex)
...
}
}
```
至此,当我们滑动联系人列表时,就可以让右侧字母导航随之变动了。效果如下:
![listtonav](figures/listtonav.gif)
3、最后,我们通过AlphabetIndexer组件的onSelect事件获取到字母导航选择项的索引,然后通过List组件的scroller控制器控制联系人列表滑动到相同的索引处,从而实现通过右侧字母导航控制联系人列表滑动到指定分组。关键代码如下:
```ts
...
@State selectedIndex:number = 0;
// 创建List组件的scroller控制器:listScroller,用于控制联系人列表的滑动位置
private listScroller:Scroller = new Scroller()
...
build() {
Stack({alignContent:Alignment.End}){
// 将scroller控制器绑定到List组件
List({scroller:this.listScroller}){
ForEach(this.contactGroups,contactGroup=>{
ListItemGroup({header:this.groupHeader(contactGroup.title)}){
ForEach(contactGroup.contacts,contact=>{
ListItem(){
...
}
})
}
})
}
...
AlphabetIndexer({arrayValue:this.alphabets,selected:0})
...
// 获取字母导航中选中字母的索引值,并通过listScroller控制列表滑动到对应索引位置
.onSelect((index:number)=>{
this.listScroller.scrollToIndex(index)
})
...
}
}
```
至此,当我们在右侧字母导航选择某个字母时就可以控制联系人列表跳转到指定分组了,效果如下:
![navtolist](figures/navtolist.gif)
## 完整代码
通过上述步骤我们已经完成了整个示例的开发,现提供本示例的完整代码供大家参考:
联系人数据类代码:
```ts
// ListModel.ets
export default class Contact{
name:string;
icon:Resource;
constructor(name:string,icon:Resource) {
this.name = name
this.icon = icon
}
}
```
案例主代码:
```ts
// Contact.ets
import Contact from '../model/ListModel'
@Entry
@Component
struct ContactList{
// 联系人列表数据
contactGroups: object[] = [
{
title: 'A',
contacts: [
new Contact('艾薇而', $r('app.media.contact1')),
new Contact('安琪', $r('app.media.contact2')),
new Contact('Angela', $r('app.media.contact3')),
],
},
{
title: 'B',
contacts: [
new Contact('Bobe', $r('app.media.contact4')),
new Contact('勃勃', $r('app.media.contact5')),
],
},
{
title: 'D',
contacts: [
new Contact('Donna', $r('app.media.contact6')),
new Contact('朵朵', $r('app.media.contact1')),
],
},
{
title: 'G',
contacts: [
new Contact('Gavin', $r('app.media.contact4')),
new Contact('果味', $r('app.media.contact1')),
],
},
{
title: 'K',
contacts: [
new Contact('孔孔', $r('app.media.contact2')),
new Contact('康康', $r('app.media.contact3')),
],
},
{
title: 'L',
contacts: [
new Contact('Lisa', $r('app.media.contact4')),
new Contact('玲玲', $r('app.media.contact5')),
],
},
{
title: 'N',
contacts: [
new Contact('牛牛', $r('app.media.contact6')),
new Contact('Natasha', $r('app.media.contact1')),
],
},
{
title: 'X',
contacts: [
new Contact('小可爱', $r('app.media.contact2')),
new Contact('徐总是', $r('app.media.contact3')),
new Contact('璇璇', $r('app.media.contact3')),
new Contact('欣欣', $r('app.media.contact3')),
],
},
]
// 自定义组件groupHeader,作为ListItemGroup的头部组件,即A、B、C等字母列表项
@Builder groupHeader(titleLetter:string){
Text(titleLetter)
.fontSize(20)
.backgroundColor('#fff1f3f5')
.width('100%')
.padding(5)
}
// 创建字母列表作为字母导航的内容
private alphabets:string[] = [ 'A', 'B', 'D', 'G', 'K', 'L', 'N', 'X'];
// 创建动态变量,用于指定字母导航的选择项
@State selectedIndex:number = 0;
// 创建List组件的scroller控制器:listScroller,用于控制联系人列表的滑动位置
private listScroller:Scroller = new Scroller()
build() {
Stack({alignContent:Alignment.End}){
// 将scroller控制器绑定到List组件
List({scroller:this.listScroller}){
// 循环渲染列表内容
ForEach(this.contactGroups,contactGroup=>{
// 采用ListItemGroup对联系人进行分组,将groupHeader作为ListItemGroup的头部组件
ListItemGroup({header:this.groupHeader(contactGroup.title)}){
ForEach(contactGroup.contacts,contact=>{
ListItem(){
Column(){
Row(){
Image(contact.icon)
.width(35)
.height(35)
.margin(10)
Text(contact.name)
}
.width('100%')
Divider().color('#fff1f3f5')
}
.justifyContent(FlexAlign.Start)
}
})
}
})
}
.width('100%')
.height('100%')
.scrollBar(BarState.Auto)
// 获取联系人列表滑动位置的索引,并将索引通过selectedIndex同步给右侧字母导航
.onScrollIndex((firstIndex:number)=>{
this.selectedIndex = firstIndex
})
// 使用AlphabetIndexer组件实现右侧字母导航
AlphabetIndexer({arrayValue:this.alphabets,selected:0})
.margin({right:10})
.itemSize(25)
.font({size:15})
// 指定字母导航的选择项为selectedIndex,完成跟联系人列表的同步
.selected(this.selectedIndex)
// 获取选中字母的索引值,通过listScroller控制列表滑动到对应索引位置
.onSelect((index:number)=>{
this.listScroller.scrollToIndex(index)
})
}
}
}
```
## 参考
[创建列表](../application-dev/ui/arkts-layout-development-create-list.md)
\ No newline at end of file
## 贡献案例
我们鼓励您积极参与案例贡献。您可以:
- 针对已有案例进行优化提升。
- 贡献全新的案例。
在参与贡献时,您需要注意:
- 您提交的内容、图片必须是原创内容,不得侵犯他人知识产权。
- 对于采纳的内容,OpenHarmony有权根据相关规范修改您提交的内容。
## 案例采纳/退出原则
### 采纳原则
- 案例完整,逻辑清晰。
- 案例具有实际指导意义。
- 案例阅读体验良好。
### 退出原则
- 案例内容陈旧,涉及不再推荐使用的技术方案或接口。
- 案例内容侵犯他人知识产权。
## 三方网站链接说明
本部分含有其他独立第三方网站的链接,该类链接仅供开发者进行开发参考。OpenHarmony开源项目不对链接网站的内容、服务、信息等提供任何明示和暗示的保证,此类链接也不视为OpenHarmony开源项目对链接网站的推荐或授权。您需自行独立判断您与链接网站的互动行为, OpenHarmony开源项目对此不承担任何责任。
## License
Creative Commons License version 4.0
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册