提交 f3d8a719 编写于 作者: J jiangminsen 提交者: Gitee

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

Signed-off-by: Njiangminsen <jiangminsen@huawei.com>
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
## IDL Overview ## IDL Overview
To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements. To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements.
**Figure 1** IDL interface description **Figure 1** IDL interface description
![IDL-interface-description](./figures/IDL-interface-description.png) ![IDL-interface-description](./figures/IDL-interface-description.png)
...@@ -156,11 +156,13 @@ On DevEco Studio, choose **Tools > SDK Manager** to view the local installation ...@@ -156,11 +156,13 @@ On DevEco Studio, choose **Tools > SDK Manager** to view the local installation
Go to the local installation path, choose **toolchains > 3.x.x.x** (the folder named after the version number), and check whether the executable file of IDL exists. Go to the local installation path, choose **toolchains > 3.x.x.x** (the folder named after the version number), and check whether the executable file of IDL exists.
> **NOTE**: Use the SDK of the latest version. The use of an earlier version may cause errors in some statements. > **NOTE**
>
> Use the SDK of the latest version. The use of an earlier version may cause errors in some statements.
If the executable file does not exist, download the SDK package from the mirror as instructed in the [Release Notes](../../release-notes). The following uses the [3.2 Beta3](../../release-notes/OpenHarmony-v3.2-beta3.md#acquiring-source-code-from-mirrors) as an example. If the executable file does not exist, download the SDK package from the mirror as instructed in the [Release Notes](../../release-notes). The following uses [3.2 Beta3](../../release-notes/OpenHarmony-v3.2-beta3.md) as an example.
For details about how to replace the SDK package, see [Guide to Switching to Full SDK](../quick-start/full-sdk-switch-guide.md). For details about how to replace the SDK package, see [Full SDK Compilation Guide](../quick-start/full-sdk-compile-guide.md).
After obtaining the executable file, perform subsequent development steps based on your scenario. After obtaining the executable file, perform subsequent development steps based on your scenario.
...@@ -176,6 +178,8 @@ You can use TS to create IDL files. ...@@ -176,6 +178,8 @@ You can use TS to create IDL files.
interface OHOS.IIdlTestService { interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data); int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data); void TestStringTransaction([in] String data);
void TestMapTransaction([in] Map<int, int> data);
int TestArrayTransaction([in] String[] data);
} }
``` ```
...@@ -183,7 +187,9 @@ Run the **idl -gen-ts -d *dir* -c dir/IIdlTestService.idl** command in the folde ...@@ -183,7 +187,9 @@ Run the **idl -gen-ts -d *dir* -c dir/IIdlTestService.idl** command in the folde
-*dir* next to **d** is the target output folder. For example, if the target output folder is **IIdlTestServiceTs**, run the **idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl** command in the folder where the executable file is located. The interface file, stub file, and proxy file are generated in the *dir* directory (**IIdlTestServiceTs** directory in this example) in the execution environment. -*dir* next to **d** is the target output folder. For example, if the target output folder is **IIdlTestServiceTs**, run the **idl -gen-ts -d IIdlTestServiceTs -c IIdlTestServiceTs/IIdlTestService.idl** command in the folder where the executable file is located. The interface file, stub file, and proxy file are generated in the *dir* directory (**IIdlTestServiceTs** directory in this example) in the execution environment.
> **NOTE**: The generated interface class file name must be the same as that of the .idl file. Otherwise, an error occurs during code generation. > **NOTE**
>
> The generated interface class file name must be the same as that of the .idl file. Otherwise, an error occurs during code generation.
For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following: For example, for an .idl file named **IIdlTestService.idl** and target output directory named **IIdlTestServiceTs**, the directory structure is similar to the following:
...@@ -203,6 +209,8 @@ The stub class generated by IDL is an abstract implementation of the interface c ...@@ -203,6 +209,8 @@ The stub class generated by IDL is an abstract implementation of the interface c
```ts ```ts
import {testIntTransactionCallback} from "./i_idl_test_service"; import {testIntTransactionCallback} from "./i_idl_test_service";
import {testStringTransactionCallback} from "./i_idl_test_service"; import {testStringTransactionCallback} from "./i_idl_test_service";
import {testMapTransactionCallback} from "./i_idl_test_service";
import {testArrayTransactionCallback} from "./i_idl_test_service";
import IIdlTestService from "./i_idl_test_service"; import IIdlTestService from "./i_idl_test_service";
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
...@@ -211,8 +219,8 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl ...@@ -211,8 +219,8 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
super(des); super(des);
} }
async onRemoteRequestEx(code: number, data, reply, option): Promise<boolean> { async onRemoteMessageRequest(code: number, data, reply, option): Promise<boolean> {
console.log("onRemoteRequestEx called, code = " + code); console.log("onRemoteMessageRequest called, code = " + code);
switch(code) { switch(code) {
case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: { case IdlTestServiceStub.COMMAND_TEST_INT_TRANSACTION: {
let _data = data.readInt(); let _data = data.readInt();
...@@ -231,6 +239,29 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl ...@@ -231,6 +239,29 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
}); });
return true; return true;
} }
case IdlTestServiceStub.COMMAND_TEST_MAP_TRANSACTION: {
let _data = new Map();
let _dataSize = data.readInt();
for (let i = 0; i < _dataSize; ++i) {
let key = data.readInt();
let value = data.readInt();
_data.set(key, value);
}
this.testMapTransaction(_data, (errCode) => {
reply.writeInt(errCode);
});
return true;
}
case IdlTestServiceStub.COMMAND_TEST_ARRAY_TRANSACTION: {
let _data = data.readStringArray();
this.testArrayTransaction(_data, (errCode, returnValue) => {
reply.writeInt(errCode);
if (errCode == 0) {
reply.writeInt(returnValue);
}
});
return true;
}
default: { default: {
console.log("invalid request code" + code); console.log("invalid request code" + code);
break; break;
...@@ -241,17 +272,23 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl ...@@ -241,17 +272,23 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
testIntTransaction(data: number, callback: testIntTransactionCallback): void{} testIntTransaction(data: number, callback: testIntTransactionCallback): void{}
testStringTransaction(data: string, callback: testStringTransactionCallback): void{} testStringTransaction(data: string, callback: testStringTransactionCallback): void{}
testMapTransaction(data: Map<number, number>, callback: testMapTransactionCallback): void{}
testArrayTransaction(data: string[], callback: testArrayTransactionCallback): void{}
static readonly COMMAND_TEST_INT_TRANSACTION = 1; static readonly COMMAND_TEST_INT_TRANSACTION = 1;
static readonly COMMAND_TEST_STRING_TRANSACTION = 2; static readonly COMMAND_TEST_STRING_TRANSACTION = 2;
static readonly COMMAND_TEST_MAP_TRANSACTION = 3;
static readonly COMMAND_TEST_ARRAY_TRANSACTION = 4;
} }
``` ```
You need to inherit the interface class defined in the IDL file and implement the methods in the class. The following code snippet shows how to inherit the **IdlTestServiceStub** interface class and implement the **testIntTransaction** and **testStringTransaction** methods. You need to inherit the interface class defined in the IDL file and implement the methods in the class. The following code snippet shows how to inherit the **IdlTestServiceStub** interface class and implement the **testIntTransaction**, **testStringTransaction**, **testMapTransaction**, and **testArrayTransaction** methods.
```ts ```ts
import {testIntTransactionCallback} from "./i_idl_test_service" import {testIntTransactionCallback} from "./i_idl_test_service"
import {testStringTransactionCallback} from "./i_idl_test_service" import {testStringTransactionCallback} from "./i_idl_test_service"
import {testMapTransactionCallback} from "./i_idl_test_service";
import {testArrayTransactionCallback} from "./i_idl_test_service";
import IdlTestServiceStub from "./idl_test_service_stub" import IdlTestServiceStub from "./idl_test_service_stub"
...@@ -265,6 +302,14 @@ class IdlTestImp extends IdlTestServiceStub { ...@@ -265,6 +302,14 @@ class IdlTestImp extends IdlTestServiceStub {
{ {
callback(0); callback(0);
} }
testMapTransaction(data: Map<number, number>, callback: testMapTransactionCallback): void
{
callback(0);
}
testArrayTransaction(data: string[], callback: testArrayTransactionCallback): void
{
callback(0, 1);
}
} }
``` ```
...@@ -320,11 +365,28 @@ function callbackTestStringTransaction(result: number): void { ...@@ -320,11 +365,28 @@ function callbackTestStringTransaction(result: number): void {
} }
} }
function callbackTestMapTransaction(result: number): void {
if (result == 0) {
console.log('case 3 success');
}
}
function callbackTestArrayTransaction(result: number, ret: number): void {
if (result == 0 && ret == 124) {
console.log('case 4 success');
}
}
var onAbilityConnectDone = { var onAbilityConnectDone = {
onConnect:function (elementName, proxy) { onConnect:function (elementName, proxy) {
let testProxy = new IdlTestServiceProxy(proxy); let testProxy = new IdlTestServiceProxy(proxy);
let testMap = new Map();
testMap.set(1, 1);
testMap.set(1, 2);
testProxy.testIntTransaction(123, callbackTestIntTransaction); testProxy.testIntTransaction(123, callbackTestIntTransaction);
testProxy.testStringTransaction('hello', callbackTestStringTransaction); testProxy.testStringTransaction('hello', callbackTestStringTransaction);
testProxy.testMapTransaction(testMap, callbackTestMapTransaction);
testProxy.testArrayTransaction(['1','2'], callbackTestMapTransaction);
}, },
onDisconnect:function (elementName) { onDisconnect:function (elementName) {
console.log('onDisconnectService onDisconnect'); console.log('onDisconnectService onDisconnect');
......
...@@ -27,8 +27,7 @@ This section uses the operation of using a browser to open a website as an examp ...@@ -27,8 +27,7 @@ This section uses the operation of using a browser to open a website as an examp
"host": "www.test.com", "host": "www.test.com",
"port": "8080", "port": "8080",
// Prefix matching is used. // Prefix matching is used.
"pathStartWith": "query", "pathStartWith": "query"
"type": "text/*"
}, },
{ {
"scheme": "http", "scheme": "http",
...@@ -53,12 +52,11 @@ function implicitStartAbility() { ...@@ -53,12 +52,11 @@ function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let wantInfo = { let wantInfo = {
// Uncomment the line below if you want to implicitly query data only in the specific bundle. // Uncomment the line below if you want to implicitly query data only in the specific bundle.
// bundleName: "com.example.myapplication", // bundleName: 'com.example.myapplication',
"action": "ohos.want.action.viewData", 'action': 'ohos.want.action.viewData',
// entities can be omitted. // entities can be omitted.
"entities": ["entity.system.browsable"], 'entities': ['entity.system.browsable'],
"uri": "https://www.test.com:8080/query/student", 'uri': 'https://www.test.com:8080/query/student'
"type": "text/plain"
} }
context.startAbility(wantInfo).then(() => { context.startAbility(wantInfo).then(() => {
// ... // ...
...@@ -75,6 +73,6 @@ The matching process is as follows: ...@@ -75,6 +73,6 @@ The matching process is as follows:
3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful. 3. If **uri** in the passed **want** parameter is included in **uris** under **skills** of the ability to match, which is concatenated into https://www.test.com:8080/query* (where * is a wildcard), the matching is successful.
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful. 4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills** of the ability to match, the matching is successful.
When there are multiple matching applications, a dialog box is displayed for you to select one of them. The following figure shows an example. If there are multiple matching applications, the system displays a dialog box for you to select one of them. The following figure shows an example.
![](figures/ability-startup-with-implicit-want1.png) ![](figures/ability-startup-with-implicit-want1.png)
\ No newline at end of file
...@@ -43,7 +43,7 @@ ...@@ -43,7 +43,7 @@
- [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**. - [AbilityStageContext](../reference/apis/js-apis-inner-application-abilityStageContext.md): module-level context. It provides **HapModuleInfo** and **Configuration** in addition to those provided by the base class **Context**.
```ts ```ts
import AbilityStage from "@ohos.app.ability.AbilityStage"; import AbilityStage from '@ohos.app.ability.AbilityStage';
export default class MyAbilityStage extends AbilityStage { export default class MyAbilityStage extends AbilityStage {
onCreate() { onCreate() {
let abilityStageContext = this.context; let abilityStageContext = this.context;
...@@ -71,7 +71,7 @@ This topic describes how to use the context in the following scenarios: ...@@ -71,7 +71,7 @@ This topic describes how to use the context in the following scenarios:
- [Obtaining the Application Development Path](#obtaining-the-application-development-path) - [Obtaining the Application Development Path](#obtaining-the-application-development-path)
- [Obtaining and Modifying Encrypted Areas](#obtaining-and-modifying-encrypted-areas) - [Obtaining and Modifying Encryption Areas](#obtaining-and-modifying-encryption-areas)
- [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module) - [Creating Context of Another Application or Module](#creating-context-of-another-application-or-module)
- [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process) - [Subscribing to UIAbility Lifecycle Changes in a Process](#subscribing-to-uiability-lifecycle-changes-in-a-process)
...@@ -84,13 +84,13 @@ The following table describes the application development paths obtained from co ...@@ -84,13 +84,13 @@ The following table describes the application development paths obtained from co
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.| | bundleCodeDir | string | Yes | No | Path for storing the application's installation package, that is, installation directory of the application on the internal storage. |
| tempDir | string | Yes| No| Temporary file directory of the application.<br>Files in this directory are deleted after the application is uninstalled.| | cacheDir | string | Yes| No| Path for storing the application's cache files, that is, cache directory of the application on the internal storage.<br>It is the content of **Storage** of an application under **Settings > Apps & services > Apps**.|
| filesDir | string | Yes| No| File directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.| | filesDir | string | Yes | No | Path for storing the application's common files, that is, file directory of the application on the internal storage.<br>Files in this directory may be synchronized to other directories during application migration or backup.|
| databaseDir | string | Yes| No| Storage directory of the local database.| | preferencesDir | string | Yes | Yes | Path for storing the application's preference files, that is, preferences directory of the application. |
| bundleCodeDir | string | Yes| No| Installation directory of the application on the internal storage.| | tempDir | string | Yes | No | Path for storing the application's temporary files.<br>Files in this directory are deleted after the application is uninstalled.|
| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| | databaseDir | string | Yes | No | Path for storing the application's database, that is, storage directory of the local database. |
| preferencesDir | string | Yes| Yes| Preferences directory of the application.| | distributedFilesDir | string | Yes| No| Path for storing the application's distributed files.|
The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below. The capability of obtaining the application development path is provided by the base class **Context**. This capability is also provided by **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, and **ExtensionContext**. However, the paths obtained from different contexts may differ, as shown below.
...@@ -144,13 +144,19 @@ export default class EntryAbility extends UIAbility { ...@@ -144,13 +144,19 @@ export default class EntryAbility extends UIAbility {
> >
> The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification. > The sample code obtains the sandbox path of the application development path. The absolute path can be obtained by running the **find / -name <fileName>** command in the hdc shell after file creation or modification.
### Obtaining and Modifying Encrypted Areas ### Obtaining and Modifying Encryption Areas
You can read and write [the area attribute in the context](../reference/apis/js-apis-inner-application-context.md) to obtain and set an encrypted area. Two encryption levels are supported: Encrypting application files enhances data security by preventing files from unauthorized access. Different application files require different levels of protection. For private files, such as alarms and wallpapers, the application must place them in the device-level encryption area (EL1) to ensure that they can be accessed before the user enters the password. For sensitive files, such as personal privacy data, the application must place them in the user-level encryption area (EL2).
- AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on. In practice, you need to select a proper encrypted area based on scenario-specific requirements to protect application data security. The proper use of EL1 and the EL2 can efficiently improve the security.
- AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time). > **NOTE**
>
> - AreaMode.EL1: device-level encryption area, which is accessible after the device is powered on.
>
> - AreaMode.EL2: user-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).
You can obtain and set the encryption area by reading and writing the [area attribute in Context](../reference/apis/js-apis-inner-application-context.md).
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -175,14 +181,15 @@ export default class EntryAbility extends UIAbility { ...@@ -175,14 +181,15 @@ export default class EntryAbility extends UIAbility {
### Creating Context of Another Application or Module ### Creating Context of Another Application or Module
The base class **Context** provides the [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) methods for creating the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules. The base class **Context** provides [createBundleContext(bundleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatebundlecontext), [createModuleContext(moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext), and [createModuleContext(bundleName:string, moduleName:string)](../reference/apis/js-apis-inner-application-context.md#contextcreatemodulecontext-1) to create the context of other applications or modules, so as to obtain the resource information, for example, [obtaining the application development paths](#obtaining-the-application-development-path) of other modules.
- Call **createBundleContext(bundleName:string)** to create the context of another application. - Call **createBundleContext(bundleName:string)** to create the context of another application.
> **NOTE** > **NOTE**
> >
> To obtain the context of another application: > To obtain the context of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon. For example, application information displayed on the home screen includes the application name and icon. The home screen application calls the foregoing method to obtain the context information, so as to obtain the resource information including the application name and icon.
...@@ -192,7 +199,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -192,7 +199,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let bundleName2 = "com.example.application"; let bundleName2 = 'com.example.application';
let context2 = this.context.createBundleContext(bundleName2); let context2 = this.context.createBundleContext(bundleName2);
let label2 = context2.applicationInfo.label; let label2 = context2.applicationInfo.label;
// ... // ...
...@@ -205,7 +212,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -205,7 +212,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
> >
> To obtain the context of a specified module of another application: > To obtain the context of a specified module of another application:
> >
> - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). > - Request the **ohos.permission.GET_BUNDLE_INFO_PRIVILEGED** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
>
> - This is a system API and cannot be called by third-party applications. > - This is a system API and cannot be called by third-party applications.
```ts ```ts
...@@ -213,8 +221,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -213,8 +221,8 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let bundleName2 = "com.example.application"; let bundleName2 = 'com.example.application';
let moduleName2 = "module1"; let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(bundleName2, moduleName2); let context2 = this.context.createModuleContext(bundleName2, moduleName2);
// ... // ...
} }
...@@ -228,7 +236,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -228,7 +236,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
let moduleName2 = "module1"; let moduleName2 = 'module1';
let context2 = this.context.createModuleContext(moduleName2); let context2 = this.context.createModuleContext(moduleName2);
// ... // ...
} }
...@@ -238,66 +246,79 @@ The base class **Context** provides the [createBundleContext(bundleName:string)] ...@@ -238,66 +246,79 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
### Subscribing to UIAbility Lifecycle Changes in a Process ### Subscribing to UIAbility Lifecycle Changes in a Process
In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to UIAbility lifecycle changes. In the DFX statistics scenario of an application, if you need to collect statistics on the stay duration and access frequency of a page, you can subscribe to UIAbility lifecycle changes in a process.
[ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered, and a listener ID is returned. The ID is incremented by 1 each time the listener is registered. When the number of listeners exceeds the upper limit (2^63-1), -1 is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example. [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext) provides APIs for subscribing to UIAbility lifecycle changes in a process. When the UIAbility lifecycle changes in a process, for example, being created or destroyed, becoming visible or invisible, or gaining or losing focus, the corresponding callback is triggered. Each time the callback is registered, a listener lifecycle ID is returned, with the value incremented by 1 each time. When the number of listeners exceeds the upper limit (2^63-1), **-1** is returned. The following uses [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md) as an example.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window'; import window from '@ohos.window';
const TAG: string = "[Example].[Entry].[EntryAbility]"; const TAG: string = '[Example].[Entry].[EntryAbility]';
export default class EntryAbility extends UIAbility { export default class EntryAbility extends UIAbility {
// Define a lifecycle ID.
lifecycleId: number; lifecycleId: number;
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Define a lifecycle callback object.
let abilityLifecycleCallback = { let abilityLifecycleCallback = {
onAbilityCreate(uiability) { // Called when a UIAbility is created.
console.info(TAG, "onAbilityCreate uiability:" + JSON.stringify(uiability)); onAbilityCreate(uiAbility) {
console.log(TAG, `onAbilityCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, },
onWindowStageCreate(uiability, windowStage) { // Called when a window is created.
console.info(TAG, "onWindowStageCreate uiability:" + JSON.stringify(uiability)); onWindowStageCreate(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageCreate uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.log(TAG, `onWindowStageCreate windowStage: ${JSON.stringify(windowStage)}`);
}, },
onWindowStageActive(uiability, windowStage) { // Called when the window becomes active.
console.info(TAG, "onWindowStageActive uiability:" + JSON.stringify(uiability)); onWindowStageActive(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageActive windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageActive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.log(TAG, `onWindowStageActive windowStage: ${JSON.stringify(windowStage)}`);
}, },
onWindowStageInactive(uiability, windowStage) { // Called when the window becomes inactive.
console.info(TAG, "onWindowStageInactive uiability:" + JSON.stringify(uiability)); onWindowStageInactive(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageInactive uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.log(TAG, `onWindowStageInactive windowStage: ${JSON.stringify(windowStage)}`);
}, },
onWindowStageDestroy(uiability, windowStage) { // Called when the window is destroyed.
console.info(TAG, "onWindowStageDestroy uiability:" + JSON.stringify(uiability)); onWindowStageDestroy(uiAbility, windowStage: window.WindowStage) {
console.info(TAG, "onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); console.log(TAG, `onWindowStageDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
console.log(TAG, `onWindowStageDestroy windowStage: ${JSON.stringify(windowStage)}`);
}, },
onAbilityDestroy(uiability) { // Called when the UIAbility is destroyed.
console.info(TAG, "onAbilityDestroy uiability:" + JSON.stringify(uiability)); onAbilityDestroy(uiAbility) {
console.log(TAG, `onAbilityDestroy uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, },
onAbilityForeground(uiability) { // Called when the UIAbility is switched from the background to the foreground.
console.info(TAG, "onAbilityForeground uiability:" + JSON.stringify(uiability)); onAbilityForeground(uiAbility) {
console.log(TAG, `onAbilityForeground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, },
onAbilityBackground(uiability) { // Called when the UIAbility is switched from the foreground to the background.
console.info(TAG, "onAbilityBackground uiability:" + JSON.stringify(uiability)); onAbilityBackground(uiAbility) {
console.log(TAG, `onAbilityBackground uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
}, },
onAbilityContinue(uiability) { // Called when UIAbility is continued on another device.
console.info(TAG, "onAbilityContinue uiability:" + JSON.stringify(uiability)); onAbilityContinue(uiAbility) {
console.log(TAG, `onAbilityContinue uiAbility.launchWant: ${JSON.stringify(uiAbility.launchWant)}`);
} }
} }
// 1. Obtain the application context through the context attribute. // Obtain the application context.
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
// 2. Register a listener for the lifecycle changes through the application context. // Register the application lifecycle callback.
this.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); this.lifecycleId = applicationContext.on('abilityLifecycle', abilityLifecycleCallback);
console.info(TAG, "register callback number: " + JSON.stringify(this.lifecycleId)); console.log(TAG, `register callback number: ${this.lifecycleId}`);
} }
// ...
onDestroy() { onDestroy() {
// Obtain the application context.
let applicationContext = this.context.getApplicationContext(); let applicationContext = this.context.getApplicationContext();
applicationContext.off("abilityLifecycle", this.lifecycleId, (error, data) => { // Deregister the application lifecycle callback.
console.info(TAG, "unregister callback success, err: " + JSON.stringify(error)); applicationContext.off('abilityLifecycle', this.lifecycleId);
});
} }
} }
``` ```
...@@ -30,7 +30,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ...@@ -30,7 +30,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground. - An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
- Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. - Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- **When the startAbilityByCall() method is used, verify the call permission.** For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction) and [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). - **When the startAbilityByCall() method is used, verify the call permission.** For details, see [Using Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction) and [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call).
- Verify the **ohos.permission.ABILITY_BACKGROUND_COMMUNICATION** permission. - Verify the **ohos.permission.ABILITY_BACKGROUND_COMMUNICATION** permission.
......
...@@ -76,22 +76,22 @@ In the FA model, you can call **getContext** of **featureAbility** to obtain the ...@@ -76,22 +76,22 @@ In the FA model, you can call **getContext** of **featureAbility** to obtain the
The following code snippet shows how to use **getContext()** to obtain the application context and distributed directory: The following code snippet shows how to use **getContext()** to obtain the application context and distributed directory:
```ts ```ts
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility';
import fileIo from '@ohos.fileio' import fs from '@ohos.file.fs';
(async () => { (async () => {
let dir: string let dir: string;
try { try {
console.info('Begin to getOrCreateDistributedDir') console.info('Begin to getOrCreateDistributedDir');
dir = await featureAbility.getContext().getOrCreateDistributedDir() dir = await featureAbility.getContext().getOrCreateDistributedDir();
console.info('distribute dir is ' + dir) console.info('distribute dir is ' + dir)
} catch (error) { } catch (error) {
console.error('getOrCreateDistributedDir failed with ' + error) console.error('getOrCreateDistributedDir failed with ' + error);
} }
let fd: number; let fd: number;
let path = dir + "/a.txt"; let path = dir + "/a.txt";
fd = fileIo.openSync(path, 0o2 | 0o100, 0o666); fd = fs.openSync(path, fs.OpenMode.READ_WRITE).fd;
fileIo.close(fd); fs.close(fd);
})() })()
``` ```
...@@ -2,20 +2,20 @@ ...@@ -2,20 +2,20 @@
Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications. Users often need to share data (such as a text or an image) from one application to another. The following uses PDF file sharing as an example to describe how to use Want to share data between applications.
Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application selector). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing. Data sharing requires two UIAbility components (one for the sharing party and the other for the shared party) and one system component (used as the application sharing box). When the sharing party initiates data sharing by calling **startAbility()**, the system implicitly matches and displays all applications that support the type of data to share. After the user selects an application, the system starts the application to complete data sharing.
In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing. In this section, data sharing is triggered by touching a button. You can use other ways to trigger data sharing during application development. This section focuses on how to configure Want to implement data sharing.
The following actions are involved for data sharing: The following actions are involved for data sharing:
- **ohos.want.action.select**: action of starting the application selector. - **ohos.want.action.select**: action of starting the application sharing box.
- **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party. - **ohos.want.action.sendData**: action of sending a single data record, that is, transferring data to the shared party.
## Sharing Party ## Sharing Party
The sharing party starts an application selector and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application selector. In the second layer, the data to share is declared The sharing party starts an application sharing box and transfers the data to the shared party. Therefore, Want of the sharing party must be nested at two layers. In the first layer, implicit Want is used together with the **ohos.want.action.select** action to display the application sharing box. In the second layer, the data to share is declared
in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application selector. The shared party obtains the shared data from **parameters**. in the custom field **parameters**, and then the Want that includes the **ohos.want.action.sendData** action and the **parameters** field is transferred to the application sharing box. The shared party obtains the shared data from **parameters**.
```ts ```ts
import common from '@ohos.app.ability.common'; import common from '@ohos.app.ability.common';
...@@ -28,21 +28,21 @@ let fileSize; // Obtain the size of the file to share. ...@@ -28,21 +28,21 @@ let fileSize; // Obtain the size of the file to share.
function implicitStartAbility() { function implicitStartAbility() {
let context = getContext(this) as common.UIAbilityContext; let context = getContext(this) as common.UIAbilityContext;
let wantInfo = { let wantInfo = {
/ This action is used to implicitly match the application selector. / This action is used to implicitly match the application sharing box.
action: 'ohos.want.action.select', action: 'ohos.want.action.select',
// This is the custom parameter in the first layer of Want, // This is the custom parameter in the first layer of Want,
/ which is intended to add information to the application selector. / which is intended to add information to the application sharing box.
parameters: { parameters: {
// MIME type of PDF. // MIME type of PDF.
"ability.picker.type": fileType, 'ability.picker.type': fileType,
"ability.picker.fileNames": [fileName], 'ability.picker.fileNames': [fileName],
"ability.picker.fileSizes": [fileSize], 'ability.picker.fileSizes': [fileSize],
// This is nested Want ,which will be directly sent to the selected application. // This is nested Want ,which will be directly sent to the selected application.
"ability.want.params.INTENT": { 'ability.want.params.INTENT': {
"action": "ohos.want.action.sendData", 'action': 'ohos.want.action.sendData',
"type": "application/pdf", 'type': 'application/pdf',
"parameters": { 'parameters': {
"keyFd": { "type": "FD", "value": fileFd } 'keyFd': { 'type': 'FD', 'value': fileFd }
} }
} }
} }
...@@ -59,7 +59,7 @@ function implicitStartAbility() { ...@@ -59,7 +59,7 @@ function implicitStartAbility() {
> >
> Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md). > Data sharing can be implemented only in FD format. For details about how to obtain the FD and file name, see [File Management](../reference/apis/js-apis-file-fs.md).
In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application selector: In the preceding code, under the custom field **parameters**, the following **ability.picker.*** fields are used to pass the information to be displayed on the application sharing box:
- **ability.picker.type**: file type icon. - **ability.picker.type**: file type icon.
- **ability.picker.fileNames**: file name. - **ability.picker.fileNames**: file name.
...@@ -67,6 +67,7 @@ In the preceding code, under the custom field **parameters**, the following **ab ...@@ -67,6 +67,7 @@ In the preceding code, under the custom field **parameters**, the following **ab
- **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping. - **ability.picker.fileNames** and **ability.picker.fileSizes** are arrays and have a one-to-one mapping.
The following figure shows an example. The following figure shows an example.
![](figures/ability-startup-with-implicit-want2.png) ![](figures/ability-startup-with-implicit-want2.png)
## Shared Party ## Shared Party
......
...@@ -79,7 +79,7 @@ The system matches the **entities** attribute in the **want** parameter passed b ...@@ -79,7 +79,7 @@ The system matches the **entities** attribute in the **want** parameter passed b
- If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails. - If **entities** in the passed **want** parameter is specified, and **entities** under **skills** of an ability is specified but does not contain **entities** in the passed **want** parameter, the matching fails.
Figure 2 Matching rule of entities in the want parameter **Figure 2** Matching rule of entities in the want parameter
![want-entities](figures/want-entities.png) ![want-entities](figures/want-entities.png)
...@@ -88,10 +88,6 @@ The system matches the **entities** attribute in the **want** parameter passed b ...@@ -88,10 +88,6 @@ The system matches the **entities** attribute in the **want** parameter passed b
When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful. When the **uri** and **type** parameters are specified in the **want** parameter to initiate a component startup request, the system traverses the list of installed components and matches the **uris** array under **skills** of the abilities one by one. If one of the **uris** arrays under **skills** matches the **uri** and **type** in the passed **want**, the matching is successful.
Figure 3 Matching rules when uri and type are specified in the want parameter
![want-uri-type1](figures/want-uri-type1.png)
There are four combinations of **uri** and **type** settings. The matching rules are as follows: There are four combinations of **uri** and **type** settings. The matching rules are as follows:
- Neither **uri** or **type** is specified in the **want** parameter. - Neither **uri** or **type** is specified in the **want** parameter.
...@@ -111,11 +107,17 @@ There are four combinations of **uri** and **type** settings. The matching rules ...@@ -111,11 +107,17 @@ There are four combinations of **uri** and **type** settings. The matching rules
- If the **uris** array under **skills** of an ability is unspecified, the matching fails. - If the **uris** array under **skills** of an ability is unspecified, the matching fails.
- If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails. - If the **uris** array under **skills** of an ability contains an element whose [uri is matched](#matching-rules-of-uri) and [type is matched](#matching-rules-of-type), the matching is successful. Otherwise, the matching fails.
Leftmost URI matching: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the **uris** array under **skills** of the ability,
the matching is successful only if the leftmost URI in the passed **want** parameter matches **scheme**, the combination of **scheme** and **host**, or the combination of **scheme**, **host**, and **port**.
To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom. **Figure 3** Matching rules when uri and type are specified in the want parameter
![want-uri-type1](figures/want-uri-type1.png)
Figure 4 Matching rules of uri and type in the want parameter To simplify the description, **uri** and **type** passed in the **want** parameter are called **w_uri** and **w_type**, respectively; the **uris** array under **skills** of an ability to match is called **s_uris**; each element in the array is called **s_uri**. Matching is performed from top to bottom.
**Figure 4** Matching rules of uri and type in the want parameter
![want-uri-type2](figures/want-uri-type2.png) ![want-uri-type2](figures/want-uri-type2.png)
...@@ -128,7 +130,9 @@ To simplify the description, **uri** in the passed **want** parameter is called ...@@ -128,7 +130,9 @@ To simplify the description, **uri** in the passed **want** parameter is called
- If **host** of **s_uri** is unspecified and **scheme** of **w_uri** and **scheme** of **s_uri** are the same, the matching is successful. Otherwise, the matching fails. - If **host** of **s_uri** is unspecified and **scheme** of **w_uri** and **scheme** of **s_uri** are the same, the matching is successful. Otherwise, the matching fails.
- If **path**, **pathStartWith**, and **pathRegex** of **s_uri** are unspecified and **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching fails. - If **port** of **s_uri** is unspecified and the combination of **scheme** and **host** of **w_uri** is the same as the combination of **scheme** and **host** of **s_uri**, the matching is successful. Otherwise, the matching fails.
- If **path**, **pathStartWith**, and **pathRegex** of **s_uri** are unspecified and the combination of **scheme**, **host**, and **port** of **w_uri** is the same as the combination of **scheme**, **host**, and **port** of **s_uri**, the matching is successful. Otherwise, the matching fails.
- If **path** of **s_uri** is specified and the **full path expressions** of **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching of **pathStartWith** continues. - If **path** of **s_uri** is specified and the **full path expressions** of **w_uri** and **s_uri** are the same, the matching is successful. Otherwise, the matching of **pathStartWith** continues.
...@@ -145,6 +149,11 @@ To simplify the description, **uri** in the passed **want** parameter is called ...@@ -145,6 +149,11 @@ To simplify the description, **uri** in the passed **want** parameter is called
> - **Prefix expression**: `scheme://host:port/pathStartWith` > - **Prefix expression**: `scheme://host:port/pathStartWith`
> >
> - **Regular expression**: `scheme://host:port/pathRegex` > - **Regular expression**: `scheme://host:port/pathRegex`
>
> - **Prefix URI expression**: When only **scheme**, a combination of **scheme** and **host**, or a combination of **scheme**, **host**, and **port** is configured in the configuration file, the matching is successful if a URI prefixed with the configuration file is passed in.
> * `scheme://`
> * `scheme://host`
> * `scheme://host:port`
### Matching Rules of type ### Matching Rules of type
......
# Cross-Device Migration (for System Applications Only)] # Cross-Device Migration (for System Applications Only)
## When to Use ## When to Use
...@@ -47,25 +47,16 @@ The table below describes the main APIs used for cross-device migration. For det ...@@ -47,25 +47,16 @@ The table below describes the main APIs used for cross-device migration. For det
## How to Develop ## How to Develop
1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows: 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
```json 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
{
"module": {
"requestPermissions":[
{
"name" : "ohos.permission.DISTRIBUTED_DATASYNC",
}
]
}
}
```
2. Configure the fields related to cross-device migration in the configuration file.
- Configure the application to support migration.
3. Configure the fields related to cross-device migration in the configuration file.
Configure the application to support migration.
Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device. Set the **continuable** field in the **module.json5** file to **true**. The default value is **false**. If this parameter is set to **false**, the application cannot be continued on the target device.
```json ```json
{ {
"module": { "module": {
...@@ -80,26 +71,10 @@ The table below describes the main APIs used for cross-device migration. For det ...@@ -80,26 +71,10 @@ The table below describes the main APIs used for cross-device migration. For det
} }
``` ```
- Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). Configure the application launch type. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).
3. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts
requestPermission() {
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
```
4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator. 4. Implement [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) in the UIAbility of the initiator.
[onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision. [onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue) is called on the initiator. You can save the data in this method to implement application compatibility check and migration decision.
- Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**. - Saving migrated data: You can save the data to be migrated in key-value pairs in **wantParam**.
- Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application. - Checking application compatibility: You can obtain the version number of the target application from **wantParam** and check the compatibility between the target application and the current application.
......
...@@ -11,7 +11,7 @@ Multi-device coordination involves the following scenarios: ...@@ -11,7 +11,7 @@ Multi-device coordination involves the following scenarios:
- [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices) - [Connecting to ServiceExtensionAbility Across Devices](#connecting-to-serviceextensionability-across-devices)
- [Using Cross-Device Ability Call](#using-cross-device-ability-call) - [Using Cross-Device Call](#using-cross-device-call)
## Multi-Device Collaboration Process ## Multi-Device Collaboration Process
...@@ -47,21 +47,9 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -47,21 +47,9 @@ On device A, touch the **Start** button provided by the initiator application to
### How to Develop ### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
}
```
3. Obtain the device ID of the target device. 3. Obtain the device ID of the target device.
...@@ -102,7 +90,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -102,7 +90,7 @@ On device A, touch the **Start** button provided by the initiator application to
abilityName: 'FuncAbility', abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional. moduleName: 'module1', // moduleName is optional.
} }
// context is the ability-level context of the initiator UIAbility. // context is the AbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -118,32 +106,20 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -118,32 +106,20 @@ On device A, touch the **Start** button provided by the initiator application to
### Available APIs ### Available APIs
**Table 2** APIs for starting an ability across devices and returning the result data **Table 2** APIs for starting a UIAbility across devices and returning the result data
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void; | Starts a UIAbility. This API uses an asynchronous callback to return the result when the UIAbility is terminated.| | startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): void; | Starts a UIAbility. This API uses an asynchronous callback to return the result when the UIAbility is terminated.|
| terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void;| Terminates this UIAbility. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**.| | terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback&lt;void&gt;): void;| Terminates this UIAbility. This API uses an asynchronous callback to return the result information. It is used together with **startAbilityForResult**.|
| terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;; | Terminates this UIAbility. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**.| | terminateSelfWithResult(parameter: AbilityResult): Promise&lt;void&gt;; | Terminates this UIAbility. This API uses a promise to return the result information. It is used together with **startAbilityForResult**.|
### How to Develop ### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
}
```
3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). 3. Set the target component parameters on the initiator, and call **startAbilityForResult()** to start the target UIAbility. **data** in the asynchronous callback is used to receive the information returned by the target UIAbility to the initiator UIAbility after the target UIAbility terminates itself. For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
...@@ -154,7 +130,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -154,7 +130,7 @@ On device A, touch the **Start** button provided by the initiator application to
abilityName: 'FuncAbility', abilityName: 'FuncAbility',
moduleName: 'module1', // moduleName is optional. moduleName: 'module1', // moduleName is optional.
} }
// context is the ability-level context of the initiator UIAbility. // context is the AbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -174,7 +150,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -174,7 +150,7 @@ On device A, touch the **Start** button provided by the initiator application to
moduleName: 'module1', moduleName: 'module1',
}, },
} }
// context is the ability-level context of the target UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { this.context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
...@@ -187,7 +163,7 @@ On device A, touch the **Start** button provided by the initiator application to ...@@ -187,7 +163,7 @@ On device A, touch the **Start** button provided by the initiator application to
// ... // ...
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { this.context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the target UIAbility. // Parse the information returned by the target UIAbility.
...@@ -218,21 +194,9 @@ A system application can connect to a service on another device by calling [conn ...@@ -218,21 +194,9 @@ A system application can connect to a service on another device by calling [conn
### How to Develop ### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows: 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
}
```
3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available. 3. (Optional) [Implement a background service](serviceextensionability.md#implementing-a-background-service). Perform this operation only if no background service is available.
...@@ -303,56 +267,45 @@ A system application can connect to a service on another device by calling [conn ...@@ -303,56 +267,45 @@ A system application can connect to a service on another device by calling [conn
``` ```
## Using Cross-Device Ability Call ## Using Cross-Device Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only). The basic principle of cross-device call is the same as that of intra-device call. For details, see [Using Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call. The following describes how to implement multi-device collaboration through cross-device call.
### Available APIs ### Available APIs
**Table 4** Ability call APIs **Table 4** Call APIs
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.| | startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the CalleeAbility.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;| Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;| Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
### How to Develop ### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts 2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
}
```
3. Create the callee ability. 3. Create the CalleeAbility.
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. For the CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
1. Configure the launch type of the UIAbility. 1. Configure the launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
Set **launchType** of the CalleeAbility to **singleton** in the **module.json5** file.
| JSON Field| Description| | JSON Field| Description|
| -------- | -------- | | -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.| | "launchType"| UIAbility launch type. Set this parameter to **singleton**.|
An example of the UIAbility configuration is as follows: An example of the UIAbility configuration is as follows:
...@@ -375,7 +328,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -375,7 +328,7 @@ The following describes how to implement multi-device collaboration through cros
``` ```
3. Define the agreed parcelable data. 3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
```ts ```ts
...@@ -403,7 +356,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -403,7 +356,7 @@ The following describes how to implement multi-device collaboration through cros
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the UIAbility and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts ```ts
const TAG: string = '[CalleeAbility]'; const TAG: string = '[CalleeAbility]';
...@@ -412,13 +365,13 @@ The following describes how to implement multi-device collaboration through cros ...@@ -412,13 +365,13 @@ The following describes how to implement multi-device collaboration through cros
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called'); console.info('CalleeSortFunc called');
// Obtain the parcelable data sent by the caller ability. // Obtain the parcelable data sent by the CallerAbility.
let receivedData = new MyParcelable(0, ''); let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData); data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the parcelable data result to the caller ability. // Return the parcelable data result to the CallerAbility.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
...@@ -441,7 +394,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -441,7 +394,7 @@ The following describes how to implement multi-device collaboration through cros
} }
``` ```
4. Obtain the caller object and access the callee ability. 4. Obtain the caller object and access the CalleeAbility.
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
```ts ```ts
...@@ -449,7 +402,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -449,7 +402,7 @@ The following describes how to implement multi-device collaboration through cros
``` ```
2. Obtain the caller object. 2. Obtain the caller object.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **context** attribute of the UIAbility implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the UIAbility, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** and **onRemoteStateChange** listeners of the CallerAbility. You need to implement processing based on service requirements.
```ts ```ts
...@@ -465,11 +418,19 @@ The following describes how to implement multi-device collaboration through cros ...@@ -465,11 +418,19 @@ The following describes how to implement multi-device collaboration through cros
if (data != null) { if (data != null) {
caller = data; caller = data;
console.info('get remote caller success'); console.info('get remote caller success');
// Register the onRelease() listener of the caller ability. // Register the onRelease listener of the CallerAbility.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`); console.info(`remote caller onRelease is called ${msg}`);
}) })
console.info('remote caller register OnRelease succeed'); console.info('remote caller register OnRelease succeed');
// Register the onRemoteStateChange listener of the CallerAbility.
try {
caller.onRemoteStateChange((str) => {
console.log('Remote state changed ' + str);
});
} catch (error) {
console.log('Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}');
}
} }
}).catch((error) => { }).catch((error) => {
console.error(`get remote caller failed with ${error}`); console.error(`get remote caller failed with ${error}`);
...@@ -479,8 +440,8 @@ The following describes how to implement multi-device collaboration through cros ...@@ -479,8 +440,8 @@ The following describes how to implement multi-device collaboration through cros
For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned). For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
5. Sends agreed parcelable data to the callee ability. 5. Sends agreed parcelable data to the CalleeAbility.
1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. 1. The parcelable data can be sent to the CalleeAbility with or without a return value. The method and parcelable data must be consistent with those of the CalleeAbility. The following example describes how to send data to the CalleeAbility.
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -493,7 +454,7 @@ The following describes how to implement multi-device collaboration through cros ...@@ -493,7 +454,7 @@ The following describes how to implement multi-device collaboration through cros
} }
} }
``` ```
2. In the following, **CallWithResult** is used to send data **originMsg** to the callee ability and assign the data processed by the **CallSendMsg** method to **backMsg**. 2. In the following, **CallWithResult** is used to send data **originMsg** to the CalleeAbility and assign the data processed by the **CallSendMsg** method to **backMsg**.
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
......
...@@ -30,18 +30,14 @@ Missions are managed by system applications (such as home screen), rather than t ...@@ -30,18 +30,14 @@ Missions are managed by system applications (such as home screen), rather than t
A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created. A UIAbility instance corresponds to an independent mission. Therefore, when an application calls [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start a UIAbility, a mission is created.
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
To call [missionManager](../reference/apis/js-apis-application-missionManager.md) to manage missions, the home screen application must request the **ohos.permission.MANAGE_MISSIONS** permission. For details about the configuration, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions.
```ts
import missionManager from '@ohos.app.ability.missionManager'
You can use **missionManager** to manage missions, for example, listening for mission changes, obtaining mission information or snapshots, and clearing, locking, or unlocking missions. The sample code is as follows: let listener = {
```ts
import missionManager from '@ohos.app.ability.missionManager'
let listener = {
// Listen for mission creation. // Listen for mission creation.
onMissionCreated: function (mission) { onMissionCreated: function (mission) {
console.info("--------onMissionCreated-------") console.info("--------onMissionCreated-------")
...@@ -70,62 +66,64 @@ let listener = { ...@@ -70,62 +66,64 @@ let listener = {
onMissionClosed: function (mission) { onMissionClosed: function (mission) {
console.info("--------onMissionClosed-------") console.info("--------onMissionClosed-------")
} }
}; };
// 1. Register a mission change listener. // 1. Register a mission change listener.
let listenerId = missionManager.on('mission', listener); let listenerId = missionManager.on('mission', listener);
// 2. Obtain the latest 20 missions in the system. // 2. Obtain the latest 20 missions in the system.
missionManager.getMissionInfos("", 20, (error, missions) => { missionManager.getMissionInfos("", 20, (error, missions) => {
console.info("getMissionInfos is called, error.code = " + error.code); console.info("getMissionInfos is called, error.code = " + error.code);
console.info("size = " + missions.length); console.info("size = " + missions.length);
console.info("missions = " + JSON.stringify(missions)); console.info("missions = " + JSON.stringify(missions));
}); });
// 3. Obtain the detailed information about a mission. // 3. Obtain the detailed information about a mission.
let missionId = 11; // The mission ID 11 is only an example. let missionId = 11; // The mission ID 11 is only an example.
let mission = missionManager.getMissionInfo("", missionId).catch(function (err) { let mission = missionManager.getMissionInfo("", missionId).catch(function (err) {
console.info(err); console.info(err);
}); });
// 4. Obtain the mission snapshot. // 4. Obtain the mission snapshot.
missionManager.getMissionSnapShot("", missionId, (error, snapshot) => { missionManager.getMissionSnapShot("", missionId, (error, snapshot) => {
console.info("getMissionSnapShot is called, error.code = " + error.code); console.info("getMissionSnapShot is called, error.code = " + error.code);
console.info("bundleName = " + snapshot.ability.bundleName); console.info("bundleName = " + snapshot.ability.bundleName);
}) })
// 5. Obtain the low-resolution mission snapshot. // 5. Obtain the low-resolution mission snapshot.
missionManager.getLowResolutionMissionSnapShot("", missionId, (error, snapshot) => { missionManager.getLowResolutionMissionSnapShot("", missionId, (error, snapshot) => {
console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code); console.info("getLowResolutionMissionSnapShot is called, error.code = " + error.code);
console.info("bundleName = " + snapshot.ability.bundleName); console.info("bundleName = " + snapshot.ability.bundleName);
}) })
// 6. Lock or unlock the mission. // 6. Lock or unlock the mission.
missionManager.lockMission(missionId).then(() => { missionManager.lockMission(missionId).then(() => {
console.info("lockMission is called "); console.info("lockMission is called ");
}); });
missionManager.unlockMission(missionId).then(() => { missionManager.unlockMission(missionId).then(() => {
console.info("unlockMission is called "); console.info("unlockMission is called ");
}); });
// 7. Switch the mission to the foreground. // 7. Switch the mission to the foreground.
missionManager.moveMissionToFront(missionId).then(() => { missionManager.moveMissionToFront(missionId).then(() => {
console.info("moveMissionToFront is called "); console.info("moveMissionToFront is called ");
}); });
// 8. Clear a single mission. // 8. Clear a single mission.
missionManager.clearMission(missionId).then(() => { missionManager.clearMission(missionId).then(() => {
console.info("clearMission is called "); console.info("clearMission is called ");
}); });
// 9. Clear all missions. // 9. Clear all missions.
missionManager.clearAllMissions().catch(function (err) { missionManager.clearAllMissions().catch(function (err) {
console.info(err); console.info(err);
}); });
// 10. Deregister the mission change listener. // 10. Deregister the mission change listener.
missionManager.off('mission', listenerId, (error) => { missionManager.off('mission', listenerId, (error) => {
console.info("unregisterMissionListener"); console.info("unregisterMissionListener");
}) })
``` ```
...@@ -9,37 +9,7 @@ During application development, you must declare the required permission in the ...@@ -9,37 +9,7 @@ During application development, you must declare the required permission in the
To declare a permission in **config.json**, add **reqPermissions** under **module** and list the permission. To declare a permission in **config.json**, add **reqPermissions** under **module** and list the permission.
For example, to request the permission to access the calendar, perform the following steps:
For example, to declare the permission to access the calendar, request the **ohos.permission.READ_CALENDAR** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Display a dialog box to ask authorization from the user when the application is started for the first time. For details, see [Requesting User Authorization](../security/accesstoken-guidelines.md#requesting-user-authorization).
The sample code in the **config.json** file is as follows:
```json
{
"module": {
// ...
"reqPermissions": [
{
"name": "ohos.permission.READ_CALENDAR"
// ...
}
]
}
}
```
Request the permission from uses in the form of a dialog box:
```ts
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
context.requestPermissionsFromUser(permissions, 1).then((data) => {
console.info("Succeed to request permission from user with data: " + JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: " + JSON.stringify(error))
})
```
...@@ -80,7 +80,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub** ...@@ -80,7 +80,7 @@ Before using the APIs provided by **EventHub**, you must obtain an **EventHub**
4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event. 4. After **event1** is used, you can call [eventHub.off()](../reference/apis/js-apis-inner-application-eventHub.md#eventhuboff) to unsubscribe from the event.
```ts ```ts
// context is the ability-level context of the UIAbility instance. // context is the AbilityContext of the UIAbility instance.
this.context.eventHub.off('event1'); this.context.eventHub.off('event1');
``` ```
...@@ -240,10 +240,6 @@ The following provides an example to describe the object overwritten problem in ...@@ -240,10 +240,6 @@ The following provides an example to describe the object overwritten problem in
struct Index { struct Index {
onPageShow() { onPageShow() {
let ctx = globalThis.context; // Obtain the context from globalThis and use it. let ctx = globalThis.context; // Obtain the context from globalThis and use it.
let permissions = ['com.example.permission']
ctx.requestPermissionsFromUser(permissions,(result) => {
// ...
});
} }
// Page display. // Page display.
build() { build() {
...@@ -274,10 +270,6 @@ The following provides an example to describe the object overwritten problem in ...@@ -274,10 +270,6 @@ The following provides an example to describe the object overwritten problem in
struct Index { struct Index {
onPageShow() { onPageShow() {
let ctx = globalThis.context; // Obtain the context from globalThis and use it. let ctx = globalThis.context; // Obtain the context from globalThis and use it.
let permissions = ['com.example.permission']
ctx.requestPermissionsFromUser(permissions,(result) => {
console.info('requestPermissionsFromUser result:' + JSON.stringify(result));
});
} }
// Page display. // Page display.
build() { build() {
...@@ -307,10 +299,6 @@ The following provides an example to describe the object overwritten problem in ...@@ -307,10 +299,6 @@ The following provides an example to describe the object overwritten problem in
struct Index { struct Index {
onPageShow() { onPageShow() {
let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB. let ctx = globalThis.context; // The context in globalThis is the context of UIAbilityB.
let permissions=['com.example.permission'];
ctx.requestPermissionsFromUser(permissions,(result) => { // Using this object causes a process breakdown.
console.info('requestPermissionsFromUser result:' + JSON.stringify(result));
});
} }
// Page display. // Page display.
build() { build() {
......
...@@ -19,7 +19,7 @@ This topic describes the UIAbility interaction modes in the following scenarios. ...@@ -19,7 +19,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) - [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only) - [Using Call to Implement UIAbility Interaction (for System Applications Only)](#using-call-to-implement-uiability-interaction-for-system-applications-only)
## Starting UIAbility in the Same Application ## Starting UIAbility in the Same Application
...@@ -31,6 +31,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -31,6 +31,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
...@@ -40,15 +41,15 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -40,15 +41,15 @@ Assume that your application has two UIAbility components: EntryAbility and Func
info: 'From the Index page of EntryAbility', info: 'From the Index page of EntryAbility',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
}) })
``` ```
2. Use the FuncAbility lifecycle callback to receive the parameters passed from EntryAbility. 2. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility.
```ts ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -56,7 +57,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -56,7 +57,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
export default class FuncAbility extends UIAbility { export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
let funcAbilityWant = want; let funcAbilityWant = want;
let info = funcAbilityWant?.parameters?.info; let info = funcAbilityWant?.parameters?.info;
// ... // ...
...@@ -64,11 +65,17 @@ Assume that your application has two UIAbility components: EntryAbility and Func ...@@ -64,11 +65,17 @@ Assume that your application has two UIAbility components: EntryAbility and Func
} }
``` ```
> **NOTE**<br>
>
> In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter.
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. 3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility.
```ts ```ts
// context is the ability-level context of the UIAbility instance to stop. let context = ...; // UIAbilityContext
this.context.terminateSelf((err) => {
// context is the UIAbilityContext of the UIAbility instance to stop.
context.terminateSelf((err) => {
// ... // ...
}); });
``` ```
...@@ -87,6 +94,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -87,6 +94,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
...@@ -96,8 +104,8 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -96,8 +104,8 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
info: 'From the Index page of EntryAbility', info: 'From the Index page of EntryAbility',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => { context.startAbilityForResult(wantInfo).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
...@@ -107,6 +115,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -107,6 +115,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility. 2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility.
```ts ```ts
let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
let abilityResult = { let abilityResult = {
resultCode: RESULT_CODE, resultCode: RESULT_CODE,
...@@ -119,8 +128,8 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -119,8 +128,8 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
}, },
}, },
} }
// context is the ability-level context of the callee UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
...@@ -128,14 +137,15 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -128,14 +137,15 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value. 3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value.
```ts ```ts
let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
// ... // ...
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { context.startAbilityForResult(wantInfo).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the callee UIAbility. // Parse the information returned by the target UIAbility.
let info = data.want?.parameters?.info; let info = data.want?.parameters?.info;
// ... // ...
} }
...@@ -147,7 +157,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned ...@@ -147,7 +157,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
## Starting UIAbility of Another Application ## Starting UIAbility of Another Application
Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the caller. Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the initiator UIAbility.
There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md). There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md).
...@@ -183,9 +193,10 @@ This section describes how to start the UIAbility of another application through ...@@ -183,9 +193,10 @@ This section describes how to start the UIAbility of another application through
} }
``` ```
2. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 2. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
// Uncomment the line below if you want to implicitly query data only in the specific bundle. // Uncomment the line below if you want to implicitly query data only in the specific bundle.
...@@ -195,8 +206,8 @@ This section describes how to start the UIAbility of another application through ...@@ -195,8 +206,8 @@ This section describes how to start the UIAbility of another application through
entities: ['entity.system.default'], entities: ['entity.system.default'],
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
...@@ -209,8 +220,10 @@ This section describes how to start the UIAbility of another application through ...@@ -209,8 +220,10 @@ This section describes how to start the UIAbility of another application through
3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). 3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
```ts ```ts
// context is the ability-level context of the UIAbility instance to stop. let context = ...; // UIAbilityContext
this.context.terminateSelf((err) => {
// context is the AbilityContext of the UIAbility instance to stop.
context.terminateSelf((err) => {
// ... // ...
}); });
``` ```
...@@ -246,9 +259,10 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -246,9 +259,10 @@ If you want to obtain the return result when using implicit Want to start the UI
} }
``` ```
2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. 2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the initiator UIAbility's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the initiator UIAbility after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select.
```ts ```ts
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
// Uncomment the line below if you want to implicitly query data only in the specific bundle. // Uncomment the line below if you want to implicitly query data only in the specific bundle.
...@@ -258,8 +272,8 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -258,8 +272,8 @@ If you want to obtain the return result when using implicit Want to start the UI
entities: ['entity.system.default'], entities: ['entity.system.default'],
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(wantInfo).then((data) => { context.startAbilityForResult(wantInfo).then((data) => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
...@@ -269,6 +283,7 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -269,6 +283,7 @@ If you want to obtain the return result when using implicit Want to start the UI
3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter. 3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter.
```ts ```ts
let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
let abilityResult = { let abilityResult = {
resultCode: RESULT_CODE, resultCode: RESULT_CODE,
...@@ -281,8 +296,8 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -281,8 +296,8 @@ If you want to obtain the return result when using implicit Want to start the UI
}, },
}, },
} }
// context is the ability-level context of the callee UIAbility. // context is the AbilityContext of the target UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => { context.terminateSelfWithResult(abilityResult, (err) => {
// ... // ...
}); });
``` ```
...@@ -290,16 +305,17 @@ If you want to obtain the return result when using implicit Want to start the UI ...@@ -290,16 +305,17 @@ If you want to obtain the return result when using implicit Want to start the UI
4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). 4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult).
```ts ```ts
let context = ...; // UIAbilityContext
const RESULT_CODE: number = 1001; const RESULT_CODE: number = 1001;
let want = { let want = {
// Want parameter information. // Want parameter information.
}; };
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbilityForResult(want).then((data) => { context.startAbilityForResult(want).then((data) => {
if (data?.resultCode === RESULT_CODE) { if (data?.resultCode === RESULT_CODE) {
// Parse the information returned by the callee UIAbility. // Parse the information returned by the target UIAbility.
let payResult = data.want?.parameters?.payResult; let payResult = data.want?.parameters?.payResult;
// ... // ...
} }
...@@ -323,7 +339,7 @@ The window mode is specified by the **windowMode** field in the [StartOptions](. ...@@ -323,7 +339,7 @@ The window mode is specified by the **windowMode** field in the [StartOptions](.
> **NOTE** > **NOTE**
> >
> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. > 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities tag](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. > 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities](../quick-start/module-configuration-file.md#abilities) tag in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported.
The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page. The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page.
...@@ -335,6 +351,7 @@ For details about how to obtain the context, see [Obtaining the Context of UIAbi ...@@ -335,6 +351,7 @@ For details about how to obtain the context, see [Obtaining the Context of UIAbi
```ts ```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant'; import AbilityConstant from '@ohos.app.ability.AbilityConstant';
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
...@@ -347,8 +364,8 @@ let wantInfo = { ...@@ -347,8 +364,8 @@ let wantInfo = {
let options = { let options = {
windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo, options).then(() => { context.startAbility(wantInfo, options).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
...@@ -365,10 +382,11 @@ A UIAbility component can have multiple pages. When it is started in different s ...@@ -365,10 +382,11 @@ A UIAbility component can have multiple pages. When it is started in different s
### Specifying a Startup Page ### Specifying a Startup Page
When the caller UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). When the initiator UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
```ts ```ts
let context = ...; // UIAbilityContext
let wantInfo = { let wantInfo = {
deviceId: '', // An empty deviceId indicates the local device. deviceId: '', // An empty deviceId indicates the local device.
bundleName: 'com.example.myapplication', bundleName: 'com.example.myapplication',
...@@ -378,8 +396,8 @@ let wantInfo = { ...@@ -378,8 +396,8 @@ let wantInfo = {
router: 'funcA', router: 'funcA',
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => { context.startAbility(wantInfo).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
// ... // ...
...@@ -400,12 +418,12 @@ export default class FuncAbility extends UIAbility { ...@@ -400,12 +418,12 @@ export default class FuncAbility extends UIAbility {
funcAbilityWant; funcAbilityWant;
onCreate(want, launchParam) { onCreate(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
this.funcAbilityWant = want; this.funcAbilityWant = want;
} }
onWindowStageCreate(windowStage: Window.WindowStage) { onWindowStageCreate(windowStage: Window.WindowStage) {
// Main window is created. Set a main page for this ability. // Main window is created. Set a main page for this UIAbility.
let url = 'pages/Index'; let url = 'pages/Index';
if (this.funcAbilityWant?.parameters?.router) { if (this.funcAbilityWant?.parameters?.router) {
if (this.funcAbilityWant.parameters.router === 'funA') { if (this.funcAbilityWant.parameters.router === 'funA') {
...@@ -435,7 +453,7 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -435,7 +453,7 @@ In summary, when a UIAbility instance of application A has been created and the
export default class FuncAbility extends UIAbility { export default class FuncAbility extends UIAbility {
onNewWant(want, launchParam) { onNewWant(want, launchParam) {
// Receive the parameters passed by the caller UIAbility. // Receive the parameters passed by the initiator UIAbility.
globalThis.funcAbilityWant = want; globalThis.funcAbilityWant = want;
// ... // ...
} }
...@@ -469,140 +487,123 @@ In summary, when a UIAbility instance of application A has been created and the ...@@ -469,140 +487,123 @@ In summary, when a UIAbility instance of application A has been created and the
> **NOTE** > **NOTE**
> >
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. > When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the target UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction (for System Applications Only) ## Using Call to Implement UIAbility Interaction (for System Applications Only)
Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two UIAbility instances (caller ability and callee ability) through IPC. Call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility invoked can be either started in the foreground or created and run in the background. You can use the call to implement data sharing between two UIAbility instances (CallerAbility and CalleeAbility) through IPC.
The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways: The core API used for the call is **startAbilityByCall**, which differs from **startAbility** in the following ways:
- **startAbilityByCall** supports ability launch in the foreground and background, whereas **startAbility** supports ability launch in the foreground only. - **startAbilityByCall** supports UIAbility launch in the foreground and background, whereas **startAbility** supports UIAbility launch in the foreground only.
- The caller ability can use the caller object returned by **startAbilityByCall** to communicate with the callee ability, but **startAbility** does not provide the communication capability. - The CallerAbility can use the caller object returned by **startAbilityByCall** to communicate with the CalleeAbility, but **startAbility** does not provide the communication capability.
Ability call is usually used in the following scenarios: Call is usually used in the following scenarios:
- Communicating with the callee ability - Communicating with the CalleeAbility
- Starting the callee ability in the background - Starting the CalleeAbility in the background
**Table 1** Terms used in the ability call **Table 1** Terms used in the call
| **Term**| Description| | **Term**| Description|
| -------- | -------- | | -------- | -------- |
| CallerAbility | UIAbility that triggers the ability call.| | CallerAbility| UIAbility that triggers the call.|
| CalleeAbility | UIAbility invoked by the ability call.| | CalleeAbility | UIAbility invoked by the call.|
| Caller | Object returned by **startAbilityByCall** and used by the caller ability to communicate with the callee ability.| | Caller | Object returned by **startAbilityByCall** and used by the CallerAbility to communicate with the CalleeAbility.|
| Callee | Object held by the callee ability to communicate with the caller ability.| | Callee | Object held by the CalleeAbility to communicate with the CallerAbility.|
The following figure shows the ability call process. The following figure shows the call process.
Figure 1 Ability call process Figure 1 Call process
![call](figures/call.png) ![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability. - The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility.
- The callee ability, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. - The CalleeAbility, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the CalleeAbility receives data from the CallerAbility.
> **NOTE** > **NOTE**
> 1. Currently, only system applications can use the ability call. > 1. Currently, only system applications can use the call.
> >
> 2. The launch type of the callee ability must be **singleton**. > 2. The launch type of the CalleeAbility must be **singleton**.
> >
> 3. Both local (intra-device) and cross-device ability calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device ability call, see [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call). > 3. Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call).
### Available APIs ### Available APIs
The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). The following table describes the main APIs used for the call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller).
**Table 2** Ability call APIs **Table 2** Call APIs
| API| Description| | API| Description|
| -------- | -------- | | -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).| | startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.| | on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.| | off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.| | call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the CalleeAbility.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.| | callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.|
| release(): void | Releases the caller object.| | release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| | on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
The implementation of using the ability call for UIAbility interaction involves two parts. The implementation of using the call for UIAbility interaction involves two parts.
- [Creating a Callee Ability](#creating-a-callee-ability)
- [Accessing the Callee Ability](#accessing-the-callee-ability) - [Creating a CalleeAbility](#creating-a-calleeability)
- [Accessing the CalleeAbility](#accessing-the-calleeability)
### Creating a Callee Ability
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener. ### Creating a CalleeAbility
1. Configure the ability launch type. For the CalleeAbility, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use **on()** to register a listener. When data does not need to be received, use **off()** to deregister the listener.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file. 1. Configure the launch type of the UIAbility.
| JSON Field| Description| For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md).
| -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
"srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
"launchType": "singleton",
"description": "$string:CalleeAbility_desc",
"icon": "$media:icon",
"label": "$string:CalleeAbility_label",
"visible": true
}]
```
2. Import the **UIAbility** module. 2. Import the **UIAbility** module.
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
``` ```
3. Define the agreed parcelable data. 3. Define the agreed parcelable data.
The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string.
```ts ```ts
export default class MyParcelable { export default class MyParcelable {
num: number = 0 num: number = 0;
str: string = "" str: string = '';
constructor(num, string) { constructor(num, string) {
this.num = num this.num = num;
this.str = string this.str = string;
} }
marshalling(messageSequence) { marshalling(messageSequence) {
messageSequence.writeInt(this.num) messageSequence.writeInt(this.num);
messageSequence.writeString(this.str) messageSequence.writeString(this.str);
return true return true
} }
unmarshalling(messageSequence) { unmarshalling(messageSequence) {
this.num = messageSequence.readInt() this.num = messageSequence.readInt();
this.str = messageSequence.readString() this.str = messageSequence.readString();
return true return true;
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: The time to register a listener for the CalleeAbility depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]'; const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg'; const MSG_SEND_METHOD: string = 'CallSendMsg';
...@@ -610,17 +611,17 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -610,17 +611,17 @@ For the callee ability, implement the callback to receive data and the methods t
function sendMsgCallback(data) { function sendMsgCallback(data) {
console.info('CalleeSortFunc called'); console.info('CalleeSortFunc called');
// Obtain the parcelable data sent by the caller ability. // Obtain the parcelable data sent by the CallerAbility.
let receivedData = new MyParcelable(0, ''); let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData); data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data. // Process the data.
// Return the parcelable data result to the caller ability. // Return the parcelable data result to the CallerAbility.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
} }
export default class CalleeAbility extends Ability { export default class CalleeAbility extends UIAbility {
onCreate(want, launchParam) { onCreate(want, launchParam) {
try { try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback); this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
...@@ -639,23 +640,25 @@ For the callee ability, implement the callback to receive data and the methods t ...@@ -639,23 +640,25 @@ For the callee ability, implement the callback to receive data and the methods t
} }
``` ```
### Accessing the Callee Ability
### Accessing the CalleeAbility
1. Import the **UIAbility** module. 1. Import the **UIAbility** module.
```ts ```ts
import Ability from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
``` ```
2. Obtain the caller interface. 2. Obtain the caller interface.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **context** attribute of the ability, uses **startAbilityByCall** to start the callee ability, obtain the caller object, and register the **onRelease** listener of the caller ability. You need to implement processing based on service requirements. The **UIAbilityContext** attribute implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **UIAbilityContext**, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements.
```ts ```ts
// Register the onRelease() listener of the caller ability. // Register the onRelease() listener of the CallerAbility.
private regOnRelease(caller) { private regOnRelease(caller) {
try { try {
caller.on("release", (msg) => { caller.on('release', (msg) => {
console.info(`caller onRelease is called ${msg}`); console.info(`caller onRelease is called ${msg}`);
}) })
console.info('caller register OnRelease succeed'); console.info('caller register OnRelease succeed');
......
...@@ -18,9 +18,12 @@ The launch type of the UIAbility component refers to the state of the UIAbility ...@@ -18,9 +18,12 @@ The launch type of the UIAbility component refers to the state of the UIAbility
Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**. Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, if a UIAbility instance of this type already exists in the application process, the instance is reused. Therefore, only one UIAbility instance of this type exists in the system, that is, displayed in **Recents**.
**Figure 1** Demonstration effect in singleton mode **Figure 1** Demonstration effect in singleton mode
![uiability-launch-type1](figures/uiability-launch-type1.png) ![uiability-launch-type1](figures/uiability-launch-type1.png)
> **NOTE**<br>Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > **NOTE**
>
> Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **singleton**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**. To use the singleton mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **singleton**.
...@@ -45,6 +48,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration ...@@ -45,6 +48,7 @@ To use the singleton mode, set **launchType** in the [module.json5 configuration
In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**. In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, a new UIAbility instance of this type is created in the application process. Multiple UIAbility instances of this type are displayed in **Recents**.
**Figure 2** Demonstration effect in standard mode **Figure 2** Demonstration effect in standard mode
![standard-mode](figures/standard-mode.png) ![standard-mode](figures/standard-mode.png)
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**. To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
...@@ -70,6 +74,7 @@ To use the standard mode, set **launchType** in the [module.json5 configuration ...@@ -70,6 +74,7 @@ To use the standard mode, set **launchType** in the [module.json5 configuration
The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document. The **specified** mode is used in some special scenarios. For example, in a document application, you want a document instance to be created each time you create a document, but you want to use the same document instance when you repeatedly open an existing document.
**Figure 3** Demonstration effect in specified mode **Figure 3** Demonstration effect in specified mode
![uiability-launch-type2](figures/uiability-launch-type2.png) ![uiability-launch-type2](figures/uiability-launch-type2.png)
For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility. For example, there are two UIAbility components: EntryAbility and SpecifiedAbility (with the launch type **specified**). You are required to start SpecifiedAbility from EntryAbility.
...@@ -108,7 +113,7 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ...@@ -108,7 +113,7 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
instanceKey: getInstance(), instanceKey: getInstance(),
}, },
} }
// context is the ability-level context of the initiator UIAbility. // context is the UIAbilityContext of the initiator UIAbility.
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
// ... // ...
}).catch((err) => { }).catch((err) => {
...@@ -137,7 +142,7 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili ...@@ -137,7 +142,7 @@ For example, there are two UIAbility components: EntryAbility and SpecifiedAbili
} }
``` ```
> **NOTE**<br> > **NOTE**
> >
> 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not. > 1. Assume that the application already has a UIAbility instance created, and the launch type of the UIAbility instance is set to **specified**. If [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called again to start the UIAbility instance, and the [onAcceptWant()](../reference/apis/js-apis-app-ability-abilityStage.md#abilitystageonacceptwant) callback of [AbilityStage](../reference/apis/js-apis-app-ability-abilityStage.md) matches a created UIAbility instance, the original UIAbility instance is started, and no new UIAbility instance is created. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback is invoked, but the [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) and [onWindowStageCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonwindowstagecreate) callbacks are not.
> 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md). > 2. AbilityStage is not automatically generated in the default project of DevEco Studio. For details about how to create an AbilityStage file, see [AbilityStage Component Container](abilitystage.md).
......
# Native APIs # Native APIs
Native APIs are a set of native development interfaces and tools provided by the OHOS SDK. It enables the use of C or C++ code to implement key application functionalities. Native APIs provide part of basic underlying capabilities of OHOS, such as libc, graphics library, window system, multimedia, and compression library. They do not provide complete OHOS platform capabilities as JS APIs do. Native APIs are compiled into a dynamic library before being packed into the application.
## Native API Composition
### Native API Directory Structure
Native APIs are stored in the **$(SDK_ROOT)/native** directory of the SDK. They consist of the following parts:
|Directory|Description|
|--|--|
|build|Used to build the toolchain.cmake script of the dynamic library in the application. The **ohos.toolchain.cmake** file in this directory defines OHOS cross compilation options.|
|build-tools|Stores build tools, such as CMake.|
|docs|Stores Native API reference documents, which is extracted from the header files using Doxgen.|
|llvm|Stores LLVM, a cross compiler that supports OHOS ABIs.|
|sysroot|Stores dependent files of build links, including header files and dynamic libraries.|
### Native APIs
|Category|Function|Introduced In|
|--|--|--|
|C standard library|C standard library interfaces based on musl. Currently, more than 1500 interfaces are provided.|API version 8|
|C++ standard library|C++ runtime library libc++_shared. This library must be packed or statically linked to the application during packing.|API version 8|
|Log|HiLog interfaces for printing logs to the system|API version 8|
|napi|A group of Node-APIs provided by ArkUI to facilitate access to the JS application environment during application development. Node-APIs are part of native APIs.|API version 8|
|XComponent|Provides surface and touchscreen event interfaces for developing high-performance graphics applications.|API version 8|
|libuv|Third-party asynchronous I/O library integrated by ArkUI.|API version 8|
|libz|zlib library that provides basic compression and decompression interfaces.|API version 8|
|Drawing|2D graphics library that can be used for drawing on the surface.|API version 8|
|OpenGL|OpenGL 3.0 interfaces.|API version 8|
|Rawfile|Application resource access interfaces that can be used to read various resources packed in the application.|API version 8|
|OpenSLES|Interface library used for 2D and 3D audio acceleration.|API version 8|
|Mindspore|AI model interface library.|API version 9|
|Bundle management|Bundle service interfaces that can be used to query bundle information of the application.|API version 8|
Some native APIs use open source standards. For details, see [Native Standard Libraries Supported by OpenHarmony](https://docs.openharmony.cn/pages/v3.1/en/application-dev/reference/native-lib/third_party_libc/musl.md/) and [Node_API](https://docs.openharmony.cn/pages/v3.1/en/application-dev/reference/native-lib/third_party_napi/napi.md/).
## Usage Guidelines
### Scenarios Where Native APIs Are Recommended
You can use native APIs when you want to:
1. Develop performance-sensitive code in computing-intensive scenarios such as gaming and physical simulation.
2. Reuse the existing C or C++ library.
3. Customize libraries related to CPU features, such as neon acceleration.
### Scenarios Where Native APIs Are Not Recommended
You do not need to use native APIs when you want to:
1. Write a native OHOS application.
2. Develop an application compatible on as many OHOS devices as possible.
# Native API References
- [Native API hello world]()
This sample shows how to develop a hello native API library, which can display strings obtained from the hello library on the TS page.
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
This document describes how to use native APIs to interact with modules, interfaces, and asynchronous tasks in JS.
- [Drawing Development](drawing-guidelines.md) - [Drawing Development](drawing-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md) - [Native Window Development](native-window-guidelines.md)
......
...@@ -232,3 +232,26 @@ struct Child { ...@@ -232,3 +232,26 @@ struct Child {
} }
} }
``` ```
## Restrictions on Naming Custom Components, Classes, and Functions
The name of a custom component, class, or function cannot be the same as any system component name.
Example:
```
// Rect.ets
export class Rect {
constructor(){}
}
// Index.ets
// ERROR: The module name 'Rect' can not be the same as the inner component name.
import { Rect } from './Rect';
@Entry
@Component
struct Index {
build() {
}
}
```
...@@ -65,11 +65,13 @@ Indicates that the device's thermal level has changed. ...@@ -65,11 +65,13 @@ Indicates that the device's thermal level has changed.
- Required subscriber permissions: none - Required subscriber permissions: none
## COMMON_EVENT_USER_PRESENT ## COMMON_EVENT_USER_PRESENT<sup>(deprecated)</sup>
(Reserved, not supported yet) Indicates that the user unlocks the device. (Reserved, not supported yet) Indicates that the user unlocks the device.
- Value: **usual.event.USER_PRESENT** - Value: **usual.event.USER_PRESENT**
- Required subscriber permissions: none - Required subscriber permissions: none
> NOTE
>
> This API is deprecated since API version 10.
## COMMON_EVENT_TIME_TICK ## COMMON_EVENT_TIME_TICK
Indicates that the system time has changed as time ticks by. Indicates that the system time has changed as time ticks by.
...@@ -929,3 +931,116 @@ Indicates the result of applying a quick fix to the application. ...@@ -929,3 +931,116 @@ Indicates the result of applying a quick fix to the application.
Indicates that the HTTP proxy configuration has changed. Indicates that the HTTP proxy configuration has changed.
- Value: **usual.event.HTTP_PROXY_CHANGE** - Value: **usual.event.HTTP_PROXY_CHANGE**
- Required subscriber permissions: none - 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**
- Required subscriber permissions: none
## COMMON_EVENT_SMS_RECEIVED_COMPLETED<sup>10+<sup>
Indicates that the SMS message is received.
- Value: **usual.event.SMS_RECEIVED_COMPLETED**
- Required subscriber permissions: ohos.permission.RECEIVE_SMS
## COMMON_EVENT_SMS_EMERGENCY_CB_RECEIVE_COMPLETED<sup>10+<sup>
Indicates that an emergency cell broadcast message is received.
- Value: **usual.event.SMS_EMERGENCY_CB_RECEIVE_COMPLETED**
- Required subscriber permissions: ohos.permission.RECEIVE_SMS
## COMMON_EVENT_SMS_CB_RECEIVE_COMPLETED<sup>10+<sup>
Indicates that a cell broadcast message is received.
- Value: **usual.event.SMS_CB_RECEIVE_COMPLETED**
- Required subscriber permissions: ohos.permission.RECEIVE_SMS
## COMMON_EVENT_STK_COMMAND<sup>10+<sup>
(Reserved, not supported yet) Indicates the STK command.
- Value: **usual.event.STK_COMMAND**
- Required subscriber permissions: none
## COMMON_EVENT_STK_SESSION_END<sup>10+<sup>
(Reserved, not supported yet) Indicates that an STK session ends.
- Value: **usual.event.STK_SESSION_END**
- Required subscriber permissions: none
## COMMON_EVENT_STK_CARD_STATE_CHANGED<sup>10+<sup>
(Reserved, not supported yet) Indicates that the STK card state has changed.
- Value: **usual.event.STK_CARD_STATE_CHANGED**
- Required subscriber permissions: ohos.permission
## COMMON_EVENT_STK_ALPHA_IDENTIFIER<sup>10+<sup>
(Reserved, not supported yet) Indicates the STK alpha indicator.
- Value: **usual.event.STK_ALPHA_IDENTIFIER**
- Required subscriber permissions: none
## COMMON_EVENT_SMS_WAPPUSH_RECEIVE_COMPLETED<sup>10+<sup>
Indicates that a WAP push message is received.
- Value: **usual.event.SMS_WAPPUSH_RECEIVE_COMPLETED**
- Required subscriber permissions: ohos.permission.RECEIVE_SMS
## COMMON_EVENT_OPERATOR_CONFIG_CHANGED<sup>10+<sup>
Indicates that the carrier configuration has been updated.
- Value: **usual.event.OPERATOR_CONFIG_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIM_CARD_DEFAULT_SMS_SUBSCRIPTION_CHANGED<sup>10+<sup>
Indicates that the default SIM card for the SMS service has changed.
- Value: **usual.event.DEFAULT_SMS_SUBSCRIPTION_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIM_CARD_DEFAULT_DATA_SUBSCRIPTION_CHANGED<sup>10+<sup>
Indicates that the default SIM card for the mobile data service has changed.
- Value: **usual.event.DEFAULT_DATA_SUBSCRIPTION_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIM_CARD_DEFAULT_MAIN_SUBSCRIPTION_CHANGED<sup>10+<sup>
Indicates that the default primary SIM card has changed.
- Value: **usual.event.SIM.DEFAULT_MAIN_SUBSCRIPTION_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIM_CARD_DEFAULT_VOICE_SUBSCRIPTION_CHANGED<sup>10+<sup>
Indicates that the default SIM card for the voice service has changed.
- Value: **usual.event.DEFAULT_VOICE_SUBSCRIPTION_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_CALL_STATE_CHANGED<sup>10+<sup>
Indicates that the call state has changed.
- Value: **usual.event.CALL_STATE_CHANGED**
- Required subscriber permissions: ohos.permission.GET_TELEPHONY_STATE
## COMMON_EVENT_CELLULAR_DATA_STATE_CHANGED<sup>10+<sup>
Indicates that the cellular data state has changed.
- Value: **usual.event.CELLULAR_DATA_STATE_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_NETWORK_STATE_CHANGED<sup>10+<sup>
Indicates that the network state has changed.
- Value: **usual.event.NETWORK_STATE_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_SIGNAL_INFO_CHANGED<sup>10+<sup>
Indicates that the signal information is updated.
- Value: **usual.event.SIGNAL_INFO_CHANGED**
- Required subscriber permissions: none
## COMMON_EVENT_INCOMING_CALL_MISSED<sup>10+<sup>
Indicates a missed call.
- Value: **usual.event.INCOMING_CALL_MISSED**
- Required subscriber permissions: ohos.permission.GET_TELEPHONY_STATE
## COMMON_EVENT_RADIO_STATE_CHANGE<sup>10+<sup>
Indicates that the power-on and power-off status of the modem has changed.
- Value: **usual.event.RADIO_STATE_CHANGE**
## COMMON_EVENT_SCREEN_LOCKED <sup>10+<sup>
Indicates that the screen is locked.
- Value: **usual.event.SCREEN_LOCKED**
- Required subscriber permissions: none
## COMMON_EVENT_SCREEN_UNLOCKED<sup>10+<sup>
Indicates that the screen is unlocked.
- Value: **usual.event.SCREEN_UNLOCKED**
- Required subscriber permissions: none
...@@ -2121,7 +2121,7 @@ audioManager.off('deviceChange', (deviceChanged) => { ...@@ -2121,7 +2121,7 @@ audioManager.off('deviceChange', (deviceChanged) => {
}); });
``` ```
### on('interrupt')<sup>(deprecated)</sup> ### on('interrupt')
on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\<InterruptAction>): void on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\<InterruptAction>): void
...@@ -2129,10 +2129,6 @@ Subscribes to audio interruption events. When the application's audio is interru ...@@ -2129,10 +2129,6 @@ Subscribes to audio interruption events. When the application's audio is interru
Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**System capability**: SystemCapability.Multimedia.Audio.Renderer **System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters** **Parameters**
...@@ -2163,16 +2159,12 @@ audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { ...@@ -2163,16 +2159,12 @@ audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => {
}); });
``` ```
### off('interrupt')<sup>(deprecated)</sup> ### off('interrupt')
off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\<InterruptAction>): void off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\<InterruptAction>): void
Unsubscribes from audio interruption events. Unsubscribes from audio interruption events.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**System capability**: SystemCapability.Multimedia.Audio.Renderer **System capability**: SystemCapability.Multimedia.Audio.Renderer
**Parameters** **Parameters**
...@@ -3953,21 +3945,20 @@ Obtains the output device with the highest priority based on the audio renderer ...@@ -3953,21 +3945,20 @@ Obtains the output device with the highest priority based on the audio renderer
let rendererInfo = { let rendererInfo = {
content : audio.ContentType.CONTENT_TYPE_MUSIC, content : audio.ContentType.CONTENT_TYPE_MUSIC,
usage : audio.StreamUsage.STREAM_USAGE_MEDIA, usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }; rendererFlags : 0 }
async function getPreferOutputDevice() { async function getPreferOutputDevice() {
audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err, desc) => { audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo, (err, desc) => {
if (err) { if (err) {
console.error(`Result ERROR: ${JSON.stringify(err)}`); console.error(`Result ERROR: ${err}`);
} else { } else {
console.info('device descriptor: ' + JSON.stringify(desc)); console.info(`device descriptor: ${desc}`);
} }
}); });
} }
``` ```
### getPreferOutputDeviceForRendererInfo<sup>9+</sup> ### getPreferOutputDeviceForRendererInfo<sup>10+</sup>
getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise&lt;AudioDeviceDescriptors&gt; getPreferOutputDeviceForRendererInfo(rendererInfo: AudioRendererInfo): Promise&lt;AudioDeviceDescriptors&gt;
Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result. Obtains the output device with the highest priority based on the audio renderer information. This API uses a promise to return the result.
...@@ -3986,19 +3977,27 @@ Obtains the output device with the highest priority based on the audio renderer ...@@ -3986,19 +3977,27 @@ Obtains the output device with the highest priority based on the audio renderer
| --------------------- | --------------------------- | | --------------------- | --------------------------- |
| Promise&lt;[AudioDeviceDescriptors](#audiodevicedescriptors)&gt; | Promise used to return the information about the output device with the highest priority.| | Promise&lt;[AudioDeviceDescriptors](#audiodevicedescriptors)&gt; | Promise used to return the information about the output device with the highest priority.|
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
**Example** **Example**
```js ```js
let rendererInfo = { let rendererInfo = {
content : audio.ContentType.CONTENT_TYPE_MUSIC, content : audio.ContentType.CONTENT_TYPE_MUSIC,
usage : audio.StreamUsage.STREAM_USAGE_MEDIA, usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }; rendererFlags : 0 }
async function getPreferOutputDevice() { async function getPreferOutputDevice() {
audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc) => { audioRoutingManager.getPreferOutputDeviceForRendererInfo(rendererInfo).then((desc) => {
console.info('device descriptor: ' + JSON.stringify(desc)); console.info(`device descriptor: ${desc}`);
}).catch((err) => { }).catch((err) => {
console.error(`Result ERROR: ${JSON.stringify(err)}`); console.error(`Result ERROR: ${err}`);
}) })
} }
``` ```
...@@ -4009,6 +4008,8 @@ on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererI ...@@ -4009,6 +4008,8 @@ on(type: 'preferOutputDeviceChangeForRendererInfo', rendererInfo: AudioRendererI
Subscribes to the change of the output device with the highest priority. This API uses an asynchronous callback to return the result. Subscribes to the change of the output device with the highest priority. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
...@@ -4017,16 +4018,24 @@ Subscribes to the change of the output device with the highest priority. This AP ...@@ -4017,16 +4018,24 @@ Subscribes to the change of the output device with the highest priority. This AP
| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. | | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information. |
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the output device with the highest priority. | | callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | Yes | Callback used to return the information about the output device with the highest priority. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
**Example** **Example**
```js ```js
let rendererInfo = { let rendererInfo = {
content : audio.ContentType.CONTENT_TYPE_MUSIC, content : audio.ContentType.CONTENT_TYPE_MUSIC,
usage : audio.StreamUsage.STREAM_USAGE_MEDIA, usage : audio.StreamUsage.STREAM_USAGE_MEDIA,
rendererFlags : 0 }; rendererFlags : 0 }
audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => { audioRoutingManager.on('preferOutputDeviceChangeForRendererInfo', rendererInfo, (desc) => {
console.info('device descriptor: ' + JSON.stringify(desc)); console.info(`device descriptor: ${desc}`);
}); });
``` ```
...@@ -4045,6 +4054,14 @@ Unsubscribes from the change of the output device with the highest priority. ...@@ -4045,6 +4054,14 @@ Unsubscribes from the change of the output device with the highest priority.
| type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.| | type | string | Yes | Event type. The value **'preferOutputDeviceChangeForRendererInfo'** means the event triggered when the output device with the highest priority changes.|
| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. | | callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | No | Callback used for unsubscription. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID| Error Message|
| ------- | --------------------------------------------|
| 6800101 | if input parameter value error |
**Example** **Example**
```js ```js
...@@ -5107,18 +5124,18 @@ audioRenderer.setVolume(0.5, (err, data)=>{ ...@@ -5107,18 +5124,18 @@ audioRenderer.setVolume(0.5, (err, data)=>{
on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void
Subscribes to audio interruption events. This API uses a callback to get interrupt events. Subscribes to audio interruption events. This API uses a callback to obtain interrupt events.
Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. Same as [on('interrupt')](#oninterrupt), this API is used to listen for focus changes. The **AudioRenderer** instance proactively gains the focus when the **start** event occurs and releases the focus when the **pause** or **stop** event occurs. Therefore, you do not need to request to gain or release the focus.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt **System capability**: SystemCapability.Multimedia.Audio.Interrupt
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | | -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | | type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio rendering is interrupted. |
| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | | callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. |
**Error codes** **Error codes**
...@@ -5131,50 +5148,68 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco ...@@ -5131,50 +5148,68 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco
**Example** **Example**
```js ```js
let isPlay; let isPlaying; // An identifier specifying whether rendering is in progress.
let started; let isDucked; // An identifier specifying whether the audio volume is reduced.
onAudioInterrupt(); onAudioInterrupt();
async function onAudioInterrupt(){ async function onAudioInterrupt(){
audioRenderer.on('audioInterrupt', async(interruptEvent) => { audioRenderer.on('audioInterrupt', async(interruptEvent) => {
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
// The system forcibly interrupts audio rendering. The application must update the status and displayed content accordingly.
switch (interruptEvent.hintType) { switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_PAUSE: case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
console.info('Force paused. Stop writing'); // The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
isPlay = false; console.info('Force paused. Update playing status and stop writing');
isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
break; break;
case audio.InterruptHint.INTERRUPT_HINT_STOP: case audio.InterruptHint.INTERRUPT_HINT_STOP:
console.info('Force stopped. Stop writing'); // The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume rendering.
isPlay = false; console.info('Force stopped. Update playing status and stop writing');
isPlaying = false; // A simplified processing indicating several operations for switching the application to the paused state.
break;
case audio.InterruptHint.INTERRUPT_HINT_DUCK:
// The audio stream is rendered at a reduced volume.
console.info('Force ducked. Update volume status');
isDucked = true; // A simplified processing indicating several operations for updating the volume status.
break;
case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
// The audio stream is rendered at the normal volume.
console.info('Force ducked. Update volume status');
isDucked = false; // A simplified processing indicating several operations for updating the volume status.
break;
default:
console.info('Invalid interruptEvent');
break; break;
} }
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
// The application can choose to take action or ignore.
switch (interruptEvent.hintType) { switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_RESUME: case audio.InterruptHint.INTERRUPT_HINT_RESUME:
// It is recommended that the application continue rendering. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume rendering now.)
console.info('Resume force paused renderer or ignore'); console.info('Resume force paused renderer or ignore');
await audioRenderer.start().then(async function () { // To continue rendering, the application must perform the required operations.
console.info('AudioInterruptMusic: renderInstant started :SUCCESS ');
started = true;
}).catch((err) => {
console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`);
started = false;
});
if (started) {
isPlay = true;
console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`);
} else {
console.error('AudioInterruptMusic Renderer start failed');
}
break; break;
case audio.InterruptHint.INTERRUPT_HINT_PAUSE: case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
// It is recommended that the application pause rendering.
console.info('Choose to pause or ignore'); console.info('Choose to pause or ignore');
if (isPlay == true) { // To pause rendering, the application must perform the required operations.
isPlay == false; break;
console.info('AudioInterruptMusic: Media PAUSE : TRUE'); case audio.InterruptHint.INTERRUPT_HINT_STOP:
} else { // It is recommended that the application stop rendering.
isPlay = true; console.info('Choose to stop or ignore');
console.info('AudioInterruptMusic: Media PLAY : TRUE'); // To stop rendering, the application must perform the required operations.
} break;
case audio.InterruptHint.INTERRUPT_HINT_DUCK:
// It is recommended that the application reduce the volume for rendering.
console.info('Choose to duck or ignore');
// To decrease the volume for rendering, the application must perform the required operations.
break;
case audio.InterruptHint.INTERRUPT_HINT_UNDUCK:
// It is recommended that the application resume rendering at the normal volume.
console.info('Choose to unduck or ignore');
// To resume rendering at the normal volume, the application must perform the required operations.
break;
default:
break; break;
} }
} }
...@@ -5850,6 +5885,84 @@ audioCapturer.getBufferSize().then((data) => { ...@@ -5850,6 +5885,84 @@ audioCapturer.getBufferSize().then((data) => {
``` ```
### on('audioInterrupt')<sup>10+</sup>
on(type: 'audioInterrupt', callback: Callback\<InterruptEvent>): void
Subscribes to audio interruption events. This API uses a callback to get interrupt events.
Same as [on('interrupt')](#oninterrupt), this API is used to listen for focus changes. The **AudioCapturer** instance proactively gains the focus when the **start** event occurs and releases the focus when the **pause** or **stop** event occurs. Therefore, you do not need to request to gain or release the focus.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ |
| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio capturing is interrupted. |
| callback | Callback\<[InterruptEvent](#interruptevent9)\> | Yes | Callback used to return the audio interruption event. |
**Error codes**
For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md).
| ID | Error Message |
| ------- | ------------------------------ |
| 6800101 | if input parameter value error |
**Example**
```js
let isCapturing; // An identifier specifying whether capturing is in progress.
onAudioInterrupt();
async function onAudioInterrupt(){
audioCapturer.on('audioInterrupt', async(interruptEvent) => {
if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) {
// The system forcibly interrupts audio capturing. The application must update the status and displayed content accordingly.
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
// The audio stream has been paused and temporarily loses the focus. It will receive the interruptEvent corresponding to resume when it is able to regain the focus.
console.info('Force paused. Update capturing status and stop reading');
isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state.
break;
case audio.InterruptHint.INTERRUPT_HINT_STOP:
// The audio stream has been stopped and permanently loses the focus. The user must manually trigger the operation to resume capturing.
console.info('Force stopped. Update capturing status and stop reading');
isCapturing = false; // A simplified processing indicating several operations for switching the application to the paused state.
break;
default:
console.info('Invalid interruptEvent');
break;
}
} else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) {
// The application can choose to take action or ignore.
switch (interruptEvent.hintType) {
case audio.InterruptHint.INTERRUPT_HINT_RESUME:
// It is recommended that the application continue capturing. (The audio stream has been forcibly paused and temporarily lost the focus. It can resume capturing now.)
console.info('Resume force paused renderer or ignore');
// To continue capturing, the application must perform the required operations.
break;
case audio.InterruptHint.INTERRUPT_HINT_PAUSE:
// It is recommended that the application pause capturing.
console.info('Choose to pause or ignore');
// To pause capturing, the application must perform the required operations.
break;
case audio.InterruptHint.INTERRUPT_HINT_STOP:
// It is recommended that the application stop capturing.
console.info('Choose to stop or ignore');
// To stop capturing, the application must perform the required operations.
break;
default:
break;
}
}
});
}
```
### on('markReach')<sup>8+</sup> ### on('markReach')<sup>8+</sup>
on(type: "markReach", frame: number, callback: Callback&lt;number&gt;): void on(type: "markReach", frame: number, callback: Callback&lt;number&gt;): void
...@@ -6306,7 +6419,7 @@ Describes the callback invoked for audio interruption or focus gain events. ...@@ -6306,7 +6419,7 @@ Describes the callback invoked for audio interruption or focus gain events.
> **NOTE** > **NOTE**
> >
> This API is supported since API version 7 and deprecated since API version 9. > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [InterruptEvent](#interruptevent9).
**System capability**: SystemCapability.Multimedia.Audio.Renderer **System capability**: SystemCapability.Multimedia.Audio.Renderer
......
...@@ -99,10 +99,10 @@ Defines the camera output capability. ...@@ -99,10 +99,10 @@ Defines the camera output capability.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------------------------- | -------------------------------------------------- | --- |------------------- | | ----------------------------- | -------------------------------------------------- | --- |------------------- |
| previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview profiles. | | previewProfiles | Array\<[Profile](#profile)\> | Yes | Supported preview profiles. |
| photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting profiles. | | photoProfiles | Array\<[Profile](#profile)\> | Yes | Supported shooting profiles. |
| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording profiles. | | videoProfiles | Array\<[VideoProfile](#videoprofile)\> | Yes | Supported video recording profiles. |
| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| | supportedMetadataObjectTypes | Array\<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.|
## CameraErrorCode ## CameraErrorCode
...@@ -128,7 +128,7 @@ Implements camera management. Before calling any API in **CameraManager**, you m ...@@ -128,7 +128,7 @@ Implements camera management. Before calling any API in **CameraManager**, you m
### getSupportedCameras ### getSupportedCameras
getSupportedCameras(): Array<CameraDevice\> getSupportedCameras(): Array\<CameraDevice\>
Obtains supported cameras. This API returns the result synchronously. Obtains supported cameras. This API returns the result synchronously.
...@@ -138,7 +138,7 @@ Obtains supported cameras. This API returns the result synchronously. ...@@ -138,7 +138,7 @@ Obtains supported cameras. This API returns the result synchronously.
| Type | Description | | Type | Description |
| ----------------------------------------------- | ---------------------------- | | ----------------------------------------------- | ---------------------------- |
| Array<[CameraDevice](#cameradevice)> | An array of supported cameras. | | Array\<[CameraDevice](#cameradevice)> | An array of supported cameras. |
**Example** **Example**
...@@ -149,7 +149,7 @@ let cameras = cameraManager.getSupportedCameras(); ...@@ -149,7 +149,7 @@ let cameras = cameraManager.getSupportedCameras();
### getSupportedOutputCapability ### getSupportedOutputCapability
getSupportedOutputCapability(cameraDevice:CameraDevice): CameraOutputCapability getSupportedOutputCapability(camera:CameraDevice): CameraOutputCapability
Obtains the output capability supported by a camera. This API returns the result synchronously. Obtains the output capability supported by a camera. This API returns the result synchronously.
...@@ -459,7 +459,7 @@ try { ...@@ -459,7 +459,7 @@ try {
### createMetadataOutput ### createMetadataOutput
createMetadataOutput(metadataObjectTypes:Array<MetadataObjectType\>): MetadataOutput createMetadataOutput(metadataObjectTypes:Array\<MetadataObjectType\>): MetadataOutput
Creates a **MetadataOutput** instance. This API returns the result synchronously. Creates a **MetadataOutput** instance. This API returns the result synchronously.
...@@ -469,7 +469,7 @@ Creates a **MetadataOutput** instance. This API returns the result synchronously ...@@ -469,7 +469,7 @@ Creates a **MetadataOutput** instance. This API returns the result synchronously
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------------- | --- | ---------------------------- | | -------------------- | -------------------------------------------------- | --- | ---------------------------- |
| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**.| | metadataObjectTypes | Array\<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**.|
**Return value** **Return value**
...@@ -534,7 +534,7 @@ try { ...@@ -534,7 +534,7 @@ try {
### on('cameraStatus') ### on('cameraStatus')
on(type: 'cameraStatus', callback: AsyncCallback<CameraStatusInfo\>): void on(type: 'cameraStatus', callback: AsyncCallback\<CameraStatusInfo\>): void
Listens for camera status changes. This API uses an asynchronous callback to return the result. Listens for camera status changes. This API uses an asynchronous callback to return the result.
...@@ -545,7 +545,7 @@ Listens for camera status changes. This API uses an asynchronous callback to ret ...@@ -545,7 +545,7 @@ Listens for camera status changes. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -----------------| ---- | --------- | | -------- | -----------------| ---- | --------- |
| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the corresponding information is returned only when the device is enabled or disabled.| | type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The event can be listened for when a **CameraManager** instance is obtained. This event is triggered and the corresponding information is returned only when the device is enabled or disabled.|
| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change.| | | callback | AsyncCallback\<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change.| |
**Example** **Example**
...@@ -558,7 +558,7 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => { ...@@ -558,7 +558,7 @@ cameraManager.on('cameraStatus', (cameraStatusInfo) => {
### on('cameraMute') ### on('cameraMute')
on(type: 'cameraMute', callback: AsyncCallback<boolean\>): void on(type: 'cameraMute', callback: AsyncCallback\<boolean\>): void
Listens for camera mute status changes. This API uses an asynchronous callback to return the result. Listens for camera mute status changes. This API uses an asynchronous callback to return the result.
...@@ -683,7 +683,7 @@ Provides camera information used in **[CaptureSession](#capturesession)**. ...@@ -683,7 +683,7 @@ Provides camera information used in **[CaptureSession](#capturesession)**.
### open ### open
open\(callback: AsyncCallback<void\>\): void open\(callback: AsyncCallback\<void\>\): void
Opens this camera. This API uses an asynchronous callback to return the result. Opens this camera. This API uses an asynchronous callback to return the result.
...@@ -693,7 +693,7 @@ Opens this camera. This API uses an asynchronous callback to return the result. ...@@ -693,7 +693,7 @@ Opens this camera. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -719,7 +719,7 @@ cameraInput.open((err) => { ...@@ -719,7 +719,7 @@ cameraInput.open((err) => {
### open ### open
open(): Promise<void\> open(): Promise\<void\>
Opens this camera. This API uses a promise to return the result. Opens this camera. This API uses a promise to return the result.
...@@ -729,7 +729,7 @@ Opens this camera. This API uses a promise to return the result. ...@@ -729,7 +729,7 @@ Opens this camera. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -753,7 +753,7 @@ cameraInput.open().then(() => { ...@@ -753,7 +753,7 @@ cameraInput.open().then(() => {
### close ### close
close\(callback: AsyncCallback<void\>\): void close\(callback: AsyncCallback\<void\>\): void
Closes this camera. This API uses an asynchronous callback to return the result. Closes this camera. This API uses an asynchronous callback to return the result.
...@@ -763,7 +763,7 @@ Closes this camera. This API uses an asynchronous callback to return the result. ...@@ -763,7 +763,7 @@ Closes this camera. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -787,7 +787,7 @@ cameraInput.close((err) => { ...@@ -787,7 +787,7 @@ cameraInput.close((err) => {
### close ### close
close(): Promise<void\> close(): Promise\<void\>
Closes this camera. This API uses a promise to return the result. Closes this camera. This API uses a promise to return the result.
...@@ -797,7 +797,7 @@ Closes this camera. This API uses a promise to return the result. ...@@ -797,7 +797,7 @@ Closes this camera. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -819,7 +819,7 @@ cameraInput.close().then(() => { ...@@ -819,7 +819,7 @@ cameraInput.close().then(() => {
### on('error') ### on('error')
on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback<BusinessError\>): void on(type: 'error', camera:CameraDevice, callback: ErrorCallback\<BusinessError\>): void
Listens for **CameraInput** errors. This API uses a callback to return the result. Listens for **CameraInput** errors. This API uses a callback to return the result.
...@@ -831,7 +831,7 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul ...@@ -831,7 +831,7 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul
| -------- | -------------------------------- | --- | ------------------------------------------- | | -------- | -------------------------------- | --- | ------------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **CameraInput** instance is created. This event is triggered and the result is returned when an error occurs on the camera. For example, if the device is unavailable or a conflict occurs, the error information is returned.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **CameraInput** instance is created. This event is triggered and the result is returned when an error occurs on the camera. For example, if the device is unavailable or a conflict occurs, the error information is returned.|
| cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| | cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.|
| callback | ErrorCallback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | ErrorCallback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -945,7 +945,7 @@ try { ...@@ -945,7 +945,7 @@ try {
### commitConfig ### commitConfig
commitConfig(callback: AsyncCallback<void\>): void commitConfig(callback: AsyncCallback\<void\>): void
Commits the configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result. Commits the configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result.
...@@ -955,7 +955,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an ...@@ -955,7 +955,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -980,7 +980,7 @@ captureSession.commitConfig((err) => { ...@@ -980,7 +980,7 @@ captureSession.commitConfig((err) => {
### commitConfig ### commitConfig
commitConfig(): Promise<void\> commitConfig(): Promise\<void\>
Commits the configuration for this **CaptureSession** instance. This API uses a promise to return the result. Commits the configuration for this **CaptureSession** instance. This API uses a promise to return the result.
...@@ -990,7 +990,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses a ...@@ -990,7 +990,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses a
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1094,7 +1094,7 @@ try { ...@@ -1094,7 +1094,7 @@ try {
### addOutput ### addOutput
addOutput(previewOutput: CameraOutput): void addOutput(cameraOutput: CameraOutput): void
Adds a [CameraOutput](#cameraoutput) instance to the session. Adds a [CameraOutput](#cameraoutput) instance to the session.
...@@ -1104,7 +1104,7 @@ Adds a [CameraOutput](#cameraoutput) instance to the session. ...@@ -1104,7 +1104,7 @@ Adds a [CameraOutput](#cameraoutput) instance to the session.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | ------------------------------- | ---- | ------------------------ | | ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| | cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.|
**Return value** **Return value**
...@@ -1125,7 +1125,7 @@ For details about the error codes, see [CameraErrorCode](#cameraerrorcode). ...@@ -1125,7 +1125,7 @@ For details about the error codes, see [CameraErrorCode](#cameraerrorcode).
```js ```js
try { try {
captureSession.addOutput(previewOutput); captureSession.addOutput(cameraOutput);
} catch (error) { } catch (error) {
// If the operation fails, error.code is returned and processed. // If the operation fails, error.code is returned and processed.
console.log(error.code); console.log(error.code);
...@@ -1134,7 +1134,7 @@ try { ...@@ -1134,7 +1134,7 @@ try {
### removeOutput ### removeOutput
removeOutput(previewOutput: CameraOutput): void removeOutput(cameraOutput: CameraOutput): void
Removes a [CameraOutput](#cameraoutput) instance from the session. Removes a [CameraOutput](#cameraoutput) instance from the session.
...@@ -1144,7 +1144,7 @@ Removes a [CameraOutput](#cameraoutput) instance from the session. ...@@ -1144,7 +1144,7 @@ Removes a [CameraOutput](#cameraoutput) instance from the session.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------- | ------------------------------- | ---- | ------------------------ | | ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| | cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.|
**Return value** **Return value**
...@@ -1174,7 +1174,7 @@ try { ...@@ -1174,7 +1174,7 @@ try {
### start ### start
start\(callback: AsyncCallback<void\>\): void start\(callback: AsyncCallback\<void\>\): void
Starts this **CaptureSession**. This API uses an asynchronous callback to return the result. Starts this **CaptureSession**. This API uses an asynchronous callback to return the result.
...@@ -1184,7 +1184,7 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return ...@@ -1184,7 +1184,7 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1209,7 +1209,7 @@ captureSession.start((err) => { ...@@ -1209,7 +1209,7 @@ captureSession.start((err) => {
### start ### start
start\(\): Promise<void\> start\(\): Promise\<void\>
Starts this **CaptureSession**. This API uses a promise to return the result. Starts this **CaptureSession**. This API uses a promise to return the result.
...@@ -1219,7 +1219,7 @@ Starts this **CaptureSession**. This API uses a promise to return the result. ...@@ -1219,7 +1219,7 @@ Starts this **CaptureSession**. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -1242,7 +1242,7 @@ captureSession.start().then(() => { ...@@ -1242,7 +1242,7 @@ captureSession.start().then(() => {
### stop ### stop
stop\(callback: AsyncCallback<void\>\): void stop\(callback: AsyncCallback\<void\>\): void
Stops this **CaptureSession**. This API uses an asynchronous callback to return the result. Stops this **CaptureSession**. This API uses an asynchronous callback to return the result.
...@@ -1252,7 +1252,7 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return ...@@ -1252,7 +1252,7 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1276,7 +1276,7 @@ captureSession.stop((err) => { ...@@ -1276,7 +1276,7 @@ captureSession.stop((err) => {
### stop ### stop
stop(): Promise<void\> stop(): Promise\<void\>
Stops this **CaptureSession**. This API uses a promise to return the result. Stops this **CaptureSession**. This API uses a promise to return the result.
...@@ -1286,7 +1286,7 @@ Stops this **CaptureSession**. This API uses a promise to return the result. ...@@ -1286,7 +1286,7 @@ Stops this **CaptureSession**. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1308,7 +1308,7 @@ captureSession.stop().then(() => { ...@@ -1308,7 +1308,7 @@ captureSession.stop().then(() => {
### release ### release
release\(callback: AsyncCallback<void\>\): void release\(callback: AsyncCallback\<void\>\): void
Releases this **CaptureSession**. This API uses an asynchronous callback to return the result. Releases this **CaptureSession**. This API uses an asynchronous callback to return the result.
...@@ -1318,7 +1318,7 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu ...@@ -1318,7 +1318,7 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1342,7 +1342,7 @@ captureSession.release((err) => { ...@@ -1342,7 +1342,7 @@ captureSession.release((err) => {
### release ### release
release(): Promise<void\> release(): Promise\<void\>
Releases this **CaptureSession**. This API uses a promise to return the result. Releases this **CaptureSession**. This API uses a promise to return the result.
...@@ -1352,7 +1352,7 @@ Releases this **CaptureSession**. This API uses a promise to return the result. ...@@ -1352,7 +1352,7 @@ Releases this **CaptureSession**. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -1709,7 +1709,7 @@ try { ...@@ -1709,7 +1709,7 @@ try {
### getExposureBiasRange ### getExposureBiasRange
getExposureBiasRange(): Array<number\> getExposureBiasRange(): Array\<number\>
Obtains the exposure compensation values of the device. Obtains the exposure compensation values of the device.
...@@ -1719,7 +1719,7 @@ Obtains the exposure compensation values of the device. ...@@ -1719,7 +1719,7 @@ Obtains the exposure compensation values of the device.
| Type | Description | | Type | Description |
| ---------- | ----------------------------- | | ---------- | ----------------------------- |
| Array<number\> | An array of compensation values. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Array\<number\> | An array of compensation values. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2032,7 +2032,7 @@ try { ...@@ -2032,7 +2032,7 @@ try {
### getZoomRatioRange ### getZoomRatioRange
getZoomRatioRange(): Array<number\> getZoomRatioRange(): Array\<number\>
Obtains the supported zoom ratio range. Obtains the supported zoom ratio range.
...@@ -2042,7 +2042,7 @@ Obtains the supported zoom ratio range. ...@@ -2042,7 +2042,7 @@ Obtains the supported zoom ratio range.
| Type | Description | | Type | Description |
| ---------- | ----------------------------- | | ---------- | ----------------------------- |
| Array<number\> | Callback used to return an array containing the minimum and maximum zoom ratios. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Array\<number\> | Callback used to return an array containing the minimum and maximum zoom ratios. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2249,7 +2249,7 @@ try { ...@@ -2249,7 +2249,7 @@ try {
### on('focusStateChange') ### on('focusStateChange')
on(type: 'focusStateChange', callback: AsyncCallback<FocusState\>): void on(type: 'focusStateChange', callback: AsyncCallback\<FocusState\>): void
Listens for focus state changes. This API uses an asynchronous callback to return the result. Listens for focus state changes. This API uses an asynchronous callback to return the result.
...@@ -2260,7 +2260,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur ...@@ -2260,7 +2260,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------ |
| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The event can be listened for when a session is created. This event is triggered only when the camera focus state changes in auto focus mode.| | type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The event can be listened for when a session is created. This event is triggered only when the camera focus state changes in auto focus mode.|
| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | | callback | AsyncCallback\<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. |
**Example** **Example**
...@@ -2272,7 +2272,7 @@ captureSession.on('focusStateChange', (focusState) => { ...@@ -2272,7 +2272,7 @@ captureSession.on('focusStateChange', (focusState) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<BusinessError\>): void on(type: 'error', callback: ErrorCallback\<BusinessError\>): void
Listens for **CaptureSession** errors. This API uses a callback to return the errors. Listens for **CaptureSession** errors. This API uses a callback to return the errors.
...@@ -2283,7 +2283,7 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er ...@@ -2283,7 +2283,7 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | | -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a session is created. This event is triggered and the error message is returned when an error occurs during the calling of a session-related API such as **beginConfig()**, **commitConfig()**, and **addInput**.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a session is created. This event is triggered and the error message is returned when an error occurs during the calling of a session-related API such as **beginConfig()**, **commitConfig()**, and **addInput**.|
| callback | ErrorCallback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | ErrorCallback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -2303,7 +2303,7 @@ Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. ...@@ -2303,7 +2303,7 @@ Implements preview output. It inherits **[CameraOutput](#cameraoutput)**.
### start ### start
start(callback: AsyncCallback<void\>): void start(callback: AsyncCallback\<void\>): void
Starts to output preview streams. This API uses an asynchronous callback to return the result. Starts to output preview streams. This API uses an asynchronous callback to return the result.
...@@ -2313,7 +2313,7 @@ Starts to output preview streams. This API uses an asynchronous callback to retu ...@@ -2313,7 +2313,7 @@ Starts to output preview streams. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2337,7 +2337,7 @@ previewOutput.start((err) => { ...@@ -2337,7 +2337,7 @@ previewOutput.start((err) => {
### start ### start
start(): Promise<void\> start(): Promise\<void\>
Starts to output preview streams. This API uses a promise to return the result. Starts to output preview streams. This API uses a promise to return the result.
...@@ -2347,7 +2347,7 @@ Starts to output preview streams. This API uses a promise to return the result. ...@@ -2347,7 +2347,7 @@ Starts to output preview streams. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2369,7 +2369,7 @@ previewOutput.start().then(() => { ...@@ -2369,7 +2369,7 @@ previewOutput.start().then(() => {
### stop ### stop
stop(callback: AsyncCallback<void\>): void stop(callback: AsyncCallback\<void\>): void
Stops outputting preview streams. This API uses an asynchronous callback to return the result. Stops outputting preview streams. This API uses an asynchronous callback to return the result.
...@@ -2379,7 +2379,7 @@ Stops outputting preview streams. This API uses an asynchronous callback to retu ...@@ -2379,7 +2379,7 @@ Stops outputting preview streams. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -2395,7 +2395,7 @@ previewOutput.stop((err) => { ...@@ -2395,7 +2395,7 @@ previewOutput.stop((err) => {
### stop ### stop
stop(): Promise<void\> stop(): Promise\<void\>
Stops outputting preview streams. This API uses a promise to return the result. Stops outputting preview streams. This API uses a promise to return the result.
...@@ -2405,7 +2405,7 @@ Stops outputting preview streams. This API uses a promise to return the result. ...@@ -2405,7 +2405,7 @@ Stops outputting preview streams. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -2419,7 +2419,7 @@ previewOutput.stop().then(() => { ...@@ -2419,7 +2419,7 @@ previewOutput.stop().then(() => {
### release ### release
release(callback: AsyncCallback<void\>): void release(callback: AsyncCallback\<void\>): void
Releases output resources. This API uses an asynchronous callback to return the result. Releases output resources. This API uses an asynchronous callback to return the result.
...@@ -2429,7 +2429,7 @@ Releases output resources. This API uses an asynchronous callback to return the ...@@ -2429,7 +2429,7 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2453,7 +2453,7 @@ previewOutput.release((err) => { ...@@ -2453,7 +2453,7 @@ previewOutput.release((err) => {
### release ### release
release(): Promise<void\> release(): Promise\<void\>
Releases output resources. This API uses a promise to return the result. Releases output resources. This API uses a promise to return the result.
...@@ -2463,7 +2463,7 @@ Releases output resources. This API uses a promise to return the result. ...@@ -2463,7 +2463,7 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2485,7 +2485,7 @@ previewOutput.release().then(() => { ...@@ -2485,7 +2485,7 @@ previewOutput.release().then(() => {
### on('frameStart') ### on('frameStart')
on(type: 'frameStart', callback: AsyncCallback<void\>): void on(type: 'frameStart', callback: AsyncCallback\<void\>): void
Listens for preview frame start events. This API uses an asynchronous callback to return the result. Listens for preview frame start events. This API uses an asynchronous callback to return the result.
...@@ -2496,7 +2496,7 @@ Listens for preview frame start events. This API uses an asynchronous callback t ...@@ -2496,7 +2496,7 @@ Listens for preview frame start events. This API uses an asynchronous callback t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | --------------------------------------- | | -------- | -------------------- | ---- | --------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.| | type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure for the first time.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. The preview starts as long as this event is returned. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. The preview starts as long as this event is returned. |
**Example** **Example**
...@@ -2508,7 +2508,7 @@ previewOutput.on('frameStart', () => { ...@@ -2508,7 +2508,7 @@ previewOutput.on('frameStart', () => {
### on('frameEnd') ### on('frameEnd')
on(type: 'frameEnd', callback: AsyncCallback<void\>): void on(type: 'frameEnd', callback: AsyncCallback\<void\>): void
Listens for preview frame end events. This API uses an asynchronous callback to return the result. Listens for preview frame end events. This API uses an asynchronous callback to return the result.
...@@ -2519,7 +2519,7 @@ Listens for preview frame end events. This API uses an asynchronous callback to ...@@ -2519,7 +2519,7 @@ Listens for preview frame end events. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------- | | -------- | -------------------- | ---- | ------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the last frame of preview ends.| | type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and returned when the last frame of preview ends.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. The preview ends as long as this event is returned. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. The preview ends as long as this event is returned. |
**Example** **Example**
...@@ -2531,7 +2531,7 @@ previewOutput.on('frameEnd', () => { ...@@ -2531,7 +2531,7 @@ previewOutput.on('frameEnd', () => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<BusinessError\>): void on(type: 'error', callback: ErrorCallback\<BusinessError\>): void
Listens for **PreviewOutput** errors. This API uses a callback to return the errors. Listens for **PreviewOutput** errors. This API uses a callback to return the errors.
...@@ -2542,7 +2542,7 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err ...@@ -2542,7 +2542,7 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------| ---- | ------------------------ | | -------- | --------------| ---- | ------------------------ |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as **start()** or **release()**.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **previewOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the use of a preview-related API such as **start()** or **release()**.|
| callback | ErrorCallback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | ErrorCallback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -2609,7 +2609,7 @@ Implements output information used in a shooting session. This class inherits fr ...@@ -2609,7 +2609,7 @@ Implements output information used in a shooting session. This class inherits fr
### capture ### capture
capture(callback: AsyncCallback<void\>): void capture(callback: AsyncCallback\<void\>): void
Captures a photo with the default shooting parameters. This API uses an asynchronous callback to return the result. Captures a photo with the default shooting parameters. This API uses an asynchronous callback to return the result.
...@@ -2619,7 +2619,7 @@ Captures a photo with the default shooting parameters. This API uses an asynchro ...@@ -2619,7 +2619,7 @@ Captures a photo with the default shooting parameters. This API uses an asynchro
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2644,7 +2644,7 @@ photoOutput.capture((err) => { ...@@ -2644,7 +2644,7 @@ photoOutput.capture((err) => {
### capture ### capture
capture(): Promise<void\> capture(): Promise\<void\>
Captures a photo with the default shooting parameters. This API uses a promise to return the result. Captures a photo with the default shooting parameters. This API uses a promise to return the result.
...@@ -2654,7 +2654,7 @@ Captures a photo with the default shooting parameters. This API uses a promise t ...@@ -2654,7 +2654,7 @@ Captures a photo with the default shooting parameters. This API uses a promise t
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2677,7 +2677,7 @@ photoOutput.capture().then(() => { ...@@ -2677,7 +2677,7 @@ photoOutput.capture().then(() => {
### capture ### capture
capture(setting: PhotoCaptureSetting, callback: AsyncCallback<void\>): void capture(setting: PhotoCaptureSetting, callback: AsyncCallback\<void\>): void
Captures a photo with the specified shooting parameters. This API uses an asynchronous callback to return the result. Captures a photo with the specified shooting parameters. This API uses an asynchronous callback to return the result.
...@@ -2688,7 +2688,7 @@ Captures a photo with the specified shooting parameters. This API uses an asynch ...@@ -2688,7 +2688,7 @@ Captures a photo with the specified shooting parameters. This API uses an asynch
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | -------------------- | | -------- | ------------------------------------------- | ---- | -------------------- |
| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | | setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. |
**Error codes** **Error codes**
...@@ -2725,7 +2725,7 @@ photoOutput.capture(settings, (err) => { ...@@ -2725,7 +2725,7 @@ photoOutput.capture(settings, (err) => {
### capture ### capture
capture(setting?: PhotoCaptureSetting): Promise<void\> capture(setting?: PhotoCaptureSetting): Promise\<void\>
Captures a photo with the specified shooting parameters. This API uses a promise to return the result. Captures a photo with the specified shooting parameters. This API uses a promise to return the result.
...@@ -2741,7 +2741,7 @@ Captures a photo with the specified shooting parameters. This API uses a promise ...@@ -2741,7 +2741,7 @@ Captures a photo with the specified shooting parameters. This API uses a promise
| Type | Description | | Type | Description |
| -------------- | ------------------------ | | -------------- | ------------------------ |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2785,7 +2785,7 @@ let isSupported = photoOutput.isMirrorSupported(); ...@@ -2785,7 +2785,7 @@ let isSupported = photoOutput.isMirrorSupported();
### release ### release
release(callback: AsyncCallback<void\>): void release(callback: AsyncCallback\<void\>): void
Releases output resources. This API uses an asynchronous callback to return the result. Releases output resources. This API uses an asynchronous callback to return the result.
...@@ -2795,7 +2795,7 @@ Releases output resources. This API uses an asynchronous callback to return the ...@@ -2795,7 +2795,7 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2819,7 +2819,7 @@ photoOutput.release((err) => { ...@@ -2819,7 +2819,7 @@ photoOutput.release((err) => {
### release ### release
release(): Promise<void\> release(): Promise\<void\>
Releases output resources. This API uses a promise to return the result. Releases output resources. This API uses a promise to return the result.
...@@ -2829,7 +2829,7 @@ Releases output resources. This API uses a promise to return the result. ...@@ -2829,7 +2829,7 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -2851,7 +2851,7 @@ photoOutput.release().then(() => { ...@@ -2851,7 +2851,7 @@ photoOutput.release().then(() => {
### on('captureStart') ### on('captureStart')
on(type: 'captureStart', callback: AsyncCallback<number\>): void on(type: 'captureStart', callback: AsyncCallback\<number\>): void
Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. Listens for shooting start events. This API uses an asynchronous callback to return the capture ID.
...@@ -2862,7 +2862,7 @@ Listens for shooting start events. This API uses an asynchronous callback to ret ...@@ -2862,7 +2862,7 @@ Listens for shooting start events. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------ | | -------- | ---------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure each time a photo is taken.| | type | string | Yes | Event type. The value is fixed at **'captureStart'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and returned when the bottom layer starts exposure each time a photo is taken.|
| callback | AsyncCallback<number\> | Yes | Callback used to return the capture ID. | | callback | AsyncCallback\<number\> | Yes | Callback used to return the capture ID. |
**Example** **Example**
...@@ -2874,7 +2874,7 @@ photoOutput.on('captureStart', (captureId) => { ...@@ -2874,7 +2874,7 @@ photoOutput.on('captureStart', (captureId) => {
### on('frameShutter') ### on('frameShutter')
on(type: 'frameShutter', callback: AsyncCallback<FrameShutterInfo\>): void on(type: 'frameShutter', callback: AsyncCallback\<FrameShutterInfo\>): void
Listens for frame shutter events. This API uses an asynchronous callback to return the event information. Listens for frame shutter events. This API uses an asynchronous callback to return the event information.
...@@ -2885,7 +2885,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu ...@@ -2885,7 +2885,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------- | --- | ------------------------------------ | | -------- | ---------- | --- | ------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The event can be listened for when a **photoOutput** instance is created.| | type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The event can be listened for when a **photoOutput** instance is created.|
| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. A new photographing request can be delivered as long as this event is returned. | | callback | AsyncCallback\<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. A new photographing request can be delivered as long as this event is returned. |
**Example** **Example**
...@@ -2898,7 +2898,7 @@ photoOutput.on('frameShutter', (frameShutterInfo) => { ...@@ -2898,7 +2898,7 @@ photoOutput.on('frameShutter', (frameShutterInfo) => {
### on('captureEnd') ### on('captureEnd')
on(type: 'captureEnd', callback: AsyncCallback<CaptureEndInfo\>): void on(type: 'captureEnd', callback: AsyncCallback\<CaptureEndInfo\>): void
Listens for shooting end events. This API uses an asynchronous callback to return the event information. Listens for shooting end events. This API uses an asynchronous callback to return the event information.
...@@ -2909,7 +2909,7 @@ Listens for shooting end events. This API uses an asynchronous callback to retur ...@@ -2909,7 +2909,7 @@ Listens for shooting end events. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | ---------------------------------------- | | -------- | --------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding information is returned when the photographing is complete.| | type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding information is returned when the photographing is complete.|
| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | | callback | AsyncCallback\<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. |
**Example** **Example**
...@@ -2922,7 +2922,7 @@ photoOutput.on('captureEnd', (captureEndInfo) => { ...@@ -2922,7 +2922,7 @@ photoOutput.on('captureEnd', (captureEndInfo) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<BusinessError\>): void on(type: 'error', callback: ErrorCallback\<BusinessError\>): void
Listens for **PhotoOutput** errors. This API uses a callback to return the errors. Listens for **PhotoOutput** errors. This API uses a callback to return the errors.
...@@ -2933,7 +2933,7 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error ...@@ -2933,7 +2933,7 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ----------------------------------- | | -------- | ------------- | ---- | ----------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a photographing-related API.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **photoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a photographing-related API.|
| callback | ErrorCallback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | ErrorCallback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -2971,7 +2971,7 @@ Implements output information used in a video recording session. This class inhe ...@@ -2971,7 +2971,7 @@ Implements output information used in a video recording session. This class inhe
### start ### start
start(callback: AsyncCallback<void\>): void start(callback: AsyncCallback\<void\>): void
Starts video recording. This API uses an asynchronous callback to return the result. Starts video recording. This API uses an asynchronous callback to return the result.
...@@ -2981,7 +2981,7 @@ Starts video recording. This API uses an asynchronous callback to return the res ...@@ -2981,7 +2981,7 @@ Starts video recording. This API uses an asynchronous callback to return the res
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- | | -------- | -------------------- | ---- | -------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3006,7 +3006,7 @@ videoOutput.start((err) => { ...@@ -3006,7 +3006,7 @@ videoOutput.start((err) => {
### start ### start
start(): Promise<void\> start(): Promise\<void\>
Starts video recording. This API uses a promise to return the result. Starts video recording. This API uses a promise to return the result.
...@@ -3016,7 +3016,7 @@ Starts video recording. This API uses a promise to return the result. ...@@ -3016,7 +3016,7 @@ Starts video recording. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3039,7 +3039,7 @@ videoOutput.start().then(() => { ...@@ -3039,7 +3039,7 @@ videoOutput.start().then(() => {
### stop ### stop
stop(callback: AsyncCallback<void\>): void stop(callback: AsyncCallback\<void\>): void
Stops video recording. This API uses an asynchronous callback to return the result. Stops video recording. This API uses an asynchronous callback to return the result.
...@@ -3049,7 +3049,7 @@ Stops video recording. This API uses an asynchronous callback to return the resu ...@@ -3049,7 +3049,7 @@ Stops video recording. This API uses an asynchronous callback to return the resu
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ | | -------- | -------------------- | ---- | ------------------------ |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -3065,7 +3065,7 @@ videoOutput.stop((err) => { ...@@ -3065,7 +3065,7 @@ videoOutput.stop((err) => {
### stop ### stop
stop(): Promise<void\> stop(): Promise\<void\>
Stops video recording. This API uses a promise to return the result. Stops video recording. This API uses a promise to return the result.
...@@ -3075,7 +3075,7 @@ Stops video recording. This API uses a promise to return the result. ...@@ -3075,7 +3075,7 @@ Stops video recording. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -3089,7 +3089,7 @@ videoOutput.stop().then(() => { ...@@ -3089,7 +3089,7 @@ videoOutput.stop().then(() => {
### release ### release
release(callback: AsyncCallback<void\>): void release(callback: AsyncCallback\<void\>): void
Releases output resources. This API uses an asynchronous callback to return the result. Releases output resources. This API uses an asynchronous callback to return the result.
...@@ -3099,7 +3099,7 @@ Releases output resources. This API uses an asynchronous callback to return the ...@@ -3099,7 +3099,7 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- | | -------- | -------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3123,7 +3123,7 @@ videoOutput.release((err) => { ...@@ -3123,7 +3123,7 @@ videoOutput.release((err) => {
### release ### release
release(): Promise<void\> release(): Promise\<void\>
Releases output resources. This API uses a promise to return the result. Releases output resources. This API uses a promise to return the result.
...@@ -3133,7 +3133,7 @@ Releases output resources. This API uses a promise to return the result. ...@@ -3133,7 +3133,7 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------- | ----------------------- | | -------------- | ----------------------- |
| Promise<void\>| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3155,7 +3155,7 @@ videoOutput.release().then(() => { ...@@ -3155,7 +3155,7 @@ videoOutput.release().then(() => {
### on('frameStart') ### on('frameStart')
on(type: 'frameStart', callback: AsyncCallback<void\>): void on(type: 'frameStart', callback: AsyncCallback\<void\>): void
Listens for video recording start events. This API uses an asynchronous callback to return the result. Listens for video recording start events. This API uses an asynchronous callback to return the result.
...@@ -3166,7 +3166,7 @@ Listens for video recording start events. This API uses an asynchronous callback ...@@ -3166,7 +3166,7 @@ Listens for video recording start events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ----------------------------------------- | | -------- | -------------------- | ---- | ----------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **videoOutput** instance is created. The event is triggered and the corresponding information is returned when the bottom layer starts exposure for the first time.| | type | string | Yes | Event type. The value is fixed at **'frameStart'**. The event can be listened for when a **videoOutput** instance is created. The event is triggered and the corresponding information is returned when the bottom layer starts exposure for the first time.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. The recording starts as long as this event is returned. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. The recording starts as long as this event is returned. |
**Example** **Example**
...@@ -3178,7 +3178,7 @@ videoOutput.on('frameStart', () => { ...@@ -3178,7 +3178,7 @@ videoOutput.on('frameStart', () => {
### on('frameEnd') ### on('frameEnd')
on(type: 'frameEnd', callback: AsyncCallback<void\>): void on(type: 'frameEnd', callback: AsyncCallback\<void\>): void
Listens for video recording stop events. This API uses an asynchronous callback to return the result. Listens for video recording stop events. This API uses an asynchronous callback to return the result.
...@@ -3189,7 +3189,7 @@ Listens for video recording stop events. This API uses an asynchronous callback ...@@ -3189,7 +3189,7 @@ Listens for video recording stop events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------ | | -------- | -------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and returned when the last frame of recording is complete.| | type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and returned when the last frame of recording is complete.|
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. The recording ends as long as this event is returned. | | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. The recording ends as long as this event is returned. |
**Example** **Example**
...@@ -3201,7 +3201,7 @@ videoOutput.on('frameEnd', () => { ...@@ -3201,7 +3201,7 @@ videoOutput.on('frameEnd', () => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<BusinessError\>): void on(type: 'error', callback: ErrorCallback\<BusinessError\>): void
Listens for errors that occur during video recording. This API uses a callback to return the result. Listens for errors that occur during video recording. This API uses a callback to return the result.
...@@ -3212,7 +3212,7 @@ Listens for errors that occur during video recording. This API uses a callback t ...@@ -3212,7 +3212,7 @@ Listens for errors that occur during video recording. This API uses a callback t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------- | ---- | -------------------------------------- | | -------- | ----------- | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a recording-related API such as **start()** and **release()**.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **videoOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a recording-related API such as **start()** and **release()**.|
| callback | Callback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | Callback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -3228,7 +3228,7 @@ Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. ...@@ -3228,7 +3228,7 @@ Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**.
### start ### start
start(callback: AsyncCallback<void\>): void start(callback: AsyncCallback\<void\>): void
Starts to output metadata. This API uses an asynchronous callback to return the result. Starts to output metadata. This API uses an asynchronous callback to return the result.
...@@ -3238,7 +3238,7 @@ Starts to output metadata. This API uses an asynchronous callback to return the ...@@ -3238,7 +3238,7 @@ Starts to output metadata. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------- | ---- | ------------------- | | -------- | -------------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3263,7 +3263,7 @@ metadataOutput.start((err) => { ...@@ -3263,7 +3263,7 @@ metadataOutput.start((err) => {
### start ### start
start(): Promise<void\> start(): Promise\<void\>
Starts to output metadata. This API uses a promise to return the result. Starts to output metadata. This API uses a promise to return the result.
...@@ -3273,7 +3273,7 @@ Starts to output metadata. This API uses a promise to return the result. ...@@ -3273,7 +3273,7 @@ Starts to output metadata. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ---------------------- | ------------------------ | | ---------------------- | ------------------------ |
| Promise<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.| | Promise\<void\> | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Error codes** **Error codes**
...@@ -3296,7 +3296,7 @@ metadataOutput.start().then(() => { ...@@ -3296,7 +3296,7 @@ metadataOutput.start().then(() => {
### stop ### stop
stop(callback: AsyncCallback<void\>): void stop(callback: AsyncCallback\<void\>): void
Stops outputting metadata. This API uses an asynchronous callback to return the result. Stops outputting metadata. This API uses an asynchronous callback to return the result.
...@@ -3306,7 +3306,7 @@ Stops outputting metadata. This API uses an asynchronous callback to return the ...@@ -3306,7 +3306,7 @@ Stops outputting metadata. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------- | ---- | ------------------- | | -------- | -------------------------- | ---- | ------------------- |
| callback | AsyncCallback<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -3322,7 +3322,7 @@ metadataOutput.stop((err) => { ...@@ -3322,7 +3322,7 @@ metadataOutput.stop((err) => {
### stop ### stop
stop(): Promise<void\> stop(): Promise\<void\>
Stops outputting metadata. This API uses a promise to return the result. Stops outputting metadata. This API uses a promise to return the result.
...@@ -3332,7 +3332,7 @@ Stops outputting metadata. This API uses a promise to return the result. ...@@ -3332,7 +3332,7 @@ Stops outputting metadata. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ---------------------- | --------------------------- | | ---------------------- | --------------------------- |
| Promise<void\> | Promise used to return the result.| | Promise\<void\> | Promise used to return the result.|
**Example** **Example**
...@@ -3346,7 +3346,7 @@ metadataOutput.stop().then(() => { ...@@ -3346,7 +3346,7 @@ metadataOutput.stop().then(() => {
### on('metadataObjectsAvailable') ### on('metadataObjectsAvailable')
on(type: 'metadataObjectsAvailable', callback: AsyncCallback<Array<MetadataObject\>\>): void on(type: 'metadataObjectsAvailable', callback: AsyncCallback\<Array\<MetadataObject\>\>): void
Listens for metadata objects. This API uses an asynchronous callback to return the result. Listens for metadata objects. This API uses an asynchronous callback to return the result.
...@@ -3357,7 +3357,7 @@ Listens for metadata objects. This API uses an asynchronous callback to return t ...@@ -3357,7 +3357,7 @@ Listens for metadata objects. This API uses an asynchronous callback to return t
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------- | ---- | ------------------------------------ | | -------- | -------------- | ---- | ------------------------------------ |
| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding metadata is returned when valid metadata is detected.| | type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding metadata is returned when valid metadata is detected.|
| callback | Callback<Array<[MetadataObject](#metadataobject)\>\> | Yes | Callback used to return the metadata.| | callback | Callback\<Array\<[MetadataObject](#metadataobject)\>\> | Yes | Callback used to return the metadata.|
**Example** **Example**
...@@ -3369,7 +3369,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { ...@@ -3369,7 +3369,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => {
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback<BusinessError\>): void on(type: 'error', callback: ErrorCallback\<BusinessError\>): void
Listens for metadata errors. This API uses an asynchronous callback to return the result. Listens for metadata errors. This API uses an asynchronous callback to return the result.
...@@ -3380,7 +3380,7 @@ Listens for metadata errors. This API uses an asynchronous callback to return th ...@@ -3380,7 +3380,7 @@ Listens for metadata errors. This API uses an asynchronous callback to return th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | --------------------------------------- | | -------- | ------------- | ---- | --------------------------------------- |
| type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a metadata-related API such as **start()** and **release()**.| | type | string | Yes | Event type. The value is fixed at **'error'**. The event can be listened for when a **metadataOutput** instance is created. This event is triggered and the corresponding error message is returned when an error occurs during the calling of a metadata-related API such as **start()** and **release()**.|
| callback | Callback<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). | | callback | Callback\<BusinessError\> | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example** **Example**
...@@ -3417,6 +3417,8 @@ Defines a rectangle. ...@@ -3417,6 +3417,8 @@ Defines a rectangle.
Implements camera metadata, which is the data source of [CameraInput](#camerainput). The metadata is obtained through metadataOutput.on('metadataObjectsAvailable'). Implements camera metadata, which is the data source of [CameraInput](#camerainput). The metadata is obtained through metadataOutput.on('metadataObjectsAvailable').
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------- | ---- | -----------------| | -------- | ------------------------------- | ---- | -----------------|
| type | [MetadataObjectType](#metadataobjecttype) | No | Metadata data type. Only face recognition is supported.| | type | [MetadataObjectType](#metadataobjecttype) | No | Metadata data type. Only face recognition is supported.|
......
...@@ -35,7 +35,6 @@ Implements initialization for the interpolation curve, which is used to create a ...@@ -35,7 +35,6 @@ Implements initialization for the interpolation curve, which is used to create a
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Interpolation curve.| | [ICurve](#icurve) | Interpolation curve.|
**Example** **Example**
```ts ```ts
...@@ -57,7 +56,7 @@ Creates a step curve. ...@@ -57,7 +56,7 @@ Creates a step curve.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------- | ----| ------------------------------------------------------------ | | ------ | ------- | ----| ------------------------------------------------------------ |
| count | number | Yes | Number of steps. The value must be a positive integer. | | count | number | Yes | Number of steps. The value must be a positive integer.<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the value **0**.|
| end | boolean | Yes | Whether jumping occurs when the interpolation ends.<br>- **true**: Jumping occurs when the interpolation ends.<br>- **false**: Jumping occurs when the interpolation starts.| | end | boolean | Yes | Whether jumping occurs when the interpolation ends.<br>- **true**: Jumping occurs when the interpolation ends.<br>- **false**: Jumping occurs when the interpolation starts.|
**Return value** **Return value**
...@@ -66,7 +65,6 @@ Creates a step curve. ...@@ -66,7 +65,6 @@ Creates a step curve.
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve) | Interpolation curve.| | [ICurve](#icurve) | Interpolation curve.|
**Example** **Example**
```ts ```ts
...@@ -85,12 +83,13 @@ Creates a cubic Bezier curve. The curve values must be between 0 and 1. ...@@ -85,12 +83,13 @@ Creates a cubic Bezier curve. The curve values must be between 0 and 1.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | -------------- | | Name| Type | Mandatory| Description |
| x1 | number | Yes | X coordinate of the first point on the Bezier curve.| | ------ | ------ | ---- | ------------------------------------------------------------ |
| y1 | number | Yes | Y coordinate of the first point on the Bezier curve.| | x1 | number | Yes | X coordinate of the first point on the Bezier curve.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.|
| x2 | number | Yes | X coordinate of the second point on the Bezier curve.| | y1 | number | Yes | Y coordinate of the first point on the Bezier curve.<br>Value range: (-∞, +∞) |
| y2 | number | Yes | Y coordinate of the second point on the Bezier curve.| | x2 | number | Yes | X coordinate of the second point on the Bezier curve.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.|
| y2 | number | Yes | Y coordinate of the second point on the Bezier curve.<br>Value range: (-∞, +∞) |
**Return value** **Return value**
...@@ -112,17 +111,17 @@ Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. ...@@ -112,17 +111,17 @@ Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve.
springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve
Creates a spring curve. Creates a spring curve. The curve shape is subject to the spring parameters, and the animation duration is subject to the **duration** parameter in **animation** and **animateTo**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ------------------------------------------------------------ |
| velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| | velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state.<br>Value range: (-∞, +∞)|
| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the value **1**.|
| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the value **1**.|
| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the value **1**.|
**Return value** **Return value**
...@@ -149,18 +148,19 @@ Creates a spring animation curve. If multiple spring animations are applied to t ...@@ -149,18 +148,19 @@ Creates a spring animation curve. If multiple spring animations are applied to t
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| response | number | No | Duration of one complete oscillation, in seconds.<br>Default value: **0.55**| | response | number | No | Duration of one complete oscillation,<br>Default value: **0.55**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.|
| dampingFraction | number | No | Damping coefficient.<br>**0**: undamped. In this case, the spring oscillates forever.<br>> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.<br>**1**: critically damped.<br>> 1: overdamped. In this case, the spring approaches equilibrium gradually.<br>Default value: **0.825**| | dampingFraction | number | No | Damping coefficient.<br>**0**: undamped. In this case, the spring oscillates forever.<br>> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.<br>**1**: critically damped.<br>> 1: overdamped. In this case, the spring approaches equilibrium gradually.<br>Default value: **0.825**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.55**.|
| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.<br> Default value: **0**| | overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.<br><br>Default value: **0**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0**.<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **[animation](../arkui-ts/ts-animatorproperty.md)** or **[animateTo](../arkui-ts/ts-explicit-animation.md)**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **[interpolate](#interpolate)** function of the curve.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Curve.<br>Note: The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| | [ICurve](#icurve)| Curve.<br>**NOTE**<br>The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the **[interpolate](#interpolate)** function of the curve.|
**Example** **Example**
...@@ -182,17 +182,18 @@ Creates a responsive spring animation curve. It is a special case of [springMoti ...@@ -182,17 +182,18 @@ Creates a responsive spring animation curve. It is a special case of [springMoti
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| response | number | No | See **response** in **springMotion**. Default value: **0.15**| | response | number | No | See **response** in **springMotion**.<br>Default value: **0.15**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.15**.|
| dampingFraction | number | No | See **dampingFraction** in **springMotion**. Default value: **0.86**| | dampingFraction | number | No | See **dampingFraction** in **springMotion**.<br>Default value: **0.86**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.86**.|
| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25**| | overlapDuration | number | No | See **overlapDuration** in **springMotion**.<br>Default value: **0.25**<br>Unit: second<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value **0.25**.<br> To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **[animation](../arkui-ts/ts-animatorproperty.md)** or **[animateTo](../arkui-ts/ts-explicit-animation.md)**. In addition, the interpolation cannot be obtained by using the **[interpolate](#interpolate)** function of the curve.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------------------- | ---------------- | | ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Curve.<br>**NOTE**<br>1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| | [ICurve](#icurve)| Curve.<br>**NOTE**<br>1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.<br>2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the **interpolate** function of the curve.|
**Example** **Example**
...@@ -202,6 +203,39 @@ Curves.responsiveSpringMotion() // Create a responsive spring animation curve wi ...@@ -202,6 +203,39 @@ Curves.responsiveSpringMotion() // Create a responsive spring animation curve wi
``` ```
## Curves.interpolatingSpringCurve<sup>10+</sup>
interpolatingSpring(velocity: number, mass: number, stiffness: number, damping: number): ICurve
Creates an interpolating spring curve animated from 0 to 1. The actual animation value is calculated based on the curve. The animation duration is subject to the curve parameters, rather than the **duration** parameter in **animation** or **animateTo**.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state. The velocity is the normalized velocity, and its value is equal to the actual velocity at the beginning of the animation divided by the animation attribute change value.|
| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.|
| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.|
| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.|
**Return value**
| Type | Description |
| ---------------------------------- | ---------------- |
| [ICurve](#icurve)| Interpolation curve.|
**Example**
```ts
import Curves from '@ohos.curves'
Curves.interpolatingSpring(100, 1, 228, 30) // Create an interpolating spring curve whose duration is subject to spring parameters.
```
## ICurve ## ICurve
...@@ -218,8 +252,8 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -218,8 +252,8 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | -------------------------------------------- | | -------- | ------ | ---- | ------------------------------------------------------------ |
| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| | fraction | number | Yes | Current normalized time.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.|
**Return value** **Return value**
...@@ -300,7 +334,7 @@ Creates a spring curve. This API is deprecated since API version 9. You are advi ...@@ -300,7 +334,7 @@ Creates a spring curve. This API is deprecated since API version 9. You are advi
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- | | --------- | ------ | ---- | ----- |
| velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| | velocity | number | Yes | Initial velocity. It is applied by external factors to the spring animation, designed to help ensure the smooth transition from the previous motion state.|
| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| | mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.|
| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| | stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.|
| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| | damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.|
......
...@@ -131,13 +131,13 @@ A class that stores the color picked. ...@@ -131,13 +131,13 @@ A class that stores the color picked.
## ColorPicker ## ColorPicker
A class used to obtain the main color of an image from its data. Before calling any method of **ColorPicker**, use [createColorPicker](#effectkitcreatecolorpicker) to create a **ColorPicker** instance. A class used to obtain the color from an image. Before calling any method of **ColorPicker**, use [createColorPicker](#effectkitcreatecolorpicker) to create a **ColorPicker** instance.
### getMainColor ### getMainColor
getMainColor(): Promise\<Color> getMainColor(): Promise\<Color>
Obtains the main color of the image and writes the result to a **[Color](#color)** instance. This API uses a promise to return the result. Obtains the main color from the image and writes the result to a [Color](#color) instance. This API uses a promise to return the result.
**System capability**: SystemCapability.Multimedia.Image.Core **System capability**: SystemCapability.Multimedia.Image.Core
...@@ -162,7 +162,7 @@ colorPicker.getMainColor().then(color => { ...@@ -162,7 +162,7 @@ colorPicker.getMainColor().then(color => {
getMainColorSync(): Color getMainColorSync(): Color
Obtains the main color of the image and writes the result to a **[Color](#color)** instance. This API returns the result in synchronous mode. Obtains the main color from the image and writes the result to a [Color](#color) instance. This API returns the result in synchronous mode.
**System capability**: SystemCapability.Multimedia.Image.Core **System capability**: SystemCapability.Multimedia.Image.Core
...@@ -180,6 +180,93 @@ console.log('get main color =' + color); ...@@ -180,6 +180,93 @@ console.log('get main color =' + color);
``` ```
![en-us_image_Main_Color.png](figures/en-us_image_Main_Color.png) ![en-us_image_Main_Color.png](figures/en-us_image_Main_Color.png)
### getLargestProportionColor<sup>10+</sup>
getLargestProportionColor(): Color
Obtains the color with the largest proportion from the image and writes the result to a [Color](#color) instance. This API returns the result in synchronous mode.
**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| :------------- | :---------------------------------------------- |
| [Color](#color) | Color value of the color with the largest proportion. If the operation fails, **null** is returned.|
**Example**
```js
let color = colorPicker.getLargestProportionColor();
console.log('get largest proportion color =' + color);
```
![en-us_image_Largest_Proportion_Color.png](figures/en-us_image_Largest_Proportion_Color.png)
### getHighestSaturationColor<sup>10+</sup>
getHighestSaturationColor(): Color
Obtains the color with the highest saturation from the image and writes the result to a [Color](#color) instance. This API returns the result in synchronous mode.
**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| :------------- | :---------------------------------------------- |
| [Color](#color) | Color value of the color with the highest saturation. If the operation fails, **null** is returned.|
**Example**
```js
let color = colorPicker.getHighestSaturationColor();
console.log('get highest saturation color =' + color);
```
![en-us_image_Highest_Saturation_Color.png](figures/en-us_image_Highest_Saturation_Color.png)
### getAverageColor<sup>10+</sup>
getAverageColor(): Color
Obtains the average color from the image and writes the result to a [Color](#color) instance. This API returns the result in synchronous mode.
**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| :------------- | :---------------------------------------------- |
| [Color](#color) | Average color value. If the operation fails, **null** is returned.|
**Example**
```js
let color = colorPicker.getAverageColor();
console.log('get average color =' + color);
```
![en-us_image_Average_Color.png](figures/en-us_image_Average_Color.png)
### isBlackOrWhiteOrGrayColor<sup>10+</sup>
isBlackOrWhiteOrGrayColor(color: number): boolean
Checks whether this image is black, white, and gray.
**System capability**: SystemCapability.Multimedia.Image.Core
**Return value**
| Type | Description |
| :------------- | :---------------------------------------------- |
| boolean | Returns **true** if the image is black, white, and gray; returns **false** otherwise.|
**Example**
```js
let bJudge = colorPicker.isBlackOrWhiteOrGrayColor(0xFFFFFFFF);
console.log('is black or white or gray color[bool](white) =' + bJudge);
```
## Filter ## Filter
A class used to add a specified effect to an image. Before calling any method of **Filter**, use [createEffect](#effectkitcreateeffect) to create a **Filter** instance. A class used to add a specified effect to an image. Before calling any method of **Filter**, use [createEffect](#effectkitcreateeffect) to create a **Filter** instance.
......
...@@ -282,10 +282,10 @@ Translates this matrix object along the x, y, and z axes. ...@@ -282,10 +282,10 @@ Translates this matrix object along the x, y, and z axes.
**Parameters** **Parameters**
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------- | | ------ | ------ | ---- | ----------------------------------------------------------- |
| x | number | No | Translation distance along the x-axis, in px.<br>Default value: **0**| | x | number | No | Translation distance along the x-axis, in px.<br>Default value: **0**<br>Value range: (-∞, +∞)|
| y | number | No | Translation distance along the y-axis, in px.<br>Default value: **0**| | y | number | No | Translation distance along the y-axis, in px.<br>Default value: **0**<br>Value range: (-∞, +∞)|
| z | number | No | Translation distance along the z-axis, in px.<br>Default value: **0**| | z | number | No | Translation distance along the z-axis, in px.<br>Default value: **0**<br>Value range: (-∞, +∞)|
**Return value** **Return value**
...@@ -329,12 +329,12 @@ Scales this matrix object along the x, y, and z axes. ...@@ -329,12 +329,12 @@ Scales this matrix object along the x, y, and z axes.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------ | ---- | --------------------------------- | | ------- | ------ | ---- | ------------------------------------------------------------ |
| x | number | No | Scaling multiple along the x-axis.<br>Default value: **1** | | x | number | No | Scaling multiple along the x-axis. If the value is greater than 1, the image is scaled up along the x-axis. If the value is less than 1, the image is scaled down along the x-axis.<br>Default value: **1**<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| y | number | No | Scaling multiple along the y-axis.<br>Default value: **1** | | y | number | No | Scaling multiple along the y-axis. If the value is greater than 1, the image is scaled up along the y-axis. If the value is less than 1, the image is scaled down along the y-axis.<br>Default value: **1**<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| z | number | No | Scaling multiple along the z-axis.<br>Default value: **1** | | z | number | No | Scaling multiple along the z-axis. If the value is greater than 1, the image is scaled up along the z-axis. If the value is less than 1, the image is scaled down along the z-axis.<br>Default value: **1**<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 0 evaluates to the default value.|
| centerX | number | No | X coordinate of the center point.<br>Default value: **0**| | centerX | number | No | X coordinate of the center point.<br>Default value: **0**<br>Value range: (-∞, +∞) |
| centerY | number | No | Y coordinate of the center point.<br>Default value: **0**| | centerY | number | No | Y coordinate of the center point.<br>Default value: **0**<br>Value range: (-∞, +∞) |
**Return value** **Return value**
...@@ -377,13 +377,13 @@ Rotates this matrix object along the x, y, and z axes. ...@@ -377,13 +377,13 @@ Rotates this matrix object along the x, y, and z axes.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------ | ---- | --------------------------------- | | ------- | ------ | ---- | ------------------------------------------------------- |
| x | number | No | X coordinate of the rotation axis vector.<br>Default value: **1** | | x | number | No | X coordinate of the rotation axis vector.<br>Default value: **1**<br>Value range: (-∞, +∞)|
| y | number | No | Y coordinate of the rotation axis vector.<br>Default value: **1** | | y | number | No | Y coordinate of the rotation axis vector.<br>Default value: **1**<br>Value range: (-∞, +∞)|
| z | number | No | Z coordinate of the rotation axis vector.<br>Default value: **1** | | z | number | No | Z coordinate of the rotation axis vector.<br>Default value: **1**<br>Value range: (-∞, +∞)|
| angle | number | No | Rotation angle.<br>Default value: **0** | | angle | number | No | Rotation angle.<br>Default value: **0** |
| centerX | number | No | X coordinate of the center point.<br>Default value: **0**| | centerX | number | No | X coordinate of the center point.<br>Default value: **0** |
| centerY | number | No | Y coordinate of the center point.<br>Default value: **0**| | centerY | number | No | Y coordinate of the center point.<br>Default value: **0** |
**Return value** **Return value**
......
...@@ -150,6 +150,8 @@ Locks the screen. This API uses an asynchronous callback to return the result. ...@@ -150,6 +150,8 @@ Locks the screen. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock **System capability**: SystemCapability.MiscServices.ScreenLock
**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_INNER
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
...@@ -186,6 +188,8 @@ Locks the screen. This API uses a promise to return the result. ...@@ -186,6 +188,8 @@ Locks the screen. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock **System capability**: SystemCapability.MiscServices.ScreenLock
**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_INNER
**System API**: This is a system API. **System API**: This is a system API.
**Return value** **Return value**
...@@ -220,6 +224,8 @@ Registers a callback for system events related to screen locking. This API can b ...@@ -220,6 +224,8 @@ Registers a callback for system events related to screen locking. This API can b
**System capability**: SystemCapability.MiscServices.ScreenLock **System capability**: SystemCapability.MiscServices.ScreenLock
**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_INNER
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
...@@ -262,6 +268,8 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac ...@@ -262,6 +268,8 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac
**System capability**: SystemCapability.MiscServices.ScreenLock **System capability**: SystemCapability.MiscServices.ScreenLock
**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_INNER
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
...@@ -300,6 +308,8 @@ Sends an event to the screen lock service. This API uses a promise to return the ...@@ -300,6 +308,8 @@ Sends an event to the screen lock service. This API uses a promise to return the
**System capability**: SystemCapability.MiscServices.ScreenLock **System capability**: SystemCapability.MiscServices.ScreenLock
**Required permissions**: ohos.permission.ACCESS_SCREEN_LOCK_INNER
**System API**: This is a system API. **System API**: This is a system API.
**Parameters** **Parameters**
......
...@@ -81,7 +81,7 @@ import web_webview from '@ohos.web.webview' ...@@ -81,7 +81,7 @@ import web_webview from '@ohos.web.webview'
@Component @Component
struct WebComponent { struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
msgPort: WebMessagePort[] = null; msgPort: web_webview.WebMessagePort[] = null;
build() { build() {
Column() { Column() {
...@@ -214,6 +214,240 @@ struct WebComponent { ...@@ -214,6 +214,240 @@ struct WebComponent {
} }
``` ```
### isExtentionType<sup>10+</sup>
**System capability**: SystemCapability.Web.Webview.Core
| Name | Type | Readable| Writable| Description |
| ------------ | ------ | ---- | ---- | ------------------------------------------------|
| isExtentionType | boolean | Yes | No| Whether to use the extended interface when creating a **WebMessagePort** instance. |
### postMessageEventExt<sup>10+</sup>
postMessageEventExt(message: WebMessageExt): void
Sends a message. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | :------------- |
| message | [WebMessageExt](#webmessageext) | Yes | Message to send.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100010 | Can not post message using this port. |
### onMessageEventExt<sup>10+</sup>
onMessageEventExt(callback: (result: WebMessageExt) => void): void
Registers a callback to receive messages from the HTML5 side.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | :------------------- |
| result | [WebMessageExt](#webmessageext10) | Yes | Message received.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ----------------------------------------------- |
| 17100006 | Can not register message event using this port. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
// Example of sending messages between an application and a web page: Use the init_web_messageport channel to receive messages from the web page on the application side through port 0 and receive messages from the application on the web page side through port 1.
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[] = null;
nativePort: web_webview.WebMessagePort = null;
@State msg1:string = "";
@State msg2:string = "";
message: web_webview.WebMessageExt = new web_webview.WebMessageExt();
build() {
Column() {
Text(this.msg1).fontSize(16)
Text(this.msg2).fontSize(16)
Button('SendToH5')
.onClick(() => {
// Use the local port to send messages to HTML5.
try {
console.log("In eTS side send true start");
if (this.nativePort) {
this.message.setString("helloFromEts");
this.nativePort.postMessageEventExt(this.message);
}
}
catch (error) {
console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.onPageEnd((e)=>{
console.log("In eTS side message onPageEnd init mesaage channel");
// 1. Create a message port.
this.ports = this.controller.createWebMessagePorts(true);
// 2. Send port 1 to HTML5.
this.controller.postMessage("init_web_messageport", [this.ports[1]], "*");
// 3. Save port 0 to the local host.
this.nativePort = this.ports[0];
// 4. Set the callback.
this.nativePort.onMessageEventExt((result) => {
console.log("In eTS side got message");
try {
var type = result.getType();
console.log("In eTS side getType:" + type);
switch (type) {
case web_webview.WebMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
this.msg2 = "result getString:" + ((result.getString()));
break;
}
case web_webview.WebMessageType.NUMBER: {
this.msg1 = "result type:" + typeof (result.getNumber());
this.msg2 = "result getNumber:" + ((result.getNumber()));
break;
}
case web_webview.WebMessageType.BOOLEAN: {
this.msg1 = "result type:" + typeof (result.getBoolean());
this.msg2 = "result getBoolean:" + ((result.getBoolean()));
break;
}
case web_webview.WebMessageType.ARRAY_BUFFER: {
this.msg1 = "result type:" + typeof (result.getArrayBuffer());
this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength));
break;
}
case web_webview.WebMessageType.ARRAY: {
this.msg1 = "result type:" + typeof (result.getArray());
this.msg2 = "result getArray:" + result.getArray();
break;
}
case web_webview.WebMessageType.ERROR: {
this.msg1 = "result type:" + typeof (result.getError());
this.msg2 = "result getError:" + result.getError();
break;
}
default: {
this.msg1 = "default break, type:" + type;
break;
}
}
}
catch (resError) {
console.log(`log error code: ${resError.code}, Message: ${resError.message}`);
}
});
})
}
}
}
```
```html
<!--index.html-->
<!DOCTYPE html>
<html lang="en-gb">
<head>
<title>WebView MessagePort Demo</title>
</head>
<body>
<h1>Html5 Send and Receive Message</h1>
<h3 id="msg">Receive string:</h3>
<h3 id="msg2">Receive arraybuffer:</h3>
<div style="font-size: 10pt; text-align: center;">
<input type="button" value="Send String" onclick="postStringToApp();" /><br/>
</div>
</body>
<script src="index.js"></script>
</html>
```
```js
//index.js
var h5Port;
window.addEventListener('message', function(event) {
if (event.data == 'init_web_messageport') {
if(event.ports[0] != null) {
h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side.
h5Port.onmessage = function(event) {
console.log("hwd In html got message");
// 2. Receive the message sent from the ArkTS side.
var result = event.data;
console.log("In html got message, typeof: ", typeof(result));
console.log("In html got message, result: ", (result));
if (typeof(result) == "string") {
console.log("In html got message, String: ", result);
document.getElementById("msg").innerHTML = "String:" + result;
} else if (typeof(result) == "number") {
console.log("In html side got message, number: ", result);
document.getElementById("msg").innerHTML = "Number:" + result;
} else if (typeof(result) == "boolean") {
console.log("In html side got message, boolean: ", result);
document.getElementById("msg").innerHTML = "Boolean:" + result;
} else if (typeof(result) == "object") {
if (result instanceof ArrayBuffer) {
document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength;
console.log("In html got message, byteLength: ", result.byteLength);
} else if (result instanceof Error) {
console.log("In html error message, err:" + (result));
console.log("In html error message, typeof err:" + typeof(result));
document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message;
} else if (result instanceof Array) {
console.log("In html got message, Array");
console.log("In html got message, Array length:" + result.length);
console.log("In html got message, Array[0]:" + (result[0]));
console.log("In html got message, typeof Array[0]:" + typeof(result[0]));
document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result;
} else {
console.log("In html got message, not any instance of support type");
document.getElementById("msg").innerHTML = "not any instance of support type";
}
} else {
console.log("In html got message, not support type");
document.getElementById("msg").innerHTML = "not support type";
}
}
h5Port.onmessageerror = (event) => {
console.error(`hwd In html Error receiving message: ${event}`);
};
}
}
})
// Use h5Port to send a message of the string type to the ArkTS side.
function postStringToApp() {
if (h5Port) {
console.log("In html send string message");
h5Port.postMessage("hello");
console.log("In html send string message end");
} else {
console.error("In html h5port is null, please init first");
}
}
```
## WebviewController ## WebviewController
Implements a **WebviewController** to control the behavior of the **\<Web>** component. A **WebviewController** can control only one **\<Web>** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\<Web>** component. Implements a **WebviewController** to control the behavior of the **\<Web>** component. A **WebviewController** can control only one **\<Web>** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\<Web>** component.
...@@ -422,7 +656,8 @@ struct WebComponent { ...@@ -422,7 +656,8 @@ struct WebComponent {
} }
``` ```
Example of loading local web pages: There are three methods for loading local resource files:
1. Using $rawfile
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview' import web_webview from '@ohos.web.webview'
...@@ -448,7 +683,7 @@ struct WebComponent { ...@@ -448,7 +683,7 @@ struct WebComponent {
} }
} }
``` ```
2. Using the resources protocol
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview' import web_webview from '@ohos.web.webview'
...@@ -475,6 +710,8 @@ struct WebComponent { ...@@ -475,6 +710,8 @@ struct WebComponent {
} }
``` ```
3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web).
```html ```html
<!-- xxx.html --> <!-- xxx.html -->
<!DOCTYPE html> <!DOCTYPE html>
...@@ -1229,6 +1466,232 @@ struct WebComponent { ...@@ -1229,6 +1466,232 @@ struct WebComponent {
} }
``` ```
### runJavaScriptExt<sup>10+</sup>
runJavaScriptExt(script: string, callback : AsyncCallback\<JsMessageExt>): void
Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------- |
| script | string | Yes | JavaScript script. |
| callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State msg1: string = ''
@State msg2: string = ''
build() {
Column() {
Text(this.msg1).fontSize(20)
Text(this.msg2).fontSize(20)
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
.onPageEnd(e => {
try {
this.controller.runJavaScriptExt(
'test()',
(error, result) => {
if (error) {
console.info(`run JavaScript error: ` + JSON.stringify(error))
return;
}
if (result) {
try {
var type = result.getType();
switch (type) {
case web_webview.JsMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
this.msg2 = "result getString:" + ((result.getString()));
break;
}
case web_webview.JsMessageType.NUMBER: {
this.msg1 = "result type:" + typeof (result.getNumber());
this.msg2 = "result getNumber:" + ((result.getNumber()));
break;
}
case web_webview.JsMessageType.BOOLEAN: {
this.msg1 = "result type:" + typeof (result.getBoolean());
this.msg2 = "result getBoolean:" + ((result.getBoolean()));
break;
}
case web_webview.JsMessageType.ARRAY_BUFFER: {
this.msg1 = "result type:" + typeof (result.getArrayBuffer());
this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength));
break;
}
case web_webview.JsMessageType.ARRAY: {
this.msg1 = "result type:" + typeof (result.getArray());
this.msg2 = "result getArray:" + result.getArray();
break;
}
default: {
this.msg1 = "default break, type:" + type;
break;
}
}
}
catch (resError) {
console.log(`log error code: ${resError.code}, Message: ${resError.message}`);
}
}
});
console.info('url: ', e.url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
}
}
}
//index.html
<!DOCTYPE html>
<html lang="en-gb">
<body>
<h1>run JavaScript Ext demo</h1>
</body>
<script type="text/javascript">
function test() {
return "hello, world";
}
</script>
</html>
```
### runJavaScriptExt<sup>10+</sup>
runJavaScriptExt(script: string): Promise\<JsMessageExt>
Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------- |
| script | string | Yes | JavaScript script.|
**Return value**
| Type | Description |
| --------------- | --------------------------------------------------- |
| Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State webResult: string = '';
@State msg1: string = ''
@State msg2: string = ''
build() {
Column() {
Text(this.webResult).fontSize(20)
Text(this.msg1).fontSize(20)
Text(this.msg2).fontSize(20)
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
.onPageEnd(e => {
this.controller.runJavaScriptExt('test()')
.then((result) => {
try {
var type = result.getType();
switch (type) {
case web_webview.JsMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
this.msg2 = "result getString:" + ((result.getString()));
break;
}
case web_webview.JsMessageType.NUMBER: {
this.msg1 = "result type:" + typeof (result.getNumber());
this.msg2 = "result getNumber:" + ((result.getNumber()));
break;
}
case web_webview.JsMessageType.BOOLEAN: {
this.msg1 = "result type:" + typeof (result.getBoolean());
this.msg2 = "result getBoolean:" + ((result.getBoolean()));
break;
}
case web_webview.JsMessageType.ARRAY_BUFFER: {
this.msg1 = "result type:" + typeof (result.getArrayBuffer());
this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength));
break;
}
case web_webview.JsMessageType.ARRAY: {
this.msg1 = "result type:" + typeof (result.getArray());
this.msg2 = "result getArray:" + result.getArray();
break;
}
default: {
this.msg1 = "default break, type:" + type;
break;
}
}
}
catch (resError) {
console.log(`log error code: ${resError.code}, Message: ${resError.message}`);
}
})
.catch(function (error) {
console.error("error: " + error);
})
})
}
}
}
//index.html
<!DOCTYPE html>
<html lang="en-gb">
<body>
<h1>run JavaScript Ext demo</h1>
</body>
<script type="text/javascript">
function test() {
return "hello, world";
}
</script>
</html>
```
### deleteJavaScriptRegister ### deleteJavaScriptRegister
deleteJavaScriptRegister(name: string): void deleteJavaScriptRegister(name: string): void
...@@ -1565,15 +2028,21 @@ struct WebComponent { ...@@ -1565,15 +2028,21 @@ struct WebComponent {
### createWebMessagePorts ### createWebMessagePorts
createWebMessagePorts(): Array\<WebMessagePort> createWebMessagePorts(isExtentionType?: boolean): Array\<WebMessagePort>
Creates web message ports. Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core **System capability**: SystemCapability.Web.Webview.Core
**Return value** **Parameters**
| Type | Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------- | ---- | :------------------------------|
| isExtentionType<sup>10+</sup> | boolean | No | Whether to use the extended interface. The default value is **false**, indicating that the extended interface is not used.|
**Return value**
| Type | Description |
| ---------------------- | ----------------- | | ---------------------- | ----------------- |
| Array\<WebMessagePort> | List of web message ports.| | Array\<WebMessagePort> | List of web message ports.|
...@@ -1626,8 +2095,8 @@ Sends a web message to an HTML5 window. ...@@ -1626,8 +2095,8 @@ Sends a web message to an HTML5 window.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ---------------------- | ---- | :------------------------------- | | ------ | ---------------------- | ---- | :------------------------------- |
| name | string | Yes | Message to send, including the data and message port.| | name | string | Yes | Name of the message to send. |
| ports | Array\<WebMessagePort> | Yes | Ports for receiving the message. | | ports | Array\<WebMessagePort> | Yes | Message ports for sending the message. |
| uri | string | Yes | URI for receiving the message. | | uri | string | Yes | URI for receiving the message. |
**Error codes** **Error codes**
...@@ -1739,9 +2208,9 @@ var output = document.querySelector('.output'); ...@@ -1739,9 +2208,9 @@ var output = document.querySelector('.output');
window.addEventListener('message', function (event) { window.addEventListener('message', function (event) {
if (event.data == '__init_port__') { if (event.data == '__init_port__') {
if (event.ports[0] != null) { if (event.ports[0] != null) {
h5Port = event.ports[0]; // 1. Save the port number sent from the ArkTS side. h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side.
h5Port.onmessage = function (event) { h5Port.onmessage = function (event) {
// 2. Receive the message sent from the ArkTS side. // 2. Receive the message sent from the eTS side.
var msg = 'Got message from ets:'; var msg = 'Got message from ets:';
var result = event.data; var result = event.data;
if (typeof(result) == "string") { if (typeof(result) == "string") {
...@@ -1763,7 +2232,7 @@ window.addEventListener('message', function (event) { ...@@ -1763,7 +2232,7 @@ window.addEventListener('message', function (event) {
} }
}) })
// 3. Use h5Port to send messages to the ArkTS side. // 3. Use h5Port to send messages to the eTS side.
function PostMsgToEts(data) { function PostMsgToEts(data) {
if (h5Port) { if (h5Port) {
h5Port.postMessage(data); h5Port.postMessage(data);
...@@ -3572,7 +4041,7 @@ struct Index { ...@@ -3572,7 +4041,7 @@ struct Index {
} }
``` ```
### setAudioMuted ### setAudioMuted<sup>10+</sup>
setAudioMuted(mute: boolean): void setAudioMuted(mute: boolean): void
...@@ -3586,6 +4055,14 @@ Mutes this web page. ...@@ -3586,6 +4055,14 @@ Mutes this web page.
| -------- | ------- | ---- | -------------------------------------- | | -------- | ------- | ---- | -------------------------------------- |
| mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| | mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example** **Example**
```ts ```ts
...@@ -3618,7 +4095,7 @@ Implements a **WebCookieManager** instance to manage behavior of cookies in **\< ...@@ -3618,7 +4095,7 @@ Implements a **WebCookieManager** instance to manage behavior of cookies in **\<
static getCookie(url: string): string static getCookie(url: string): string
Obtains the cookie value corresponding to the specified URL. Obtains the cookie corresponding to the specified URL.
**System capability**: SystemCapability.Web.Webview.Core **System capability**: SystemCapability.Web.Webview.Core
...@@ -3626,7 +4103,7 @@ Obtains the cookie value corresponding to the specified URL. ...@@ -3626,7 +4103,7 @@ Obtains the cookie value corresponding to the specified URL.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| ------ | ------ | ---- | :------------------------ | | ------ | ------ | ---- | :------------------------ |
| url | string | Yes | URL of the cookie value to obtain. A complete URL is recommended.| | url | string | Yes | URL of the cookie to obtain. A complete URL is recommended.|
**Return value** **Return value**
...@@ -3674,7 +4151,7 @@ struct WebComponent { ...@@ -3674,7 +4151,7 @@ struct WebComponent {
static setCookie(url: string, value: string): void static setCookie(url: string, value: string): void
Sets a cookie value for the specified URL. Sets a cookie for the specified URL.
**System capability**: SystemCapability.Web.Webview.Core **System capability**: SystemCapability.Web.Webview.Core
...@@ -3867,7 +4344,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and ...@@ -3867,7 +4344,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and
| Type | Description | | Type | Description |
| ------- | -------------------------------- | | ------- | -------------------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies.| | boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies. The default value is **true**.|
**Example** **Example**
...@@ -3946,7 +4423,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and ...@@ -3946,7 +4423,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and
| Type | Description | | Type | Description |
| ------- | -------------------------------------- | | ------- | -------------------------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.| | boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. The default value is **false**.|
**Example** **Example**
...@@ -5112,6 +5589,463 @@ Describes the data types supported for [WebMessagePort](#webmessageport). ...@@ -5112,6 +5589,463 @@ Describes the data types supported for [WebMessagePort](#webmessageport).
| string | String type.| | string | String type.|
| ArrayBuffer | Binary type.| | ArrayBuffer | Binary type.|
## JsMessageType<sup>10+</sup>
Describes the type of the returned result of script execution using [runJavaScirptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
| Name | Value| Description |
| ------------ | -- |--------------------------------- |
| NOT_SUPPORT | 0 |Unsupported data type.|
| STRING | 1 |String type.|
| NUMBER | 2 |Number type.|
| BOOLEAN | 3 |Boolean type.|
| ARRAY_BUFFER | 4 |Raw binary data buffer.|
| ARRAY | 5 |Array type.|
## WebMessageType<sup>10+</sup>
Describes the data type supported by the [webMessagePort](#webmessageport) API.
**System capability**: SystemCapability.Web.Webview.Core
| Name | Value| Description |
| ------------ | -- |------------------------------- |
| NOT_SUPPORT | 0 |Unsupported data type.|
| STRING | 1 |String type.|
| NUMBER | 2 |Number type.|
| BOOLEAN | 3 |Boolean type.|
| ARRAY_BUFFER | 4 |Raw binary data buffer.|
| ARRAY | 5 |Array type.|
| ERROR | 6 |Error object type.|
## JsMessageExt<sup>10+</sup>
Implements the **JsMessageExt** data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API.
### getType<sup>10+</sup>
getType(): JsMessageType
Obtains the type of the data object.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| --------------------------------------------------------- |
| [JsMessageType](#jsmessagetype10) | Type of the data object that is returned after script execution using the [runJavaScirptExt](#runjavascriptext10) API.|
### getString<sup>10+</sup>
getString(): string
Obtains string-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| string | Data of the string type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the result. |
### getNumber<sup>10+</sup>
getNumber(): number
Obtains number-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| number | Data of the number type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the result. |
### getBoolean<sup>10+</sup>
getBoolean(): boolean
Obtains Boolean-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| boolean | Data of the Boolean type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the result. |
### getArrayBuffer<sup>10+</sup>
getArrayBuffer(): ArrayBuffer
Obtains raw binary data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| ArrayBuffer | Raw binary data.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the result. |
### getArray<sup>10+</sup>
getArray(): Array\<string | number | boolean\>
Obtains array-type data of the data object. For the complete sample code, see [runJavaScriptExt](#runjavascriptext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| Array\<string | number | boolean\> | Data of the array type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the result. |
## WebMessageExt<sup>10+</sup>
Data object received and sent by the [webMessagePort](#webmessageport) interface.
### getType<sup>10+</sup>
getType(): WebMessageType
Obtains the type of the data object.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| --------------------------------------------------------- |
| [WebMessageType](#webmessagetype10) | Data type supported by the [webMessagePort](#webmessageport) API.|
### getString<sup>10+</sup>
getString(): string
Obtains string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| string | Data of the string type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### getNumber<sup>10+</sup>
getNumber(): number
Obtains number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| number | Data of the number type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### getBoolean<sup>10+</sup>
getBoolean(): boolean
Obtains Boolean-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| boolean | Data of the Boolean type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### getArrayBuffer<sup>10+</sup>
getArrayBuffer(): ArrayBuffer
Obtains raw binary data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| ArrayBuffer | Raw binary data.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### getArray<sup>10+</sup>
getArray(): Array\<string | number | boolean\>
Obtains array-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| Array\<string | number | boolean\> | Data of the array type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### getError<sup>10+</sup>
getError(): Error
Obtains the error-object-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| --------------| ------------- |
| Error | Data of the error object type.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setType<sup>10+</sup>
setType(type: WebMessageType): void
Sets the type for the data object.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------- |
| type | [WebMessageType](#webmessagetype10) | Yes | Data type supported by the [webMessagePort](#webmessageport) API.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setString<sup>10+</sup>
setString(message: string): void
Sets the string-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | string | Yes | String type.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setNumber<sup>10+</sup>
setNumber(message: number): void
Sets the number-type data of the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | number | Yes | Data of the number type.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setBoolean<sup>10+</sup>
setBoolean(message: boolean): void
Sets the Boolean-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | boolean | Yes | Data of the Boolean type.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setArrayBuffer<sup>10+</sup>
setArrayBuffer(message: ArrayBuffer): void
Sets the raw binary data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | ArrayBuffer | Yes | Raw binary data.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setArray<sup>10+</sup>
setArray(message: Array\<string | number | boolean\>): void
Sets the array-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | Array\<string \| number \| boolean\> | Yes | Data of the array type.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
### setError<sup>10+</sup>
setError(message: Error): void
Sets the error-object-type data for the data object. For the complete sample code, see [onMessageEventExt](#onmessageeventext10).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| message | Error | Yes | Data of the error object type.|
**Error codes**
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100014 | The type does not match with the value of the web message. |
## WebStorageOrigin ## WebStorageOrigin
Provides usage information of the Web SQL Database. Provides usage information of the Web SQL Database.
......
...@@ -64,11 +64,11 @@ Media logical operators (and, or, not, and only) are used to implement complex m ...@@ -64,11 +64,11 @@ Media logical operators (and, or, not, and only) are used to implement complex m
| Type | Description | | Type | Description |
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
| and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen and (device-type: wearable) and (max-height: 600) ** evaluates to true when the device type is wearable and the maximum height of the application is 600 pixel units.| | and | The **and** operator is used to combine multiple media features into one media query, in a logical AND operation. The query is valid only when all media features are true. It can also combine media types and media functions.<br>For example, **screen and (device-type: wearable) and (max-height: 600)** evaluates to **true** when the device type is wearable and the maximum height of the application is 600 pixel units.|
| not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.<br>For example, **not screen and (min-height: 50) and (max-height: 600) ** evaluates to true when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>You must specify the media type when using the **not** operator.| | not | The **not** operator is used to perform a logical negation for a media query. **true** is returned if the query condition is not met. Otherwise, **false** is returned. In a media query list, logical negation is performed only for the media query using the **not** operator.<br>For example, **not screen and (min-height: 50) and (max-height: 600)** evaluates to **true** when the height of the application is less than 50 pixel units or greater than 600 pixel units.<br>You must specify the media type when using the **not** operator.|
| only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen and (min-height: 50)<br>The browsers of earlier versions would mislead this sentence into **screen**, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>You must specify the media type when using the **only** operator.| | only | The **only** operator applies the selected style only when the entire expression is matched. It can be used to prevent ambiguity on browsers of earlier versions. The statements that contain both media types and media features produce ambiguity when they are received by some browsers of earlier versions. For example:<br>screen and (min-height: 50)<br>The browsers of earlier versions would mislead this sentence into **screen**, causing the fact that the specified style is applied when only the media type is matched. In this case, the **only** operator can be used to avoid this problem.<br>You must specify the media type when using the **only** operator.|
| ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen and (min-height: 1000), (round-screen: true) ** evaluates to true when the minimum height of the application is 1000 pixel units or the device screen is round.| | ,(comma) | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true. The effect of a comma operator is equivalent to that of the **or** operator.<br>For example, **screen and (min-height: 1000), (round-screen: true)** evaluates to **true** when the minimum height of the application is 1000 pixel units or the device screen is round.|
| or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen and (max-height: 1000) or (round-screen: true)** evaluates to true when the maximum height of the application is 1000 pixel units or the device screen is round.| | or | The **or** operator is used to combine multiple media features into one media query, in a logical OR operation. The query is valid if a media feature is true.<br>For example, **screen and (max-height: 1000) or (round-screen: true)** evaluates to **true** when the maximum height of the application is 1000 pixel units or the device screen is round.|
At MediaQuery Level 4, range query is imported so that you can use the operators including &lt;=, &gt;=, &lt;, and &gt; besides the max- and min-operators. At MediaQuery Level 4, range query is imported so that you can use the operators including &lt;=, &gt;=, &lt;, and &gt; besides the max- and min-operators.
......
...@@ -14,13 +14,13 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -14,13 +14,13 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ | | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | No | Animation duration, in ms.<br>Default value: **1000**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The maximum animation duration on an ArkTS widget is 1000 ms. If the set value exceeds the limit, the value **1000** will be used. | | duration | number | No | Animation duration, in ms.<br>Default value: **1000**<br>Unit: ms<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>- The maximum animation duration on an ArkTS widget is 1000 ms.<br>- A value less than 1 evaluates to the value **0**.<br>- If the value is of the floating point type, the value is rounded down. If the value is 1.2, the value **1** is used.|
| tempo | number | No | Animation playback speed. A greater value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**| | tempo | number | No | Animation playback speed. A larger value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**<br>**NOTE**<br>A value less than 1 evaluates to the value **1**.|
| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve<sup>9+</sup> | No | Animation curve.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets. | | curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve<sup>9+</sup> | No | Animation curve. The default curve is linear.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets.|
| delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0** | | delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0**<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 1 evaluates to the value **0**. If the value is of the floating point type, the value is rounded down. If the value is 1.2, the value **1** is used.|
| iterations | number | No | Number of times that the animation is played. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**| | iterations | number | No | Number of times that the animation is played.<br>Default value: **1**<br>Value range: [-1, +∞)<br>**NOTE**<br>The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that no animation is applied.|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.| | playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.|
| onFinish | () => void | No | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.| | onFinish | () => void | No | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This callback is not invoked when **iterations** is set to **-1**.|
## Example ## Example
......
...@@ -237,8 +237,8 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -237,8 +237,8 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Description | | Name | Description |
| ------ | -------------------------------------------------- | | ------ | -------------------------------------------------- |
| All | The transition takes effect in all scenarios.| | All | The transition takes effect in all scenarios.|
| Insert | The transition takes effect when a component is inserted. | | Insert | The transition takes effect when a component is inserted or displayed.|
| Delete | The transition takes effect when a component is deleted. | | Delete | The transition takes effect when a component is deleted or hidden.|
## RelateType ## RelateType
...@@ -307,12 +307,12 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -307,12 +307,12 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Description | | Name | Description |
| -------- | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ |
| Auto | The default configuration in the flex container is used. | | Auto | The default configuration of the flex container is used. |
| Start | The elements are in the flex container, top-aligned in the cross-axis direction. | | Start | The items in the flex container are aligned with the cross-start edge. |
| Center | The elements are in the flex container, centered in the cross-axis direction. | | Center | The items in the flex container are centered along the cross axis. |
| End | The elements are in the flex container, bottom-aligned in the cross-axis direction. | | End | The items in the flex container are aligned with the cross-end edge. |
| Stretch | The elements are in the flex container, stretched and padded in the cross-axis direction. If the size is not set, the elements are stretched to the container size.| | Stretch | The items in the flex container are stretched and padded along the cross axis. If the flex container has the **Wrap** attribute set to **FlexWrap.Wrap** or **FlexWrap.WrapReverse**, the items are stretched to the cross size of the widest element on the current row or column. In other cases, the items with no size set are stretched to the container size.|
| Baseline | The elements are in the flex container, text baseline aligned in the cross-axis direction. | | Baseline | The items in the flex container are aligned in such a manner that their text baselines are aligned along the cross axis. |
## FlexDirection ## FlexDirection
...@@ -520,30 +520,30 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -520,30 +520,30 @@ Since API version 9, this API is supported in ArkTS widgets.
This API is supported in ArkTS widgets. This API is supported in ArkTS widgets.
| Name| Description| | Name| Description|
| ------- | ---------- | | ------- | ---------- |
| Thin | Thin material. | | Thin | Thin material. |
| Regular | Regular material. | | Regular | Regular material. |
| Thick | Thick material. | | Thick | Thick material. |
| BackgroundThin | Material that creates the minimum depth of field effect.| | BackgroundThin | Material that creates the minimum depth of field effect.|
| BackgroundRegular | Material that creates a medium shallow depth of field effect.| | BackgroundRegular | Material that creates a medium shallow depth of field effect.|
| BackgroundThick | Material that creates a high shallow depth of field effect.| | BackgroundThick | Material that creates a high shallow depth of field effect.|
| BackgroundUltraThick | Material that creates the maximum depth of field effect.| | BackgroundUltraThick | Material that creates the maximum depth of field effect.|
## ThemeColorMode<sup>10+</sup> ## ThemeColorMode<sup>10+</sup>
| Name | Description | | Name | Description |
| ------- | ---------- | | ------- | ---------- |
| System | Following the system color mode.| | System | Following the system color mode.|
| Light | Light color mode.| | Light | Light color mode.|
| Dark | Dark color mode.| | Dark | Dark color mode.|
## AdaptiveColor<sup>10+</sup> ## AdaptiveColor<sup>10+</sup>
| Name | Description | | Name | Description |
| ------- | ----------- | | ------- | ----------- |
| Default | Adaptive color mode is not used. The default color is used as the mask color.| | Default | Adaptive color mode is not used. The default color is used as the mask color.|
| Average | Adaptive color mode is used. The average color value of the color picking area is used as the mask color.| | Average | Adaptive color mode is used. The average color value of the color picking area is used as the mask color.|
## TextHeightAdaptivePolicy<sup>10+</sup> ## TextHeightAdaptivePolicy<sup>10+</sup>
......
...@@ -47,7 +47,7 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -47,7 +47,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| stateEffect | boolean | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.| | stateEffect | boolean | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.|
| labelStyle<sup>10+</sup> | [LabelStyle](#labelstyle10) | Label style of the button.| | labelStyle<sup>10+</sup> | [LabelStyle](#labelstyle10) | Label style of the button.|
## ButtonType enums ## ButtonType
Since API version 9, this API is supported in ArkTS widgets. Since API version 9, this API is supported in ArkTS widgets.
......
...@@ -17,7 +17,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb ...@@ -17,7 +17,7 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**| | fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**<br>Value range: 1 to 10<br>**NOTE**<br>If the value is less than 1 or is not set, the default value is used.|
| direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**| | direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**|
| distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5**<br>**NOTE**<br>If a pan gesture and [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.| | distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5**<br>**NOTE**<br>If a pan gesture and [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
......
# TapGesture # TapGesture
**TapGesture** is used to trigger a tap gesture with one or more taps. **TapGesture** is used to trigger a tap gesture with one, two, or more taps.
> **NOTE** > **NOTE**
> >
...@@ -15,8 +15,8 @@ TapGesture(value?: { count?: number, fingers?: number }) ...@@ -15,8 +15,8 @@ TapGesture(value?: { count?: number, fingers?: number })
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| count | number | No| Number of consecutive taps. If this parameter is set to a value less than **1**, the default value will be used.<br>Default value: **1**<br>> **NOTE**<br>> If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.| | count | number | No| Number of consecutive taps. If the value is less than 1 or is not set, the default value is used.<br>Default value: **1**<br>**NOTE**<br>If multi-tap is configured, the timeout interval between a lift and the next tap is 300 ms.|
| fingers | number | No| Number of fingers required to trigger a tap. The value ranges from 1 to 10.<br>Default value: **1**<br>> **NOTE**<br>> 1. When multi-finger is configured, the gesture will fail to be recognized if the number of fingers used for tapping is less than the configured number within 300 ms of tapping by the first finger.<br>> 2. The gesture will fail to be recognized if the number of fingers used for tapping exceeds the configured number.| | fingers | number | No| Number of fingers required to trigger a tap. The value ranges from 1 to 10. If the value is less than 1 or is not set, the default value is used.<br>Default value: **1**<br>**NOTE**<br>1. When multi-finger is configured, if the number of fingers used for tap does not reach the specified number within 300 ms after the first finger is tapped, the gesture fails to be recognized.<br>2. Gesture recognition fails if the number of fingers used for tap exceeds the configured number.|
## Events ## Events
......
...@@ -126,7 +126,11 @@ A grid supports a maximum of six breakpoints: xs, sm, md, lg, xl and xxl, whose ...@@ -126,7 +126,11 @@ A grid supports a maximum of six breakpoints: xs, sm, md, lg, xl and xxl, whose
## Attributes ## Attributes
The [universal attributes](ts-universal-attributes-size.md) are supported. In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------- |
| alignItems<sup>10+</sup> | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the **\<GridCol>** cross axis.<br>Default value: **ItemAlign.Start**<br>**NOTE**<br>The alignment mode of the **\<GridCol>** component can also be set using **alignSelf([ItemAlign](ts-appendix-enums.md#itemalign))**. If both of the preceding methods are used, the setting of **alignSelf(ItemAlign)** prevails.<br>Since API version 10, this API is supported in ArkTS widgets.|
## Events ## Events
......
...@@ -183,7 +183,7 @@ struct ListLanesExample { ...@@ -183,7 +183,7 @@ struct ListLanesExample {
.lanes({ minLength: 40, maxLength: 40 }) .lanes({ minLength: 40, maxLength: 40 })
.alignListItem(this.alignListItem) .alignListItem(this.alignListItem)
Button("Change alignListItem: "+ this.alignListItem).onClick(() => { Button("Click to modify alignListItem: "+ this.alignListItem).onClick(() => {
if (this.alignListItem == ListItemAlign.Start) { if (this.alignListItem == ListItemAlign.Start) {
this.alignListItem = ListItemAlign.Center this.alignListItem = ListItemAlign.Center
} else if (this.alignListItem == ListItemAlign.Center) { } else if (this.alignListItem == ListItemAlign.Center) {
......
...@@ -22,7 +22,7 @@ SideBarContainer( type?: SideBarContainerType ) ...@@ -22,7 +22,7 @@ SideBarContainer( type?: SideBarContainerType )
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | SideBarContainerType | No| Display type of the sidebar.<br>Default value: **SideBarContainerType.Embed**| | type | SideBarContainerType | No| Display type of the sidebar.<br>Default value: **SideBarContainerType.Embed**|
## SideBarContainerType enums ## SideBarContainerType
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
......
...@@ -11,7 +11,7 @@ The motion path animation is used to animate a component along a custom path. ...@@ -11,7 +11,7 @@ The motion path animation is used to animate a component along a custom path.
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| motionPath | {<br>path: string,<br>from?: number,<br>to?: number,<br>rotatable?: boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x start.y L50 50 Lend.x end.y Z'<br>For more information, see [Path Drawing](../../ui/ui-js-components-svg-path.md).| {<br>'',<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component.<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path. The default value is **0.0**.<br>- **to**: end point of the motion path. The default value is **1.0**.<br>- **rotatable**: whether to rotate along the path.| | motionPath | {<br>path:&nbsp;string,<br>from?:&nbsp;number,<br>to?:&nbsp;number,<br>rotatable?:&nbsp;boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x&nbsp;start.y&nbsp;L50&nbsp;50&nbsp;Lend.x&nbsp;end.y&nbsp;Z'<br>For more information, see [Path Drawing](../../ui/ui-js-components-svg-path.md).| {<br>'',<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component.<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path.<br>Default value: **0.0**<br>Value range: [0, 1]<br>A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.<br>- **to**: end point of the motion path.<br>Default value: **1.0**<br>Value range: [0, 1]<br>A value less than 0 evaluates to the value **0**. A value larger than 1 evaluates to the value **1**.<br>- **rotatable**: whether to rotate along the path. |
## Example ## Example
......
# Page Transition # Page Transition
The page transition navigates users between pages. You can customize page transitions by configuring the page entrance and exit components in the global **pageTransition** API. The page transition navigates users between pages. You can customize page transitions by configuring the page entrance and exit components in the **pageTransition** API.
> **NOTE** > **NOTE**
> >
...@@ -8,12 +8,12 @@ The page transition navigates users between pages. You can customize page transi ...@@ -8,12 +8,12 @@ The page transition navigates users between pages. You can customize page transi
> >
| Name | Parameter | Description | | Name | Parameter | Mandatory| Description |
| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| PageTransitionEnter | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | Page entrance animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**Note**: If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.| | PageTransitionEnter | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | No | Page entrance animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**NOTE**<br>If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration.<br>Unit: ms<br>- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".<br>Default value: **Curve.Linear**<br>- **delay**: animation delay.<br>Default value: **0**<br>Unit: ms|
| PageTransitionExit | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | Page exit animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**Note**: If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.| | PageTransitionExit | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | No | Page exit animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**NOTE**<br>If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.<br>Default value: **Curve.Linear**<br>- **delay**: animation delay.<br>Default value: **0**<br>Unit: ms|
## RouteType enums ## RouteType
| Name| Description | | Name| Description |
| ---- | ------------------------------------------------------------ | | ---- | ------------------------------------------------------------ |
...@@ -28,7 +28,7 @@ The page transition navigates users between pages. You can customize page transi ...@@ -28,7 +28,7 @@ The page transition navigates users between pages. You can customize page transi
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| slide | [SlideEffect](#slideeffect) | No | Slide effect during page transition.<br>Default value: **SlideEffect.Right**| | slide | [SlideEffect](#slideeffect) | No | Slide effect during page transition.<br>Default value: **SlideEffect.Right**|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.<br>- **x**: translation distance along the x-axis.<br>- **y**: translation distance along the y-axis.<br>- **z**: translation distance along the y-axis.| | translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.<br>- **x**: translation distance along the x-axis.<br>- **y**: translation distance along the y-axis.<br>- **z**: translation distance along the y-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.<br>- **x**: scale ratio along the x-axis.<br>- **y**: scale ratio along the y-axis.<br>- **z**: scale ratio along the z-axis.<br>- **centerX** and **centerY**: scale center point.<br>- If the center point is 0, it refers to the upper left corner of the component.<br>| | scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.<br>- **x**: scale ratio along the x-axis.<br>- **y**: scale ratio along the y-axis.<br>- **z**: scale ratio along the z-axis.<br>- **centerX** and **centerY**: scale center point.<br>- If the center point is 0, it refers to the upper left corner of the component. |
| opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.<br>Default value: **1**| | opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.<br>Default value: **1**|
## SlideEffect ## SlideEffect
...@@ -45,8 +45,8 @@ The page transition navigates users between pages. You can customize page transi ...@@ -45,8 +45,8 @@ The page transition navigates users between pages. You can customize page transi
| Name | Description | | Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| onEnter(event: (type?: RouteType, progress?: number) =&gt; void) | The callback input parameter is the normalized progress of the current entrance animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress.| | onEnter(event: (type?: RouteType, progress?: number) =&gt; void) | Invoked once every animation frame until the entrance animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current entrance animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress. |
| onExit(event: (type?: RouteType, progress?: number) =&gt; void) | The callback input parameter is the normalized progress of the current exit animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress.| | onExit(event: (type?: RouteType, progress?: number) =&gt; void) | Invoked once every animation frame until the exit animation ends, when the value of **progress** changes from 0 to 1. The input parameter is the normalized progress of the current exit animation. The value range is 0–1.<br>- **type**: route type.<br>- **progress**: current progress. |
## Example ## Example
......
...@@ -12,17 +12,17 @@ Configure the component transition animations for when a component is inserted o ...@@ -12,17 +12,17 @@ Configure the component transition animations for when a component is inserted o
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| transition | TransitionOptions | Transition parameters, which are all optional. For details, see **TransitionOptions**.| | transition | TransitionOptions | Transition effects when the component is inserted, displayed, deleted, or hidden.<br>If no transition effect is set, an opacity transition from 0 to 1 is applied. <br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>Transition parameters, which are all optional. For details, see **TransitionOptions**.|
## TransitionOptions ## TransitionOptions
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.<br>Default value: **TransitionType.All**<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.| | type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.<br>Default value: **TransitionType.All**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.|
| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Default value: **1**| | opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Default value: **1**<br>Value range: [0, 1]<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. A value greater than 1 evaluates to the value **1**.|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.| | translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.<br>Since API version 9, this API is supported in ArkTS widgets.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>| | scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.| | rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
## Example ## Example
......
# Transition of Shared Elements # Shared Element Transition
Shared element transition can be used for transition between pages, for example, transition from an image on the current page to the next page. A shared element transition is a transition animation applied to a component that is present on two pages. This component is called the shared element and can be set in the **sharedTransition** attribute.
> **NOTE** > **NOTE**
> >
...@@ -10,14 +10,14 @@ Shared element transition can be used for transition between pages, for example, ...@@ -10,14 +10,14 @@ Shared element transition can be used for transition between pages, for example,
## Attributes ## Attributes
| Name | Parameters | Description | | Name | Parameter | Description |
| ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| sharedTransition | id: string,<br>{<br> duration?: number,<br> curve?: Curve \| string,<br> delay?: number,<br> motionPath?: <br>{<br> path: string,<br> form?: number,<br> to?: number,<br> rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: animation duration, in ms. The default duration is 1000 ms.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: Delay of animation playback, in ms. By default, the playback is not delayed.<br>- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.| | sharedTransition | id: string,<br>{<br> duration?: number,<br> curve?: Curve \| string,<br> delay?: number,<br> motionPath?: <br>{<br> path: string,<br> form?: number,<br> to?: number,<br> rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: animation duration.<br>Default value: **1000**<br>Unit: ms<br>Value range: [0, +∞)<br>The value **0** indicates that no animation is applied. A value less than 0 evaluates to the value **0**.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: animation delay.<br>Default value: **0**<br>Unit: ms<br>Value range: [0, +∞)<br>A value less than 0 evaluates to the value **0**.<br>- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.|
## Example ## Example
The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image. This example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image.
```ts ```ts
// xxx.ets // xxx.ets
......
...@@ -14,7 +14,7 @@ The location attributes set the alignment mode, layout direction, and position o ...@@ -14,7 +14,7 @@ The location attributes set the alignment mode, layout direction, and position o
| -------- | -------- | -------- | | -------- | -------- | -------- |
| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.<br>Default value: **Alignment.Center**<br>Since API version 9, this API is supported in ArkTS widgets.| | align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.<br>Default value: **Alignment.Center**<br>Since API version 9, this API is supported in ArkTS widgets.|
| direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.<br>Default value: **Direction.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.<br>Default value: **Direction.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.|
| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Since API version 9, this API is supported in ArkTS widgets.| | position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>This attribute is applicable to scenarios where the component is fixed at a position in the parent container, for example, where it is pinned to top or floating above the UI.<br>Since API version 9, this API is supported in ArkTS widgets.|
| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>}<br>Since API version 9, this API is supported in ArkTS widgets.| | markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>}<br>Since API version 9, this API is supported in ArkTS widgets.|
| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>}<br>Since API version 9, this API is supported in ArkTS widgets.| | offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>}<br>Since API version 9, this API is supported in ArkTS widgets.|
| alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container. This attribute is valid only when the container is [\<RelativeContainer>](ts-container-relativecontainer.md).<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.| | alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container. This attribute is valid only when the container is [\<RelativeContainer>](ts-container-relativecontainer.md).<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>This API is supported in ArkTS widgets.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.|
......
...@@ -26,7 +26,15 @@ You can bind a popup to a component, specifying its content, interaction logic, ...@@ -26,7 +26,15 @@ You can bind a popup to a component, specifying its content, interaction logic,
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup. <br>When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default. <br/>When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default. <br/>When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. | | arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup. <br>When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default. <br/>When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default. <br/>When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. |
| showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow. <br/>Default value: **false** | | showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow. <br/>Default value: **false** |
| mask<sup>10+</sup> | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No | Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.| | mask<sup>10+</sup> | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No | Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.|
| messageOptions<sup>10+</sup> | [PopupMessageOptions](#popupmessageoptions10) | No | Parameters of the popup message.|
| targetSpace<sup>10+</sup> | [Length](ts-types.md#length) | No | Space between the popup and the target.|
## PopupMessageOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------ | ---- | ---------------------- |
| textColor | [ResourceColor](ts-types.md#resourcecolor) | No | Text color of the popup message.|
| font | [Font](ts-types.md#Font) | No | Font attributes of the popup message.|
## CustomPopupOptions<sup>8+</sup> ## CustomPopupOptions<sup>8+</sup>
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -34,13 +42,13 @@ You can bind a popup to a component, specifying its content, interaction logic, ...@@ -34,13 +42,13 @@ You can bind a popup to a component, specifying its content, interaction logic,
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | | builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom** | | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.<br>Default value: **Placement.Bottom** |
| popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. |
| enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the position set for the popup is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** but the popup height is less than twice the arrow width (64 vp), the arrow will not be displayed.<br>Default value: **true**| | enableArrow | boolean | No | Whether to display an arrow.<br>Since API version 9, if the position set for the popup is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left**, but the popup height (80 vp) is less than the sum of the arrow width (32 vp) and diameter of popup rounded corner (48 vp), the arrow will not be displayed.<br>Default value: **true**|
| autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.<br>Default value: **true** | | autoCancel | boolean | No | Whether to automatically close the popup when an operation is performed on the page.<br>Default value: **true** |
| onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event.<br>**isVisible**: whether the popup is visible. | | onStateChange | (event: { isVisible: boolean }) =&gt; void | No | Callback for the popup status change event.<br>**isVisible**: whether the popup is visible. |
| arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup. <br/>When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default. <br/>When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default. <br/>When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. | | arrowOffset<sup>9+</sup> | [Length](ts-types.md#length) | No | Offset of the popup arrow relative to the popup. <br/>When the arrow is at the top or bottom of the popup: The value **0** indicates that the arrow is located on the leftmost, and any other value indicates the distance from the arrow to the leftmost; the arrow is centered by default. <br/>When the arrow is on the left or right side of the popup: The value indicates the distance from the arrow to the top; the arrow is centered by default. <br/>When the popup is displayed on either edge of the screen, it will automatically deviate leftward or rightward to stay within the safe area. When the value is **0**, the arrow always points to the bound component. |
| showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow.<br/>Default value: **false** | | showInSubWindow<sup>9+</sup> | boolean | No | Whether to show the popup in the subwindow.<br/>Default value: **false** |
| mask<sup>10+</sup> | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No| Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.| | mask<sup>10+</sup> | boolean \| [ResourceColor](ts-types.md#resourcecolor) | No| Whether to apply a mask to the popup. The value **true** means to apply a transparent mask to the popup, **false** means not to apply a mask to the popup, and a color value means to apply a mask in the corresponding color to the popup.|
| targetSpace<sup>10+</sup> | [Length](ts-types.md#length) | No| Space between the popup and the target.|
## Example ## Example
```ts ```ts
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
> >
> This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md). > This topic describes only module-specific error codes. For details about universal error codes, see [Universal Error Codes](errorcode-universal.md).
## 17100001 WebviewController Not Associated with a Web Component ## 17100001 WebviewController Not Associated with a Web Component
**Error Message** **Error Message**
...@@ -229,3 +228,41 @@ The related JS database API is not used. ...@@ -229,3 +228,41 @@ The related JS database API is not used.
1. Check whether the JS database API is used. 1. Check whether the JS database API is used.
2. If the JS database API is used, find out the failure cause, for example, check whether **databaseAccess** is enabled. 2. If the JS database API is used, find out the failure cause, for example, check whether **databaseAccess** is enabled.
## 17100013 Memory Allocation Failure
**Error Message**
New failed, out of memeory.
**Description**
Memory allocation failed due to insufficient memory.
**Possible Causes**
The data to send is too large.
**Solution**
Check the length of the data to be sent.
## 17100014 Type and Value Mismatch
**Error Message**
The type does not match with the value of the message.
**Description**
The type and value of the message do not match.
**Possible Causes**
The value of the obtained message does not match the type of the message.
**Solution**
Call the API based on the message type to obtain the message value. For example, if the type is **BOOLEAN**, call the **GetBoolean** API to obtain the Boolean value.
...@@ -5,12 +5,12 @@ ...@@ -5,12 +5,12 @@
The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class. The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class.
**Table 1** Major APIs in reminderAgentManager **Table 1** Major APIs in reminderAgentManager
| API | Description | | API | Description |
| ---------------------------------------- | ---------------------------------------- | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application<br>and 2000 for the entire system.| | publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| | cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) |
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. | | getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. |
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. | | cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. |
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. | | addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. |
...@@ -19,7 +19,7 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -19,7 +19,7 @@ The agent-powered reminder feature provides APIs for publishing background remin
## How to Develop ## How to Develop
1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. [Enable the notification feature](../notification/notification-enable.md). 2. [Enable the notification feature](../notification/notification-enable.md).
...@@ -95,7 +95,7 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -95,7 +95,7 @@ The agent-powered reminder feature provides APIs for publishing background remin
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 5, // Reminder snooze interval, in seconds. timeInterval: 5, // Reminder snooze interval, in seconds.
title: 'this is title', // Reminder title. title: 'this is title', // Reminder title.
content:'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed. snoozeContent: 'remind later', // Content to be displayed when the reminder is snoozed.
notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one. notificationId: 100, // Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.
......
...@@ -23,11 +23,11 @@ The following table lists the licenses of the third-party open source software u ...@@ -23,11 +23,11 @@ The following table lists the licenses of the third-party open source software u
| third_party_jerryscript | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.| | third_party_jerryscript | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.|
| third_party_libjpeg | Libjpeg License (JPEG License) | The license does not require any product that uses such a repository to open their code.| | third_party_libjpeg | Libjpeg License (JPEG License) | The license does not require any product that uses such a repository to open their code.|
| third_party_libpng | libpng license | The license does not require any product that uses such a repository to open their code.| | third_party_libpng | libpng license | The license does not require any product that uses such a repository to open their code.|
| third_party_Linux_Kernel | GPL V2.0+EXCEPTION | The third\_party\_Linux\_Kernel repository contains two modules, jffs2 and scripts. <br>1. The jffs2 module is introduced to be compatible with Journalling Flash File System version 2 (JFFS2). This module uses the GNU General Public License version 2 (GPLv2) and EXCEPTION licenses, which are available at https://gitee.com/openharmony/third_party_Linux_Kernel/blob/master/fs/jffs2/LICENCE.<br>OpenHarmony compiles the jffs2 module and uses links in a way that meets the EXCEPTION requirements. The use will not cause other code to be affected by GPLv2. <br>2. The scripts module is an independent compiler. It is only used to generate the conf and mconf tools during compilation, and its code is not packaged into kernel\_liteos\_a. Therefore, it will not cause kernel_\liteos\_a to be affected by the GPL.| | third_party_Linux_Kernel | GPL V2.0+EXCEPTION | The third\_party\_Linux\_Kernel repository contains two modules, jffs2 and scripts.<br>(1) The jffs2 module is introduced to be compatible with Journalling Flash File System version 2 (JFFS2). This module uses the GNU General Public License version 2 (GPLv2) and EXCEPTION licenses, which are available at https://gitee.com/openharmony/third_party_Linux_Kernel/blob/master/fs/jffs2/LICENCE.<br>OpenHarmony compiles the jffs2 module and uses links in a way that meets the EXCEPTION requirements. The use will not cause other code to be affected by GPLv2.<br>(2) The scripts module is an independent compiler. It is only used to generate the conf and mconf tools during compilation, and its code is not packaged into kernel\_liteos\_a. Therefore, it will not cause kernel_\liteos\_a to be affected by the GPL. |
| third_party_ltp | GPL V2.0 | third\_party\_ltp is an independent process used to test kernel\_liteos\_a APIs across processes. It will not cause kernel_\liteos\_a to be affected by the GPL.| | third_party_ltp | GPL V2.0 | third\_party\_ltp is an independent process used to test kernel\_liteos\_a APIs across processes. It will not cause kernel_\liteos\_a to be affected by the GPL. |
| third_party_lwip | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.| | third_party_lwip | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.|
| third_party_mbedtls | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.| | third_party_mbedtls | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.|
| third_party_mtd_utils | GPL V2.0 | third\_party\_mtd\_utils is used to compile and generate a tool that is used for packaging rootfs and userfs images in JFFS2 format. Its code is not packaged into kernel\_liteos\_a. It will not cause kernel_\liteos\_a to be affected by the GPL.| | third_party_mtd_utils | GPL V2.0 | third\_party\_mtd\_utils is used to compile and generate a tool that is used for packaging rootfs and userfs images in JFFS2 format. Its code is not packaged into kernel\_liteos\_a. It will not cause kernel_\liteos\_a to be affected by the GPL. |
| third_party_musl | BSD 2-Clause License | The license does not require any product that uses such a repository to open their code.| | third_party_musl | BSD 2-Clause License | The license does not require any product that uses such a repository to open their code.|
| third_party_NuttX | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.| | third_party_NuttX | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.|
| third_party_openssl | OpenSSL License and Original SSLeay License | The license does not require any product that uses such a repository to open their code.| | third_party_openssl | OpenSSL License and Original SSLeay License | The license does not require any product that uses such a repository to open their code.|
...@@ -74,7 +74,7 @@ The following table lists the licenses of the third-party open source software u ...@@ -74,7 +74,7 @@ The following table lists the licenses of the third-party open source software u
| third_party_mingw-w64 | Zope Public License V2.1 | The license does not require any product that uses such a repository to open their code. Some build scripts use Autoconf exception to GPL 2.0 or later. The use meets its requirements and will not cause OpenHarmony processes to be affected by the GPL. Some header files use LGPL-2.1+ and are invoked through a dynamic link. The use of these files will not cause OpenHarmony processes to be affected by the GPL.| | third_party_mingw-w64 | Zope Public License V2.1 | The license does not require any product that uses such a repository to open their code. Some build scripts use Autoconf exception to GPL 2.0 or later. The use meets its requirements and will not cause OpenHarmony processes to be affected by the GPL. Some header files use LGPL-2.1+ and are invoked through a dynamic link. The use of these files will not cause OpenHarmony processes to be affected by the GPL.|
| third_party_mtdev | MIT License | The license does not require any product that uses such a repository to open their code.| | third_party_mtdev | MIT License | The license does not require any product that uses such a repository to open their code.|
| third_party_ninja | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.| | third_party_ninja | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.|
| third_party_node | Apache License V2.0<br>Artistic License 2.0<br>BSD 2-Clause License<br>BSD 3-Clause License<br>ICU License<br>MIT License<br>OpenSSL License<br>Public Domain<br>SSLeay License<br>UNICODE INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE<br>c-ares license<br>zlib/libpng License<br> | The components corresponding to Artistic License 2.0 contained in the software is not used in OpenHarmony. Other licenses do not require the products that use such a repository to open their code.| | third_party_node | Apache License V2.0<br>Artistic License 2.0<br>BSD 2-Clause License<br>BSD 3-Clause License<br>ICU License<br>MIT License<br>OpenSSL License<br>Public Domain<br>SSLeay License<br>UNICODE INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE<br>c-ares license<br>zlib/libpng License<br>| The components corresponding to Artistic License 2.0 contained in the software is not used in OpenHarmony. Other licenses do not require the products that use such a repository to open their code.|
| third_party_objenesis | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.| | third_party_objenesis | Apache License V2.0 | The license does not require any product that uses such a repository to open their code.|
| third_party_pixman | MIT license | The license does not require any product that uses such a repository to open their code.| | third_party_pixman | MIT license | The license does not require any product that uses such a repository to open their code.|
| third_party_protobuf | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.| | third_party_protobuf | BSD 3-Clause License | The license does not require any product that uses such a repository to open their code.|
...@@ -90,8 +90,8 @@ The following table lists the licenses of the third-party open source software u ...@@ -90,8 +90,8 @@ The following table lists the licenses of the third-party open source software u
| third_party_mksh | MirOS License | The license does not require any product that uses such a repository to open their code.| | third_party_mksh | MirOS License | The license does not require any product that uses such a repository to open their code.|
| third_party_toybox | Public Domain License | The license does not require any product that uses such a repository to open their code.| | third_party_toybox | Public Domain License | The license does not require any product that uses such a repository to open their code.|
| third_party_optimized_routines | MIT License | The license does not require any product that uses such a repository to open their code.| | third_party_optimized_routines | MIT License | The license does not require any product that uses such a repository to open their code.|
| third_party_libsnd | LGPL v2.1 | The license does not require any product that uses such a repository to open their code. Some test code uses GPL-3.0-or-later, and some uses GPL-2.0-or-later.| | third_party_libsnd | LGPL v2.1 | third\_party_\libsnd is called through a dynamic link. It will not cause OpenHarmony processes to be affected by the LGPL. Some test code uses GPL-3.0-or-later, and some uses GPL-2.0-or-later.|
| third_party_pulseaudio | LGPL v2.1 | The license does not require any product that uses such a repository to open their code.| | third_party_pulseaudio | LGPL v2.1 | third\_party_\pulseaudio is called through a dynamic link. It will not cause OpenHarmony processes to be affected by the LGPL.|
| third_party_ffmpeg | LGPL v2.1 | OpenHarmony uses the ffmpeg repository in the LGPL through a dynamic link. The use will not cause other code to be affected by the LGPL.| | third_party_ffmpeg | LGPL v2.1 | OpenHarmony uses the ffmpeg repository in the LGPL through a dynamic link. The use will not cause other code to be affected by the LGPL.|
| third_party_quickjs | MIT licence | The license does not require any product that uses such a repository to open their code.| | third_party_quickjs | MIT licence | The license does not require any product that uses such a repository to open their code.|
| third_party_icu | BSD 3-Clause License, ICU License, UNICODE INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE | The license does not require any product that uses such a repository to open their code.| | third_party_icu | BSD 3-Clause License, ICU License, UNICODE INC. LICENSE AGREEMENT - DATA FILES AND SOFTWARE | The license does not require any product that uses such a repository to open their code.|
......
...@@ -38,7 +38,7 @@ foundation/bundlemanager/bundle_framework ...@@ -38,7 +38,7 @@ foundation/bundlemanager/bundle_framework
│ ├── js # JS APIs │ ├── js # JS APIs
│ └── native # C/C++ APIs │ └── native # C/C++ APIs
├── services # Framework code of the bundle management service ├── services # Framework code of the bundle management service
── test # Testing ── test # Testing
``` ```
...@@ -179,6 +179,7 @@ bm get -u ...@@ -179,6 +179,7 @@ bm get -u
Bundle Management Subsystem Bundle Management Subsystem
[**appexecfwk_standard**](https://gitee.com/openharmony/appexecfwk_standard) [**bundlemanager_bundle_framework**](https://gitee.com/openharmony/bundlemanager_bundle_framework)
[**bundlemanager_bundle_framework_lite**](https://gitee.com/openharmony/bundlemanager_bundle_framework_lite)
[developtools_packing_tool](https://gitee.com/openharmony/developtools_packing_tool) [developtools_packing_tool](https://gitee.com/openharmony/developtools_packing_tool)
...@@ -123,7 +123,7 @@ For details, see the README and **test** directory of each repository. ...@@ -123,7 +123,7 @@ For details, see the README and **test** directory of each repository.
**Graphics subsystem** **Graphics subsystem**
- [**graphic_graphic_2d**](https://gitee.com/abbuu_openharmony/graphic_graphic_2d) - [**graphic_graphic_2d**](https://gitee.com/openharmony/graphic_graphic_2d)
- [arkui_ace_engine](https://gitee.com/openharmony/arkui_ace_engine) - [arkui_ace_engine](https://gitee.com/openharmony/arkui_ace_engine)
- [ability_ability_runtime](https://gitee.com/openharmony/ability_ability_runtime) - [ability_ability_runtime](https://gitee.com/openharmony/ability_ability_runtime)
- [multimedia_player_framework](https://gitee.com/openharmony/multimedia_player_framework) - [multimedia_player_framework](https://gitee.com/openharmony/multimedia_player_framework)
......
...@@ -231,3 +231,10 @@ If the **distroFilter** tag is used, an error is reported during compilation on ...@@ -231,3 +231,10 @@ If the **distroFilter** tag is used, an error is reported during compilation on
**Adaptation Guide**<br> **Adaptation Guide**<br>
Replace **distroFilter** with **distributionFilter** in the configuration file. Replace **distroFilter** with **distributionFilter** in the configuration file.
## cl.bundlemanager.20 Changed standard of launchType to multiton in the module.json Configuration File
The **standard** mode of the [launchType](../../../application-dev/quick-start/module-configuration-file.md) tag in the **module.json** file is changed to **multiton**.
**Adaptation Guide**<br>
Replace **standard** of **launchType** to **multiton** in the configuration file.
# Web Subsystem Changelog
Compared with earlier versions, OpenHarmony 4.0.6.1 has the following API changes in its web subsystem:
## cl.web.1 Parameters in createWebMessagePorts
Added an optional parameter to the **WebMessagePort** API to accommodate more data types.
**Change Impact**
None (The added parameter is optional, and the API is forward compatible.)
**Key API/Component Changes**
- Involved APIs:
createWebMessagePorts(): Array\<WebMessagePort>;
- Before change:
```ts
createWebMessagePorts(): Array<WebMessagePort>;
```
- After change:
```ts
createWebMessagePorts(isExtentionType?: boolean): Array<WebMessagePort>;
```
**Adaptation Guide**
N/A
...@@ -25,49 +25,31 @@ Beta is a branch pulled from Master in the OpenHarmony community irregularly. Th ...@@ -25,49 +25,31 @@ Beta is a branch pulled from Master in the OpenHarmony community irregularly. Th
A tag version is a stable and reliable version created by applying patches to an LTS or a Release branch, with the purpose of fixing individual bugs, security vulnerabilities, and other necessary adaptation modifications. A tag version is a stable and reliable version created by applying patches to an LTS or a Release branch, with the purpose of fixing individual bugs, security vulnerabilities, and other necessary adaptation modifications.
### Commands for Downloading Branches The release versions are available in the [**Release Notes** folder](../release-notes).
| Branch | Download Command (repo + https) | Download Command (repo + ssh) | ## Lifecycle Policies
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 1.0.1-Release | repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony_1.0.1_release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
| 3.0-LTS | repo init -u https://gitee.com/openharmony/manifest.git -b OpenHarmony-3.0-LTS --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.0-LTS --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
| 3.1-Release | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
## Maintenance Policies
### Lifecycle Policies
OpenHarmony provides lifecycle management services for LTS and Release branches as follows:
#### Release -> Stop proactive maintenance
​ The Release SIG periodically makes and maintains tag version plans to resolve individual bugs, security vulnerabilities, and other major issues to ensure continuously stable and available branches.
#### Stop proactive maintenance -> Stop maintenance The OpenHarmony community provides maintenance and technical support for Release and LTS branches based on the OpenHarmony Version Lifecycle Management. The OpenHarmony community provides maintenance and technical support based on the *OpenHarmony Version Lifecycle Management*.
​ The Release SIG no longer proactively plans and releases tag versions. It only fixes security vulnerabilities and major defects in corresponding branches. ### Maintenance Schedule
### LTS and Release Maintenance Policies
For an LTS branch, the OpenHarmony community provides 2-year proactive maintenance and 1.5-year passive maintenance since its release.
For a Release branch, the OpenHarmony community provides 1-year proactive maintenance and 1-year passive maintenance since its release. The following table lists the maintenance schedule of the LTS and Release branches that have been released in the OpenHarmony community.
### Branch Merge Policies | Branch Name | Branch Type| Release Date | End of Proactive Maintenance| End of Maintenance |
| ------------- | -------- | --------- | ------------ | --------- |
| 1.0.1-Release | Release | 2021-03-30| 2022-03-30 | 2023-03-30|
| 3.0-LTS | LTS | 2021-09-30| 2023-09-30 | 2025-03-30|
| 3.1-Release | Release | 2022-03-30| 2023-03-30 | 2024-03-30|
The Release SIG is responsible for lifecycle management of an LTS or a Release branch. During the maintenance period, the SIG accepts only code updates that resolve security vulnerabilities, ACTS issues, and other major issues. All code updates can be merged into the branch only after the related pull request has been approved by the [owner](https://gitee.com/openharmony/community/blob/master/zh/BRANCHOWNER). Run the following commands to download the source code of each branch:
### Maintenance Schedule | Branch | Download Command (repo + https) | Download Command (repo + ssh) |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 1.0.1-Release | repo init -u https://gitee.com/openharmony/manifest -b OpenHarmony_1.0.1_release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
| 3.0-LTS | repo init -u https://gitee.com/openharmony/manifest.git -b OpenHarmony-3.0-LTS --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.0-LTS --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
| 3.1-Release | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' | repo init -u git@gitee.com:openharmony/manifest.git -b OpenHarmony-3.1-Release -m default.xml --no-repo-verify<br>repo sync -c<br>repo forall -c 'git lfs pull' |
The following table lists the maintenance schedule of the LTS and Release branches that have been released in the OpenHarmony community.
| No. | Branch Name | Branch Type| Release Date | End of Proactive Maintenance| End of Maintenance |
| :--- | ------------- | :------- | :-------- | :----------- | :-------- |
| 1 | 1.0.1-Release | Release | 2021-03-30| 2022-03-30 | 2023-03-30|
| 2 | 3.0-LTS | LTS | 2021-09-30| 2023-09-30 | 2025-03-30|
| 3 | 3.1-Release | Release | 2022-03-30| 2023-03-30 | 2024-03-30|
### Version Plan ### Version Plan
......
...@@ -17,11 +17,37 @@ ...@@ -17,11 +17,37 @@
- ExtensionAbility组件 - ExtensionAbility组件
- [ExtensionAbility组件概述](extensionability-overview.md) - [ExtensionAbility组件概述](extensionability-overview.md)
- [ServiceExtensionAbility](serviceextensionability.md) - [ServiceExtensionAbility](serviceextensionability.md)
- [DataShareExtensionAbility(仅对系统应用开放)](datashareextensionability.md)
- [AccessibilityExtensionAbility](accessibilityextensionability.md) - [AccessibilityExtensionAbility](accessibilityextensionability.md)
- [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md) - [EnterpriseAdminExtensionAbility](enterprise-extensionAbility.md)
- [InputMethodExtensionAbility](inputmethodextentionability.md) - [InputMethodExtensionAbility](inputmethodextentionability.md)
- [WindowExtensionAbility](windowextensionability.md) - [WindowExtensionAbility](windowextensionability.md)
- [服务卡片开发指导](widget-development-stage.md) - 服务卡片开发指导(Stage模型)
- [服务卡片概述](service-widget-overview.md)
- 开发基于ArkTS UI的卡片
- [ArkTS卡片运行机制](arkts-ui-widget-working-principles.md)
- [ArkTS卡片相关模块](arkts-ui-widget-modules.md)
- ArkTS卡片开发指导
- [创建一个ArkTS卡片](arkts-ui-widget-creation.md)
- [配置卡片的配置文件](arkts-ui-widget-configuration.md)
- [卡片生命周期管理](arkts-ui-widget-lifecycle.md)
- 开发卡片页面
- [卡片页面能力说明](arkts-ui-widget-page-overview.md)
- [卡片使用动效能力](arkts-ui-widget-page-animation.md)
- [卡片使用自定义绘制能力](arkts-ui-widget-page-custom-drawing.md)
- 开发卡片事件
- [卡片事件能力说明](arkts-ui-widget-event-overview.md)
- [通过FormExtensionAbility刷新卡片内容](arkts-ui-widget-event-formextensionability.md)
- [通过UIAbility刷新卡片内容](arkts-ui-widget-event-uiability.md)
- [使用router事件跳转到指定页面](arkts-ui-widget-event-router.md)
- 卡片数据交互
- [卡片数据交互说明](arkts-ui-widget-interaction-overview.md)
- [定时刷新和定点刷新](arkts-ui-widget-update-by-time.md)
- [刷新本地图片和网络图片](arkts-ui-widget-image-update.md)
- [根据卡片状态刷新不同内容](arkts-ui-widget-update-by-status.md)
- [使用方刷新卡片内容(仅对系统应用开放)](arkts-ui-widget-content-update.md)
- [开发基于JS UI的卡片](js-ui-widget-development.md)
- [Stage模型服务卡片相关实例](service-widget-development-samples.md)
- [AbilityStage组件容器](abilitystage.md) - [AbilityStage组件容器](abilitystage.md)
- [应用上下文Context](application-context-stage.md) - [应用上下文Context](application-context-stage.md)
- 信息传递载体Want - 信息传递载体Want
......
# 卡片数据交互说明 # 卡片数据交互说明
ArkTS卡片框架提供了updateForm()接口和requestForm()接口主动触发卡片的页面刷新。**(介绍下LocalStorageProp在这个过程中起到的作用)** ArkTS卡片框架提供了updateForm()接口和requestForm()接口主动触发卡片的页面刷新。
![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png) ![WidgetLocalStorageProp](figures/WidgetLocalStorageProp.png)
......
...@@ -46,7 +46,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等 ...@@ -46,7 +46,7 @@ ExtensionAbility组件是基于特定场景(例如服务卡片、输入法等
## 实现指定类型的ExtensionAbility组件 ## 实现指定类型的ExtensionAbility组件
以实现卡片[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md)为例进行说明。卡片框架提供了[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md)基类,开发者通过派生此基类(如MyFormExtensionAbility),实现回调(如创建卡片的onCreate()回调、更新卡片的onUpdateForm()回调等)来实现具体卡片功能,具体见开发指导见[服务卡片FormExtensionAbility](widget-development-stage.md) 以实现卡片[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md)为例进行说明。卡片框架提供了[FormExtensionAbility](../reference/apis/js-apis-app-form-formExtensionAbility.md)基类,开发者通过派生此基类(如MyFormExtensionAbility),实现回调(如创建卡片的onCreate()回调、更新卡片的onUpdateForm()回调等)来实现具体卡片功能,具体见开发指导见[服务卡片FormExtensionAbility](service-widget-overview.md)
卡片FormExtensionAbility实现方不用关心使用方何时去请求添加、删除卡片,FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由卡片管理系统服务FormManagerService进行调度管理。 卡片FormExtensionAbility实现方不用关心使用方何时去请求添加、删除卡片,FormExtensionAbility实例及其所在的ExtensionAbility进程的整个生命周期,都是由卡片管理系统服务FormManagerService进行调度管理。
......
...@@ -57,13 +57,6 @@ FormExtensionAbility类拥有如下API接口,具体的API介绍详见[接口 ...@@ -57,13 +57,6 @@ FormExtensionAbility类拥有如下API接口,具体的API介绍详见[接口
| onConfigurationUpdate(config:&nbsp;Configuration):&nbsp;void | 当系统配置更新时调用。 | | onConfigurationUpdate(config:&nbsp;Configuration):&nbsp;void | 当系统配置更新时调用。 |
| onShareForm?(formId:&nbsp;string):&nbsp;{&nbsp;[key:&nbsp;string]:&nbsp;any&nbsp;} | 卡片提供方接收卡片分享的通知接口。 | | onShareForm?(formId:&nbsp;string):&nbsp;{&nbsp;[key:&nbsp;string]:&nbsp;any&nbsp;} | 卡片提供方接收卡片分享的通知接口。 |
FormExtensionAbility类还拥有成员context,为FormExtensionContext类,具体的API介绍详见[接口文档](../reference/apis/js-apis-inner-application-formExtensionContext.md)
| 接口名 | 描述 |
| -------- | -------- |
| startAbility(want:&nbsp;Want,&nbsp;callback:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | 回调形式拉起一个卡片所属应用的UIAbility(系统接口,三方应用不支持调用,需申请后台拉起权限)。 |
| startAbility(want:&nbsp;Want):&nbsp;Promise&lt;void&gt; | Promise形式拉起一个卡片所属应用的UIAbility(系统接口,三方应用不支持调用,需申请后台拉起权限)。 |
formProvider类有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-app-form-formProvider.md) formProvider类有如下API接口,具体的API介绍详见[接口文档](../reference/apis/js-apis-app-form-formProvider.md)
| 接口名 | 描述 | | 接口名 | 描述 |
...@@ -324,7 +317,7 @@ export default class EntryFormAbility extends FormExtension { ...@@ -324,7 +317,7 @@ export default class EntryFormAbility extends FormExtension {
} }
``` ```
具体的持久化方法可以参考[轻量级数据存储开发指导](../database/database-preference-guidelines.md) 具体的持久化方法可以参考[轻量级数据存储开发指导](../database/app-data-persistence-overview.md)
需要注意的是,卡片使用方在请求卡片时传递给提供方应用的Want数据中存在临时标记字段,表示此次请求的卡片是否为临时卡片: 需要注意的是,卡片使用方在请求卡片时传递给提供方应用的Want数据中存在临时标记字段,表示此次请求的卡片是否为临时卡片:
......
...@@ -54,14 +54,3 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上 ...@@ -54,14 +54,3 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上
| 逻辑代码执行(不包含import能力) | 不支持 | 支持 | | 逻辑代码执行(不包含import能力) | 不支持 | 支持 |
相比于JS卡片,ArkTS卡片在能力和场景方面更加丰富,因此无论开发何种用途的卡片,都推荐使用ArkTS卡片,因为它可以提高开发效率并实现动态化。但如果只需要做静态页面展示的卡片,可以考虑使用JS卡片。 相比于JS卡片,ArkTS卡片在能力和场景方面更加丰富,因此无论开发何种用途的卡片,都推荐使用ArkTS卡片,因为它可以提高开发效率并实现动态化。但如果只需要做静态页面展示的卡片,可以考虑使用JS卡片。
## 限制
为了降低FormExtensionAbility能力被三方应用滥用的风险,在FormExtensionAbility中限制以下接口的调用
- @ohos.ability.particleAbility.d.ts
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
\ No newline at end of file
# 服务卡片开发指导(Stage模型)
[服务卡片概述](service-widget-overview.md)
开发基于ArkTS UI的卡片
- [ArkTS卡片运行机制](arkts-ui-widget-working-principles.md)
- [ArkTS卡片相关模块](arkts-ui-widget-modules.md)
- ArkTS卡片开发指导
- [创建一个ArkTS卡片](arkts-ui-widget-creation.md)
- [配置卡片的配置文件](arkts-ui-widget-configuration.md)
- [卡片生命周期管理](arkts-ui-widget-lifecycle.md)
- 开发卡片页面
- [卡片页面能力说明](arkts-ui-widget-page-overview.md)
- [卡片使用动效能力](arkts-ui-widget-page-animation.md)
- [卡片使用自定义绘制能力](arkts-ui-widget-page-custom-drawing.md)
- 开发卡片事件
- [卡片事件能力说明](arkts-ui-widget-event-overview.md)
- [通过FormExtensionAbility刷新卡片内容](arkts-ui-widget-event-formextensionability.md)
- [通过UIAbility刷新卡片内容](arkts-ui-widget-event-uiability.md)
- [使用router事件跳转到指定页面](arkts-ui-widget-event-router.md)
- 卡片数据交互
- [卡片数据交互说明](arkts-ui-widget-interaction-overview.md)
- [定时刷新和定点刷新](arkts-ui-widget-update-by-time.md)
- [刷新本地图片和网络图片](arkts-ui-widget-image-update.md)
- [根据卡片状态刷新不同内容](arkts-ui-widget-update-by-status.md)
- [使用方刷新卡片内容(仅对系统应用开放)](arkts-ui-widget-content-update.md)
[开发基于JS UI的卡片](js-ui-widget-development.md)
[Stage模型服务卡片相关实例](service-widget-development-samples.md)
\ No newline at end of file
...@@ -134,10 +134,10 @@ ...@@ -134,10 +134,10 @@
| exported | 对其他应用是否可见,设置为true时,才能与其他应用进行通信传输数据。 | 是 | | exported | 对其他应用是否可见,设置为true时,才能与其他应用进行通信传输数据。 | 是 |
| readPermission | 访问数据时需要的权限,不配置默认不进行读权限校验。 | 否 | | readPermission | 访问数据时需要的权限,不配置默认不进行读权限校验。 | 否 |
| writePermission | 修改数据时需要的权限,不配置默认不进行写权限校验。 | 否 | | writePermission | 修改数据时需要的权限,不配置默认不进行写权限校验。 | 否 |
| metadata | 增加静默访问所需的额外配置项,包含name和resource字段。<br /> name类型固定为"ohos.extension.dataShare",是配置的唯一标识。 <br /> resource类型固定为"$profile:data_share_config",表示配置文件的名称为data_share_config.json。 | 若Ability启动模式为"singleton",则metadata必填,Ability启动模式可见[abilities对象的内部结构-launchType](../quick-start/module-structure.md#abilities对象的内部结构);其他情况下无需填写。 |
**module.json5配置样例:** **module.json5配置样例:**
```json ```json
"extensionAbilities": [ "extensionAbilities": [
{ {
...@@ -147,7 +147,35 @@ ...@@ -147,7 +147,35 @@
"description": "$string:description_datashareextability", "description": "$string:description_datashareextability",
"type": "dataShare", "type": "dataShare",
"uri": "datashare://com.samples.datasharetest.DataShare", "uri": "datashare://com.samples.datasharetest.DataShare",
"exported": true "exported": true,
"metadata": [{"name": "ohos.extension.dataShare", "resource": "$profile:data_share_config"}]
}
]
```
**表2** data_share_config.json对应属性字段
| 属性名称 | 备注说明 | 必填 |
| ------------ | ------------------------------------------------------------ | --- |
| tableConfig | 配置标签。 | 是 |
| uri | 指定配置生效的范围,uri支持以下三种格式,优先级为**表配置>库配置>\***,如果同时配置,高优先级会覆盖低优先级 。<br /> 1. "*" : 所有的数据库和表。<br /> 2. "datashare:///{bundleName}/{moduleName}/{storeName}" : 指定数据库。<br /> 3. "datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}" : 指定表。 | 是 |
| crossUserMode | 标识数据是否为多用户共享,配置为1则多用户数据共享,配置为2则多用户数据隔离。 | 是 |
**data_share_config.json配置样例**
```json
"tableConfig": [
{
"uri": "*",
"crossUserMode": 1
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00",
"crossUserMode": 1
},
{
"uri": "datashare:///com.acts.datasharetest/entry/DB00/TBL00",
"crossUserMode": 2
} }
] ]
``` ```
......
...@@ -70,7 +70,7 @@ ...@@ -70,7 +70,7 @@
| distributedfiles | distributedFilesDir | 分布式文件路径 | 应用在el2加密条件下存放分布式文件的目录,应用将文件放入该目录可分布式跨设备直接访问;随应用卸载而清理。 | | distributedfiles | distributedFilesDir | 分布式文件路径 | 应用在el2加密条件下存放分布式文件的目录,应用将文件放入该目录可分布式跨设备直接访问;随应用卸载而清理。 |
| files | filesDir | 应用通用文件路径 | 应用在本设备内部存储上通用的存放默认长期保存的文件路径;随应用卸载而清理。 | | files | filesDir | 应用通用文件路径 | 应用在本设备内部存储上通用的存放默认长期保存的文件路径;随应用卸载而清理。 |
| cache | cacheDir | 应用缓存文件路径 | 应用在本设备内部存储上用于缓存下载的文件或可重新生成的缓存文件的路径,应用cache目录大小超过配额或者系统空间达到一定条件,自动触发清理该目录下文件;用户通过系统空间管理类应用也可能触发清理该目录。应用需判断文件是否仍存在,决策是否需重新缓存该文件。 | | cache | cacheDir | 应用缓存文件路径 | 应用在本设备内部存储上用于缓存下载的文件或可重新生成的缓存文件的路径,应用cache目录大小超过配额或者系统空间达到一定条件,自动触发清理该目录下文件;用户通过系统空间管理类应用也可能触发清理该目录。应用需判断文件是否仍存在,决策是否需重新缓存该文件。 |
| preferences | preferencesDir | 应用首选项文件路径 | 应用在本设备内部存储上通过数据库API存储配置类或首选项的目录;随应用卸载而清理。 | | preferences | preferencesDir | 应用首选项文件路径 | 应用在本设备内部存储上通过数据库API存储配置类或首选项的目录;应用在本设备内部存储上通过数据库API存储配置类或首选项的目录;随应用卸载而清理。详见[通过用户首选项实现数据持久化](../database/data-persistence-by-preferences.md)。 |
| temp | tempDir | 应用临时文件路径 | 应用在本设备内部存储上仅在应用运行期间产生和需要的文件,应用退出后即清理。 | | temp | tempDir | 应用临时文件路径 | 应用在本设备内部存储上仅在应用运行期间产生和需要的文件,应用退出后即清理。 |
对于上述各类应用文件路径,常见使用场景如下: 对于上述各类应用文件路径,常见使用场景如下:
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
在操作系统中,存在各种各样的数据,按数据结构可分为: 在操作系统中,存在各种各样的数据,按数据结构可分为:
- 结构化数据:能够用统一的数据模型加以描述的数据。常见的是各类数据库数据。在应用开发中,对结构化数据的开发活动隶属于数据管理模块 - 结构化数据:能够用统一的数据模型加以描述的数据。常见的是各类数据库数据。在应用开发中,对结构化数据的开发活动隶属于[数据管理模块](../database/data-mgmt-overview.md)
- 非结构化数据:指数据结构不规则或不完整,没有预定义的数据结构/模型,不方便用数据库二维逻辑表来表现的数据。常见的是各类文件,如文档、图片、音频、视频等。在应用开发中,对非结构化数据的开发活动隶属于文件管理模块,将在下文展开介绍。 - 非结构化数据:指数据结构不规则或不完整,没有预定义的数据结构/模型,不方便用数据库二维逻辑表来表现的数据。常见的是各类文件,如文档、图片、音频、视频等。在应用开发中,对非结构化数据的开发活动隶属于文件管理模块,将在下文展开介绍。
......
# 设置分布式文件数据等级 # 设置分布式文件数据等级
不同设备本身的安全能力差异较大,一些小的嵌入式设备安全能力远弱于平板等设备类型。用户或者应用不同的文件数据有不同安全诉求,例如个人的健康信息和银行卡信息等不期望被弱设备读取。因此,OpenHarmony提供一套完整的数据分级、设备分级标准,并针对不同设备制定不同的数据流转策略。 不同设备本身的安全能力差异较大,一些小的嵌入式设备安全能力远弱于平板等设备类型。用户或者应用不同的文件数据有不同安全诉求,例如个人的健康信息和银行卡信息等不期望被弱设备读取。因此,OpenHarmony提供一套完整的数据分级、设备分级标准,并针对不同设备制定不同的数据流转策略,具体规则请参见[数据、设备安全分级](../database/access-control-by-device-and-data-level.md)
## 接口说明 ## 接口说明
......
...@@ -26,6 +26,14 @@ ...@@ -26,6 +26,14 @@
console.info(`createAVRecorder fail, error:${error}`); console.info(`createAVRecorder fail, error:${error}`);
} }
}); });
// AVRecorderConfig可参考下一章节
AVRecorder.prepare(AVRecorderConfig, (err) => {
if (err == null) {
console.log('prepare success');
} else {
console.log('prepare failed and error is ' + err.message);
}
})
let videoSurfaceId = null; let videoSurfaceId = null;
AVRecorder.getInputSurface().then((surfaceId) => { AVRecorder.getInputSurface().then((surfaceId) => {
......
...@@ -33,7 +33,7 @@ app.json5配置文件包含以下标签。 ...@@ -33,7 +33,7 @@ app.json5配置文件包含以下标签。
| 属性名称 | 含义 | 数据类型 | 是否可缺省 | | 属性名称 | 含义 | 数据类型 | 是否可缺省 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | 标识应用的Bundle名称,用于标识应用的唯一性。该标签不可缺省。标签的值命名规则&nbsp;<br/>-&nbsp;字符串以字母、数字、下划线和符号“.”组成。<br/>-&nbsp;以字母开头。<br/>-&nbsp;最小长度7个字节,最大长度127个字节。<br/>推荐采用反域名形式命名(如com.example.demo,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。<br/>其中,随系统源码编译的应用建议命名为“com.ohos.demo”形式,&nbsp;ohos标识OpenHarmony系统应用。 | 字符串 | 该标签不可缺省。 | | bundleName | 标识应用的Bundle名称,用于标识应用的唯一性。该标签不可缺省。标签的值命名规则&nbsp;<br/>-&nbsp;字符串以字母、数字、下划线和符号“.”组成。<br/>-&nbsp;以字母开头。<br/>-&nbsp;最小长度7个字节,最大长度127个字节。<br/>推荐采用反域名形式命名(如com.example.demo,建议第一级为域名后缀com,第二级为厂商/个人名,第三级为应用名,也可以多级)。<br/>其中,随系统源码编译的应用建议命名为“com.ohos.demo”形式,&nbsp;ohos标识OpenHarmony系统应用。 | 字符串 | 该标签不可缺省。 |
| bundleType| 标识应用的Bundle类型,用于区分应用或者原子化服务。该标签可选值为app和atomicService&nbsp;<br/>-&nbsp;app:当前Bundle为普通应用。<br/>-&nbsp;atomicService:当前Bundle为原子化服务。| 字符串| 该标签可以缺省,缺省为app。 | | bundleType| 标识应用的Bundle类型,用于区分应用或者原子化服务。该标签可选值为app和atomicService&nbsp;<br/>-&nbsp;app:当前Bundle为普通应用。<br/>-&nbsp;atomicService:当前Bundle为原子化服务。<br/>-&nbsp;shared:当前Bundle为共享库应用。 | 字符串| 该标签可以缺省,缺省为app。 |
| debug | 标识应用是否可调试,该标签由IDE编译构建时生成。<br/>-&nbsp;true:可调试。<br/>-&nbsp;false:不可调式。 | 布尔值 | 该标签可以缺省,缺省为false。 | | debug | 标识应用是否可调试,该标签由IDE编译构建时生成。<br/>-&nbsp;true:可调试。<br/>-&nbsp;false:不可调式。 | 布尔值 | 该标签可以缺省,缺省为false。 |
| icon | 标识[应用的图标](../application-models/application-component-configuration-stage.md),标签值为图标资源文件的索引。 | 字符串 | 该标签不可缺省。 | | icon | 标识[应用的图标](../application-models/application-component-configuration-stage.md),标签值为图标资源文件的索引。 | 字符串 | 该标签不可缺省。 |
| label | 标识[应用的名称](../application-models/application-component-configuration-stage.md),标签值为字符串资源的索引。 | 字符串 | 该标签不可缺省。 | | label | 标识[应用的名称](../application-models/application-component-configuration-stage.md),标签值为字符串资源的索引。 | 字符串 | 该标签不可缺省。 |
......
...@@ -40,7 +40,7 @@ Column() { ...@@ -40,7 +40,7 @@ Column() {
- Text组件的非必选参数content。 - Text组件的非必选参数content。
- ```ts ```ts
// string类型的参数 // string类型的参数
Text('test') Text('test')
// $r形式引入应用资源,可应用于多语言场景 // $r形式引入应用资源,可应用于多语言场景
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
> **说明:** > **说明:**
>
> 从API version 9开始,该装饰器支持在ArkTS卡片中使用。 > 从API version 9开始,该装饰器支持在ArkTS卡片中使用。
......
...@@ -5,6 +5,7 @@ ...@@ -5,6 +5,7 @@
> **说明:** > **说明:**
>
> 从API version 9开始,这两个装饰器支持在ArkTS卡片中使用。 > 从API version 9开始,这两个装饰器支持在ArkTS卡片中使用。
......
...@@ -4,6 +4,6 @@ ...@@ -4,6 +4,6 @@
除了前面章节提到的组件状态管理和应用状态管理,ArkTS还提供了\@Watch和$$来为开发者提供更多功能: 除了前面章节提到的组件状态管理和应用状态管理,ArkTS还提供了\@Watch和$$来为开发者提供更多功能:
- \@Watch用于监听状态变量的变化。 - [\@Watch](arkts-watch.md)用于监听状态变量的变化。
- $$运算符:给内置组件提供TS变量的引用,使得TS变量和内置组件的内部状态保持同步。 - [$$运算符](arkts-two-way-sync.md):给内置组件提供TS变量的引用,使得TS变量和内置组件的内部状态保持同步。
...@@ -52,7 +52,7 @@ ...@@ -52,7 +52,7 @@
| -------------- | ---------------------------------------- | | -------------- | ---------------------------------------- |
| 装饰器参数 | 别名:常量字符串,可选。<br/>如果提供了别名,则必须有\@Provide的变量和其有相同的别名才可以匹配成功;否则,则需要变量名相同才能匹配成功。 | | 装饰器参数 | 别名:常量字符串,可选。<br/>如果提供了别名,则必须有\@Provide的变量和其有相同的别名才可以匹配成功;否则,则需要变量名相同才能匹配成功。 |
| 同步类型 | 双向:从\@Provide变量(具体请参见\@Provide)到所有\@Consume变量,以及相反的方向。双向同步操作与\@State和\@Link的组合相同。 | | 同步类型 | 双向:从\@Provide变量(具体请参见\@Provide)到所有\@Consume变量,以及相反的方向。双向同步操作与\@State和\@Link的组合相同。 |
| 允许装饰的变量类型 | Object、class、string、number、boolean、enum类型,以及这些类型的数组。嵌套类型的场景请参考[观察变化](#观察变化)<br/>不支持any,不允许使用undefined和null。<br/>必须指定类型。\@Provide变量的\@Consume变量的类型必须相同。<br/>**说明:**<br/>-&nbsp;\@Consume装饰的变量,在其父节点或者祖先节点上,必须有对应的属性和别名的\@Provide装饰的变量。 | | 允许装饰的变量类型 | Object、class、string、number、boolean、enum类型,以及这些类型的数组。嵌套类型的场景请参考[观察变化](#观察变化)<br/>不支持any,不允许使用undefined和null。<br/>必须指定类型。\@Provide变量的\@Consume变量的类型必须相同。<br/>**说明:**<br/>\@Consume装饰的变量,在其父节点或者祖先节点上,必须有对应的属性和别名的\@Provide装饰的变量。 |
| 被装饰变量的初始值 | 无,禁止本地初始化。 | | 被装饰变量的初始值 | 无,禁止本地初始化。 |
...@@ -112,7 +112,8 @@ ...@@ -112,7 +112,8 @@
2. 通知\@Consume更新后,子组件所有依赖\@Consume的系统组件(elementId)都会被通知更新。以此实现\@Provide对\@Consume状态数据同步。 2. 通知\@Consume更新后,子组件所有依赖\@Consume的系统组件(elementId)都会被通知更新。以此实现\@Provide对\@Consume状态数据同步。
3.\@Consume装饰的数据变化时: 3.\@Consume装饰的数据变化时:
1. 通过初始渲染的步骤可知,子组件\@Consume持有\@Provide的实例。在\@Consume更新后调用\@Provide的更新方法,将更新的数值同步回\@Provide,以此实现\@Consume向\@Provide的同步更新。
通过初始渲染的步骤可知,子组件\@Consume持有\@Provide的实例。在\@Consume更新后调用\@Provide的更新方法,将更新的数值同步回\@Provide,以此实现\@Consume向\@Provide的同步更新。
## 使用场景 ## 使用场景
......
...@@ -123,7 +123,8 @@ struct MainView { ...@@ -123,7 +123,8 @@ struct MainView {
CounterView(label为 'CounterView \#positive')子组件在初次渲染时创建。此子组件携带名为counter的状态变量。当修改CounterView.counter状态变量时,CounterView(label为 'CounterView \#positive')子组件重新渲染时并保留状态变量值。当MainView.toggle状态变量的值更改为false时,MainView父组件内的if语句将更新,随后将删除CounterView(label为 'CounterView \#positive')子组件。与此同时,将创建新的CounterView(label为 'CounterView \#negative')实例。而它自己的counter状态变量设置为初始值0。 CounterView(label为 'CounterView \#positive')子组件在初次渲染时创建。此子组件携带名为counter的状态变量。当修改CounterView.counter状态变量时,CounterView(label为 'CounterView \#positive')子组件重新渲染时并保留状态变量值。当MainView.toggle状态变量的值更改为false时,MainView父组件内的if语句将更新,随后将删除CounterView(label为 'CounterView \#positive')子组件。与此同时,将创建新的CounterView(label为 'CounterView \#negative')实例。而它自己的counter状态变量设置为初始值0。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > **说明:**
>
> CounterView(label为 'CounterView \#positive')和CounterView(label为 'CounterView \#negative')是同一自定义组件的两个不同实例。if分支的更改,不会更新现有子组件,也不会保留状态。 > CounterView(label为 'CounterView \#positive')和CounterView(label为 'CounterView \#negative')是同一自定义组件的两个不同实例。if分支的更改,不会更新现有子组件,也不会保留状态。
以下示例展示了条件更改时,若需要保留counter值所做的修改。 以下示例展示了条件更改时,若需要保留counter值所做的修改。
......
...@@ -97,12 +97,12 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。 ...@@ -97,12 +97,12 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
|:----------------:|:---:|-----| |:----------------:|:---:|-----|
| FORM | 0 | [FormExtensionAbility](../../application-models/widget-development-stage.md):卡片扩展能力,提供卡片开发能力。 | | FORM | 0 | [FormExtensionAbility](../../application-models/service-widget-overview.md):卡片扩展能力,提供卡片开发能力。 |
| WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md):延时任务扩展能力,允许应用在系统闲时执行实时性不高的任务。 | | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md):延时任务扩展能力,允许应用在系统闲时执行实时性不高的任务。 |
| INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md):输入法扩展能力,用于开发输入法应用。 | | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md):输入法扩展能力,用于开发输入法应用。 |
| SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md):后台服务扩展能力,提供后台运行并对外提供相应能力。 | | SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md):后台服务扩展能力,提供后台运行并对外提供相应能力。 |
| ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md):无障碍服务扩展能力,支持访问与操作前台界面。 | | ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md):无障碍服务扩展能力,支持访问与操作前台界面。 |
| DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/database-datashare-guidelines.md):数据共享扩展能力,用于对外提供数据读写服务。 | | DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/share-data-by-datashareextensionability.md):数据共享扩展能力,用于对外提供数据读写服务。 |
| FILE_SHARE | 6 | FileShareExtensionAbility:文件共享扩展能力,用于应用间的文件分享。预留能力,当前暂未支持。 | | FILE_SHARE | 6 | FileShareExtensionAbility:文件共享扩展能力,用于应用间的文件分享。预留能力,当前暂未支持。 |
| STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md):静态广播扩展能力,用于处理静态事件,比如开机事件。 | | STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md):静态广播扩展能力,用于处理静态事件,比如开机事件。 |
| WALLPAPER | 8 | WallpaperExtensionAbility:壁纸扩展能力,用于实现桌面壁纸。预留能力,当前暂未支持。 | | WALLPAPER | 8 | WallpaperExtensionAbility:壁纸扩展能力,用于实现桌面壁纸。预留能力,当前暂未支持。 |
...@@ -186,7 +186,7 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。 ...@@ -186,7 +186,7 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。
| AUTO_ROTATION_PORTRAIT_RESTRICTED |11|表示受开关控制的自动竖向旋转模式。| | AUTO_ROTATION_PORTRAIT_RESTRICTED |11|表示受开关控制的自动竖向旋转模式。|
| LOCKED |12|表示锁定模式。| | LOCKED |12|表示锁定模式。|
### CompatiblePolicy ### CompatiblePolicy<sup>10+</sup>
标识共享库的版本兼容类型。 标识共享库的版本兼容类型。
......
...@@ -29,7 +29,7 @@ createEffect(source: image.PixelMap): Filter ...@@ -29,7 +29,7 @@ createEffect(source: image.PixelMap): Filter
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------- | ---- | -------- | | ------- | ----------------- | ---- | -------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | image模块创建的PixelMap实例。 | | source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | image模块创建的PixelMap实例。可通过图片解码或直接创建获得,具体可见[图片开发指导](../../media/image-overview.md) |
**返回值:** **返回值:**
...@@ -61,7 +61,7 @@ createColorPicker(source: image.PixelMap): Promise\<ColorPicker> ...@@ -61,7 +61,7 @@ createColorPicker(source: image.PixelMap): Promise\<ColorPicker>
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------- | ---- | -------------------------- | | -------- | ----------- | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | image模块创建的PixelMap实例。 | | source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 | image模块创建的PixelMap实例。可通过图片解码或直接创建获得,具体可见[图片开发指导](../../media/image-overview.md) |
**返回值:** **返回值:**
...@@ -95,7 +95,7 @@ createColorPicker(source: image.PixelMap, callback: AsyncCallback\<ColorPicker>) ...@@ -95,7 +95,7 @@ createColorPicker(source: image.PixelMap, callback: AsyncCallback\<ColorPicker>)
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------ | ---- | -------------------------- | | -------- | ------------------ | ---- | -------------------------- |
| source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 |image模块创建的PixelMap实例。 | | source | [image.PixelMap](js-apis-image.md#pixelmap7) | 是 |image模块创建的PixelMap实例。可通过图片解码或直接创建获得,具体可见[图片开发指导](../../media/image-overview.md) |
| callback | AsyncCallback\<[ColorPicker](#colorpicker)> | 是 | 回调函数。返回创建的ColorPicker实例。 | | callback | AsyncCallback\<[ColorPicker](#colorpicker)> | 是 | 回调函数。返回创建的ColorPicker实例。 |
**示例:** **示例:**
......
...@@ -476,7 +476,7 @@ try { ...@@ -476,7 +476,7 @@ try {
| isKeepData | boolean | 否 | 卸载时是否保留数据目录。 | | isKeepData | boolean | 否 | 卸载时是否保留数据目录。 |
| hashParams | Array<[HashParam](#hashparam)> | 否 | 哈希值参数。 | | hashParams | Array<[HashParam](#hashparam)> | 否 | 哈希值参数。 |
| crowdtestDeadline| number | 否 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期。 | | crowdtestDeadline| number | 否 |[众测](https://developer.huawei.com/consumer/cn/agconnect/crowd-test/)截止日期。 |
| sharedBundleDirPaths | Array\<String> | 否 |共享包文件所在路径。 | | sharedBundleDirPaths<sup>10+</sup> | Array\<String> | 否 |共享包文件所在路径。 |
## UninstallParam<sup>10+</sup> ## UninstallParam<sup>10+</sup>
......
...@@ -45,7 +45,7 @@ getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallba ...@@ -45,7 +45,7 @@ getLauncherAbilityInfo(bundleName: string, userId: number, callback: AsyncCallba
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
| 17700001 | The specified bundle name is not found. | | 17700001 | The specified bundle name is not found. |
| 17700004 | The specified userId is not found. | | 17700004 | The specified user ID is not found. |
**示例:** **示例:**
...@@ -97,7 +97,7 @@ getLauncherAbilityInfo(bundleName: string, userId: number) : Promise<Array\<[Lau ...@@ -97,7 +97,7 @@ getLauncherAbilityInfo(bundleName: string, userId: number) : Promise<Array\<[Lau
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
| 17700001 | The specified bundle name is not found. | | 17700001 | The specified bundle name is not found. |
| 17700004 | The specified userId is not found. | | 17700004 | The specified user ID is not found. |
**示例:** **示例:**
...@@ -145,7 +145,7 @@ getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback<Array\<[Launch ...@@ -145,7 +145,7 @@ getAllLauncherAbilityInfo(userId: number, callback: AsyncCallback<Array\<[Launch
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
| 17700004 | The specified userId is not found. | | 17700004 | The specified user ID is not found. |
示例: 示例:
...@@ -194,7 +194,7 @@ getAllLauncherAbilityInfo(userId: number) : Promise<Array\<[LauncherAbilityInfo] ...@@ -194,7 +194,7 @@ getAllLauncherAbilityInfo(userId: number) : Promise<Array\<[LauncherAbilityInfo]
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| -------- | ---------------------------------------- | | -------- | ---------------------------------------- |
| 17700004 | The specified userId is not found. | | 17700004 | The specified user ID is not found. |
**示例:** **示例:**
......
...@@ -239,7 +239,7 @@ getOverlayModuleInfo(moduleName: string): Promise\<OverlayModuleInfo>; ...@@ -239,7 +239,7 @@ getOverlayModuleInfo(moduleName: string): Promise\<OverlayModuleInfo>;
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700002 | The specified module name is not found. | | 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. | | 17700033 | The specified module is not an overlay module. |
**示例:** **示例:**
...@@ -415,7 +415,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promi ...@@ -415,7 +415,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName?: string): Promi
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700032 | The 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. | | 17700033 | The specified module is not an overlay module. |
...@@ -462,7 +462,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callbac ...@@ -462,7 +462,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, moduleName: string, callbac
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700032 | The 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. | | 17700033 | The specified module is not an overlay module. |
...@@ -511,7 +511,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\<Ar ...@@ -511,7 +511,7 @@ getOverlayModuleInfoByBundleName(bundleName: string, callback: AsyncCallback\<Ar
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700032 | The 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. | | 17700033 | The specified module is not an overlay module. |
...@@ -565,7 +565,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: s ...@@ -565,7 +565,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName?: s
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700034 | The specified module is an overlay module. | | 17700034 | The specified module is an overlay module. |
| 17700035 | The specified bundle is an overlay bundle. | | 17700035 | The specified bundle is an overlay bundle. |
...@@ -612,7 +612,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: st ...@@ -612,7 +612,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, moduleName: st
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700034 | The specified module is an overlay module. | | 17700034 | The specified module is an overlay module. |
| 17700035 | The specified bundle is an overlay bundle. | | 17700035 | The specified bundle is an overlay bundle. |
...@@ -661,7 +661,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn ...@@ -661,7 +661,7 @@ getTargetOverlayModuleInfosByBundleName(targetBundleName: string, callback: Asyn
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------ | -------------------------------------- | | ------ | -------------------------------------- |
| 17700001 | The specified bundleName is not found | | 17700001 | The specified bundleName is not found. |
| 17700002 | The specified module name is not found. | | 17700002 | The specified module name is not found. |
| 17700034 | The specified module is an overlay module. | | 17700034 | The specified module is an overlay module. |
| 17700035 | The specified bundle is an overlay bundle. | | 17700035 | The specified bundle is an overlay bundle. |
......
# @ohos.application.uriPermissionManager(URI权限管理)
> **说明:**
>
> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
URI权限管理模块。用于应用A授权/撤销授权URI给应用B
## 导入模块
```js
import UriPermissionManager from '@ohos.application.uriPermissionManager';
```
## uriPermissionManager.grantUriPermission
grantUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void
授权URI给指定应用,通过callback返回结果。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uri | string | 是 | 指向文件的URI,例如fileshare:///com.samples.filesharetest.FileShare/person/10。 |
| flag | [wantConstant.Flags](js-apis-ability-wantConstant.md#wantconstantflags) | 是 | URI的读权限或写权限。 |
| targetBundleName | string | 是 | 被授权URI的应用包名 |
| callback | AsyncCallback&lt;number&gt; | 是 | callback形式返回检验结果,返回0表示有权限,返回-1表示无权限。 |
**示例:**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.grantUriPermission(uri, WantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName, (result) => {
console.log("result.code = " + result.code)
})
```
## uriPermissionManager.grantUriPermission
grantUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise&lt;number&gt;
授权URI给指定应用,通过返回值返回结果。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uri | string | 是 | 指向文件的URI,例如fileshare:///com.samples.filesharetest.FileShare/person/10。 |
| flag | [wantConstant.Flags](js-apis-ability-wantConstant.md#wantconstantflags) | 是 | URI的读权限或写权限。 |
| targetBundleName | string | 是 | 被授权URI的应用包名 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt; | 返回0表示有权限,返回-1表示无权限。 |
**示例:**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.grantUriPermission(uri, wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, targetBundleName)
.then((data) => {
console.log('Verification succeeded.' + data)
}).catch((error) => {
console.log('Verification failed.');
})
```
## uriPermissionManager.revokeUriPermission
revokeUriPermission(uri: string, accessTokenId: number, callback: AsyncCallback&lt;number&gt;): void
撤销授权指定应用的URI,通过callback返回结果。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uri | string | 是 | 指向文件的URI,例如fileshare:///com.samples.filesharetest.FileShare/person/10。 |
| targetBundleName | string | 是 | 被撤销授权uri的应用包名 |
| callback | AsyncCallback&lt;number&gt; | 是 | callback形式返回检验结果,返回0表示有权限,返回-1表示无权限。 |
**示例:**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let URI = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.revokeUriPermission(uri, targetBundleName, (result) => {
console.log("result.code = " + result.code)
})
```
## uriPermissionManager.revokeUriPermission
revokeUriPermission(uri: string, flag: wantConstant.Flags, accessTokenId: number): Promise&lt;number&gt;
撤销授权指定应用的URI,通过返回值返回结果。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| uri | string | 是 | 指向文件的URI,例如fileshare:///com.samples.filesharetest.FileShare/person/10。 |
| targetBundleName | string | 是 | 被授权URI的应用包名 |
**返回值:**
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;number&gt; | 返回0表示有权限,返回-1表示无权限。 |
**示例:**
```js
import WantConstant from '@ohos.ability.wantConstant';
let targetBundleName = 'com.example.test_case1'
let uri = "fileshare:///com.samples.filesharetest.FileShare/person/10"
uriPermissionManager.revokeUriPermission(uri, targetBundleName)
.then((data) => {
console.log('Verification succeeded.' + data)
}).catch((error) => {
console.log('Verification failed.');
})
```
...@@ -300,8 +300,6 @@ import window from '@ohos.window'; ...@@ -300,8 +300,6 @@ import window from '@ohos.window';
窗口生命周期。 窗口生命周期。
**系统接口:** 此接口为系统接口。
**系统能力**:SystemCapability.WindowManager.WindowManager.Core **系统能力**:SystemCapability.WindowManager.WindowManager.Core
| 名称 | 值 | 说明 | | 名称 | 值 | 说明 |
...@@ -832,6 +830,148 @@ try { ...@@ -832,6 +830,148 @@ try {
} }
``` ```
## window.on('gestureNavigationEnabledChange')<sup>10+</sup>
on(type: 'gestureNavigationEnabledChange', callback: Callback&lt;boolean&gt;): void
添加手势导航启用状态变化的监听。
**系统接口:** 此接口为系统接口。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | ---- | ----------------------------------------------------------------------------- |
| type | string | 是 | 监听事件,固定为'gestureNavigationEnabledChange',即手势导航启用状态变化事件。 |
| callback | Callback&lt;boolean&gt; | 是 | 回调函数。返回当前手势导航的启用状态。true表示手势导航状态变化为启用;false表示手势导航状态变化为禁用。 |
**示例:**
```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
移除手势导航启用状态变化的监听。
**系统接口:** 此接口为系统接口。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------- | -- | ------------------------------------------------------------ |
| type | string | 是 | 监听事件,固定为'gestureNavigationEnabledChange',即手势导航启用状态变化事件。 |
| callback | Callback&lt;boolean&gt; | 否 | 已注册的回调函数。参数传入时表示只移除该监听;参数未传入时表示移除所有手势导航启用状态变化的监听。 |
**示例:**
```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
设置手势导航启用状态。使用callback异步回调。
**系统接口:** 此接口为系统接口。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | -------------- |
| enable | boolean | 是 | 设置手势导航启用状态。true表示启用手势导航;false表示禁用手势导航。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调信息。 |
**错误码:**
以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)
| 错误码ID | 错误信息 |
| ------- | --------------------------------------------- |
| 1300002 | This window state is abnormal. |
| 1300003 | This window manager service works abnormally. |
**示例:**
```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;
设置手势导航启用状态。使用Promise异步回调。
**系统接口:** 此接口为系统接口。
**系统能力:** SystemCapability.WindowManager.WindowManager.Core
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------ | ------- | ---- | -------------------- |
| enable | boolean | 是 | 设置手势导航启用状态。true表示启用手势导航;false表示禁用手势导航。 |
**返回值:**
| 类型 | 说明 |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | 无返回结果的Promise对象。 |
**错误码:**
以下错误码的详细介绍请参见[窗口错误码](../errorcodes/errorcode-window.md)
| 错误码ID | 错误信息 |
| ------- | -------------------------------------------- |
| 1300002 | This window state is abnormal. |
| 1300003 | This window manager service works abnormally. |
**示例:**
```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> ## window.create<sup>(deprecated)</sup>
create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void create(id: string, type: WindowType, callback: AsyncCallback&lt;Window&gt;): void
...@@ -2361,7 +2501,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback&lt;void ...@@ -2361,7 +2501,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback&lt;void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | 是 | 设置加载页面的路径。 | | path | string | 是 | 设置加载页面的路径。 |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**错误码:** **错误码:**
...@@ -2407,7 +2547,7 @@ loadContent(path: string, storage: LocalStorage): Promise&lt;void&gt; ...@@ -2407,7 +2547,7 @@ loadContent(path: string, storage: LocalStorage): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | 是 | 设置加载页面的路径。 | | path | string | 是 | 设置加载页面的路径。 |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 |
**返回值:** **返回值:**
...@@ -6788,7 +6928,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback&lt;void ...@@ -6788,7 +6928,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback&lt;void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | 是 | 设置加载页面的路径。 | | path | string | 是 | 设置加载页面的路径。 |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
**错误码:** **错误码:**
...@@ -6843,7 +6983,7 @@ loadContent(path: string, storage?: LocalStorage): Promise&lt;void&gt; ...@@ -6843,7 +6983,7 @@ loadContent(path: string, storage?: LocalStorage): Promise&lt;void&gt;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ |
| path | string | 是 | 设置加载页面的路径。 | | path | string | 是 | 设置加载页面的路径。 |
| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | storage | [LocalStorage](../../quick-start/arkts-localstorage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 |
**返回值:** **返回值:**
......
...@@ -28,15 +28,15 @@ Image(src: PixelMap | ResourceStr | DrawableDescriptor) ...@@ -28,15 +28,15 @@ Image(src: PixelMap | ResourceStr | DrawableDescriptor)
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | ---- | ---------------------------------------- | ---- | ---------------------------------------- |
| src | &nbsp;[PixelMap](../apis/js-apis-image.md#pixelmap7)&nbsp;\|ResourceStr\|&nbsp;[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是 | 图片的数据源,支持本地图片和网络图片。<br/>当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。<br/>\- 支持的图片格式包括png、jpg、bmp、svg和gif。<br/>\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]``Base64`字符串数据。<br/>\- 支持`datashare://`路径前缀的字符串,用于访问通过data&nbsp;ability提供的图片路径。图片加载前需要申请[媒体库功能相关权限](../../file-management/medialibrary-overview.md#申请媒体库功能相关权限)<br/>\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。<br/>\- 支持[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor)对象<br/>**说明:**<br/>- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。<br/>- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串<br/>- ArkTS卡片上不支持&nbsp;[PixelMap](../apis/js-apis-image.md#pixelmap7)类型 | | src | &nbsp;[PixelMap](../apis/js-apis-image.md#pixelmap7)&nbsp;\|ResourceStr\|&nbsp;[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor) | 是 | 图片的数据源,支持本地图片和网络图片。<br/>当使用相对路径引用图片资源时,例如`Image("common/test.jpg")`,不支持跨包/跨模块调用该Image组件,建议使用`$r`方式来管理需全局使用的图片资源。<br/>\- 支持的图片格式包括png、jpg、bmp、svg和gif。<br/>\- 支持`Base64`字符串。格式`data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, 其中`[base64 data]``Base64`字符串数据。<br/>\- 支持`datashare://`路径前缀的字符串,用于访问通过data&nbsp;ability提供的图片路径。<br/>\- 支持file:///data/storage路径前缀的字符串,用于读取本应用安装目录下files文件夹下的图片资源。需要保证目录包路径下的文件有可读权限。<br/>\- 支持[DrawableDescriptor](../apis/js-apis-arkui-drawableDescriptor.md#drawabledescriptor)对象<br/>**说明:**<br/>- ArkTS卡片上支持gif图片格式动效,但仅在显示时播放一次。<br/>- ArkTS卡片上不支持`http://`等网络相关路径前缀、`datashare://`路径前缀以及`file://data/storage`路径前缀的字符串<br/>- ArkTS卡片上不支持&nbsp;[PixelMap](../apis/js-apis-image.md#pixelmap7)类型 |
## 属性 ## 属性
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ | | ------------------------ | ---------------------------------------- | ---------------------------------------- |
| alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | alt | string \| [Resource](ts-types.md#resource类型) | 加载时显示的占位图,支持本地图片。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。<br/>默认值:ImageFit.Cover<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | 设置图片的缩放类型。<br/>默认值:ImageFit.Cover<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。<br/>默认值:ImageRepeat.NoRepeat<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:**<br/>svg类型图源不支持该属性。 | | objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | 设置图片的重复样式。<br/>默认值:ImageRepeat.NoRepeat<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:**<br/>svg类型图源不支持该属性。 |
...@@ -82,7 +82,7 @@ Image(src: PixelMap | ResourceStr | DrawableDescriptor) ...@@ -82,7 +82,7 @@ Image(src: PixelMap | ResourceStr | DrawableDescriptor)
除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
| 名称 | 功能描述 | | 名称 | 功能描述 |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------------------------------- | ---------------------------------------- |
| onComplete(callback:&nbsp;(event?:&nbsp;{&nbsp;width:&nbsp;number,&nbsp;height:&nbsp;number,&nbsp;componentWidth:&nbsp;number,<br>&nbsp;componentHeight:&nbsp;number,&nbsp;loadingStatus:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 图片成功加载时触发该回调,返回成功加载的图片尺寸。<br>- width:图片的宽,单位为像素。<br/>- height:图片的高,单位为像素。<br/>- componentWidth:组件的宽,单位为像素。<br/>- componentHeight:组件的高,单位为像素。<br/>- loadingStatus:图片加载成功的状态。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>loadingStatus返回的状态值为0时,代表图片加载失败;返回的状态值为1时,代表图片加载成功。 | | onComplete(callback:&nbsp;(event?:&nbsp;{&nbsp;width:&nbsp;number,&nbsp;height:&nbsp;number,&nbsp;componentWidth:&nbsp;number,<br>&nbsp;componentHeight:&nbsp;number,&nbsp;loadingStatus:&nbsp;number&nbsp;})&nbsp;=&gt;&nbsp;void) | 图片成功加载时触发该回调,返回成功加载的图片尺寸。<br>- width:图片的宽,单位为像素。<br/>- height:图片的高,单位为像素。<br/>- componentWidth:组件的宽,单位为像素。<br/>- componentHeight:组件的高,单位为像素。<br/>- loadingStatus:图片加载成功的状态。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>loadingStatus返回的状态值为0时,代表图片加载失败;返回的状态值为1时,代表图片加载成功。 |
| onError(callback:&nbsp;(event?:&nbsp;{&nbsp;componentWidth:&nbsp;number,&nbsp;componentHeight:&nbsp;number&nbsp;, message<sup>9+</sup>: string })&nbsp;=&gt;&nbsp;void) | 图片加载出现异常时触发该回调。<br>- componentWidth:组件的宽,单位为像素。<br/>- componentHeight:组件的高,单位为像素。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | onError(callback:&nbsp;(event?:&nbsp;{&nbsp;componentWidth:&nbsp;number,&nbsp;componentHeight:&nbsp;number&nbsp;, message<sup>9+</sup>: string })&nbsp;=&gt;&nbsp;void) | 图片加载出现异常时触发该回调。<br>- componentWidth:组件的宽,单位为像素。<br/>- componentHeight:组件的高,单位为像素。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | onFinish(event:&nbsp;()&nbsp;=&gt;&nbsp;void) | 当加载的源文件为带动效的svg图片时,当svg动效播放完成时会触发这个回调,如果动效为无限循环动效,则不会触发这个回调。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
...@@ -163,7 +163,7 @@ struct ImageExample1 { ...@@ -163,7 +163,7 @@ struct ImageExample1 {
### 网络图片 ### 网络图片
加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用SDK中提供的[HTTP](../../connectivity/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../media/image.md)。代码如下。 加载网络图片时,默认网络超时是5分钟,建议使用alt配置加载时的占位图。如果需要更灵活的网络配置,可以使用SDK中提供的[HTTP](../../connectivity/http-request.md)工具包发送网络请求,接着将返回的数据解码为Image组件中的`PixelMap`,图片开发可参考[图片处理](../../media/image-overview.md)。代码如下。
```tsx ```tsx
// @ts-nocheck // @ts-nocheck
......
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
> **说明:** > **说明:**
> >
> - 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > - 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
> - 子组件个数:多个。 > - 子组件个数:多个。
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
> **说明:** > **说明:**
> >
> 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
## 接口 ## 接口
......
...@@ -21,7 +21,7 @@ ...@@ -21,7 +21,7 @@
> >
> ForEach/LazyForEach语句中,会计算展开所有子节点索引值。 > ForEach/LazyForEach语句中,会计算展开所有子节点索引值。
> >
> [if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载)发生变化以后,会更新子节点索引值。 > [if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)发生变化以后,会更新子节点索引值。
> >
> Grid子组件的visibility属性设置为Hidden或None时依然会计算索引值。 > Grid子组件的visibility属性设置为Hidden或None时依然会计算索引值。
> >
...@@ -51,7 +51,7 @@ Grid(scroller?: Scroller) ...@@ -51,7 +51,7 @@ Grid(scroller?: Scroller)
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 |
| scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 | | scrollBarColor | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Color](ts-appendix-enums.md#color) | 设置滚动条的颜色。 |
| scrollBarWidth | string \| number | 设置滚动条的宽度。宽度设置后,滚动条正常状态和按压状态宽度均为滚动条的宽度值。<br/>默认值:4<br/>单位:vp | | scrollBarWidth | string \| number | 设置滚动条的宽度。宽度设置后,滚动条正常状态和按压状态宽度均为滚动条的宽度值。<br/>默认值:4<br/>单位:vp |
| cachedCount | number | 设置预加载的GridItem的数量,只在[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载)中生效。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)<br/>默认值:1<br/>**说明:** <br>设置缓存后会在Grid显示区域上下各缓存cachedCount*列数个GridItem。<br/>[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载)超出显示和缓存范围的GridItem会被释放。<br/>设置为小于0的值时,按默认值显示。 | | cachedCount | number | 设置预加载的GridItem的数量,只在[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)中生效。具体使用可参考[减少应用白块说明](../../ui/arkts-performance-improvement-recommendation.md#减少应用滑动白块)<br/>默认值:1<br/>**说明:** <br>设置缓存后会在Grid显示区域上下各缓存cachedCount*列数个GridItem。<br/>[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)超出显示和缓存范围的GridItem会被释放。<br/>设置为小于0的值时,按默认值显示。 |
| editMode <sup>8+</sup> | boolean | 设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部[GridItem](ts-container-griditem.md)<br/>默认值:flase | | editMode <sup>8+</sup> | boolean | 设置Grid是否进入编辑模式,进入编辑模式可以拖拽Grid组件内部[GridItem](ts-container-griditem.md)<br/>默认值:flase |
| layoutDirection<sup>8+</sup> | [GridDirection](#griddirection8枚举说明) | 设置布局的主轴方向。<br/>默认值:GridDirection.Row | | layoutDirection<sup>8+</sup> | [GridDirection](#griddirection8枚举说明) | 设置布局的主轴方向。<br/>默认值:GridDirection.Row |
| maxCount<sup>8+</sup> | number | 当layoutDirection是Row/RowReverse时,表示可显示的最大列数<br/>当layoutDirection是Column/ColumnReverse时,表示可显示的最大行数。<br/>默认值:Infinity<br/>**说明:** <br/>当maxCount小于minCount时,maxCount和minCount都按默认值处理。<br/>设置为小于0的值时,按默认值显示。 | | maxCount<sup>8+</sup> | number | 当layoutDirection是Row/RowReverse时,表示可显示的最大列数<br/>当layoutDirection是Column/ColumnReverse时,表示可显示的最大行数。<br/>默认值:Infinity<br/>**说明:** <br/>当maxCount小于minCount时,maxCount和minCount都按默认值处理。<br/>设置为小于0的值时,按默认值显示。 |
......
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
> >
> ForEach/LazyForEach语句中,会计算展开所有子节点索引值。 > ForEach/LazyForEach语句中,会计算展开所有子节点索引值。
> >
> [if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载)发生变化以后,会更新子节点索引值。 > [if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)发生变化以后,会更新子节点索引值。
> >
> ListItemGroup作为一个整体计算一个索引值,ListItemGroup内部的ListItem不计算索引值。 > ListItemGroup作为一个整体计算一个索引值,ListItemGroup内部的ListItem不计算索引值。
> >
...@@ -54,7 +54,7 @@ List(value?:{space?: number&nbsp;|&nbsp;string, initialIndex?: number, scroller? ...@@ -54,7 +54,7 @@ List(value?:{space?: number&nbsp;|&nbsp;string, initialIndex?: number, scroller?
| listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。<br/>默认值:Axis.Vertical<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | listDirection | [Axis](ts-appendix-enums.md#axis) | 设置List组件排列方向。<br/>默认值:Axis.Vertical<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| divider | {<br/>strokeWidth:&nbsp;[Length](ts-types.md#length),<br/>color?:[ResourceColor](ts-types.md#resourcecolor),<br/>startMargin?:&nbsp;Length,<br/>endMargin?:&nbsp;Length<br/>}&nbsp;\|&nbsp;null | 设置ListItem分割线样式,不支持设置百分比,默认无分割线。<br/>- strokeWidth:&nbsp;分割线的线宽。<br/>- color:&nbsp;分割线的颜色。<br/>- startMargin:&nbsp;分割线与列表侧边起始端的距离。<br/>- endMargin:&nbsp;分割线与列表侧边结束端的距离。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>endMargin +startMargin 不能超过列宽度。 <br/>startMargin和endMargin不支持设置百分比。<br/>List的分割线画在主轴方向两个子组件之间,第一个子组件上方和最后一个子组件下方不会绘制分割线。<br/>多列模式下,ListItem与ListItem之间的分割线起始边距从每一列的交叉轴方向起始边开始计算,其他情况从List交叉轴方向起始边开始计算。 | | divider | {<br/>strokeWidth:&nbsp;[Length](ts-types.md#length),<br/>color?:[ResourceColor](ts-types.md#resourcecolor),<br/>startMargin?:&nbsp;Length,<br/>endMargin?:&nbsp;Length<br/>}&nbsp;\|&nbsp;null | 设置ListItem分割线样式,不支持设置百分比,默认无分割线。<br/>- strokeWidth:&nbsp;分割线的线宽。<br/>- color:&nbsp;分割线的颜色。<br/>- startMargin:&nbsp;分割线与列表侧边起始端的距离。<br/>- endMargin:&nbsp;分割线与列表侧边结束端的距离。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>endMargin +startMargin 不能超过列宽度。 <br/>startMargin和endMargin不支持设置百分比。<br/>List的分割线画在主轴方向两个子组件之间,第一个子组件上方和最后一个子组件下方不会绘制分割线。<br/>多列模式下,ListItem与ListItem之间的分割线起始边距从每一列的交叉轴方向起始边开始计算,其他情况从List交叉轴方向起始边开始计算。 |
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。<br/>默认值:BarState.Off<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>API version 9及以下版本默认值为BarState.Off,API version 10的默认值为BarState.Auto。 |
| cachedCount | number | 设置列表中ListItem/ListItemGroup的预加载数量,只在[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载)中生效,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来。具体使用可参考[减少应用白块说明](../../ui/ui-ts-performance-improvement-recommendation.md#减少应用滑动白块)<br/>默认值:1<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>单列模式下,会在List显示的ListItem前后各缓存cachedCount个ListItem。<br/>多列模式下, 会在List显示的ListItem前后各缓存cachedCount*列数个ListItem。 | | cachedCount | number | 设置列表中ListItem/ListItemGroup的预加载数量,只在[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md)中生效,其中ListItemGroup将作为一个整体进行计算,ListItemGroup中的所有ListItem会一次性全部加载出来。具体使用可参考[减少应用白块说明](../../ui/arkts-performance-improvement-recommendation.md#减少应用滑动白块)<br/>默认值:1<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>单列模式下,会在List显示的ListItem前后各缓存cachedCount个ListItem。<br/>多列模式下, 会在List显示的ListItem前后各缓存cachedCount*列数个ListItem。 |
| editMode<sup>(deprecated)</sup> | boolean | 声明当前List组件是否处于可编辑模式。<br/>从API version9开始废弃。<br/>默认值:false | | editMode<sup>(deprecated)</sup> | boolean | 声明当前List组件是否处于可编辑模式。<br/>从API version9开始废弃。<br/>默认值:false |
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果,支持弹簧效果和阴影效果。<br/>默认值:EdgeEffect.Spring<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | 设置组件的滑动效果,支持弹簧效果和阴影效果。<br/>默认值:EdgeEffect.Spring<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
| chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。<br/>默认值:false<br/>-&nbsp;false:不启用链式联动。<br/>-&nbsp;true:启用链式联动。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | chainAnimation | boolean | 设置当前List是否启用链式联动动效,开启后列表滑动以及顶部和底部拖拽时会有链式联动的效果。链式联动效果:List内的list-item间隔一定距离,在基本的滑动交互行为下,主动对象驱动从动对象进行联动,驱动效果遵循弹簧物理动效。<br/>默认值:false<br/>-&nbsp;false:不启用链式联动。<br/>-&nbsp;true:启用链式联动。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
> **说明:** > **说明:**
> >
> 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
## 接口 ## 接口
......
...@@ -19,8 +19,8 @@ Refresh\(value: \{ refreshing: boolean, offset?: number&nbsp;|&nbsp;string , fr ...@@ -19,8 +19,8 @@ Refresh\(value: \{ refreshing: boolean, offset?: number&nbsp;|&nbsp;string , fr
**参数:** **参数:**
| 参数 | 参数名 | 必填 | 参数描述 | | 参数 | 参数名 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- |
| refreshing | boolean | 是 | 当前组件是否正在刷新。<br/>该参数支持[$$](../../quick-start/arkts-restrictions-and-extensions.md#变量的双向绑定)双向绑定变量。 | | refreshing | boolean | 是 | 当前组件是否正在刷新。<br/>该参数支持[$$](../../quick-start/arkts-two-way-sync.md)双向绑定变量。 |
| offset | string&nbsp;\|&nbsp;number | 否 | 下拉起点距离组件顶部的距离。<br/>默认值:16,单位vp <br/>**说明:**<br/>不支持百分比,不支持负数 | | offset | string&nbsp;\|&nbsp;number | 否 | 下拉起点距离组件顶部的距离。<br/>默认值:16,单位vp <br/>**说明:**<br/>不支持百分比,不支持负数 |
| friction | number&nbsp;\|&nbsp;string | 否 | 下拉摩擦系数,取值范围为0到100。<br/>默认值:62<br/>-&nbsp;0表示下拉刷新容器不跟随手势下拉而下拉。<br/>-&nbsp;100表示下拉刷新容器紧紧跟随手势下拉而下拉。<br/>-&nbsp;数值越大,下拉刷新容器跟随手势下拉的反应越灵敏。 | | friction | number&nbsp;\|&nbsp;string | 否 | 下拉摩擦系数,取值范围为0到100。<br/>默认值:62<br/>-&nbsp;0表示下拉刷新容器不跟随手势下拉而下拉。<br/>-&nbsp;100表示下拉刷新容器紧紧跟随手势下拉而下拉。<br/>-&nbsp;数值越大,下拉刷新容器跟随手势下拉的反应越灵敏。 |
| builder | [CustomBuilder](ts-types.md#custombuilder8)<sup>10+</sup> | 否 | 下拉时,自定义刷新样式的组件。 | | builder | [CustomBuilder](ts-types.md#custombuilder8)<sup>10+</sup> | 否 | 下拉时,自定义刷新样式的组件。 |
...@@ -35,14 +35,14 @@ Refresh\(value: \{ refreshing: boolean, offset?: number&nbsp;|&nbsp;string , fr ...@@ -35,14 +35,14 @@ Refresh\(value: \{ refreshing: boolean, offset?: number&nbsp;|&nbsp;string , fr
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | ---------------------------------------- | -------------------------------------- |
| onStateChange(callback: (state: [RefreshStatus](#refreshstatus枚举说明)) => void)| 当前刷新状态变更时,触发回调。<br/>-&nbsp;state:刷新状态。 | | onStateChange(callback: (state: [RefreshStatus](#refreshstatus枚举说明)) => void) | 当前刷新状态变更时,触发回调。<br/>-&nbsp;state:刷新状态。 |
| onRefreshing(callback: () => void)| 进入刷新状态时触发回调。 | | onRefreshing(callback: () => void) | 进入刷新状态时触发回调。 |
## RefreshStatus枚举说明 ## RefreshStatus枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | -------- | -------------------- |
| Inactive | 默认未下拉状态。 | | Inactive | 默认未下拉状态。 |
| Drag | 下拉中,下拉距离小于刷新距离。 | | Drag | 下拉中,下拉距离小于刷新距离。 |
| OverDrag | 下拉中,下拉距离超过刷新距离。 | | OverDrag | 下拉中,下拉距离超过刷新距离。 |
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
> **说明:** > **说明:**
> >
> - 子组件类型:系统组件和自定义组件,不支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > - 子组件类型:系统组件和自定义组件,不支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
> - 子组件个数:必须且仅包含2个子组件。 > - 子组件个数:必须且仅包含2个子组件。
> - 子组件个数异常时:3个或以上子组件,显示第一个和第二个。1个子组件,显示侧边栏,内容区为空白。 > - 子组件个数异常时:3个或以上子组件,显示第一个和第二个。1个子组件,显示侧边栏,内容区为空白。
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
> **说明:** > **说明:**
> >
> 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > 子组件类型:系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
## 接口 ## 接口
......
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
> **说明:** > **说明:**
> >
> 可内置系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control.md#条件渲染)、[ForEach](../../quick-start/arkts-rendering-control.md#循环渲染)和[LazyForEach](../../quick-start/arkts-rendering-control.md#数据懒加载))。 > 可内置系统组件和自定义组件,支持渲染控制类型([if/else](../../quick-start/arkts-rendering-control-ifelse.md)、[ForEach](../../quick-start/arkts-rendering-control-foreach.md)和[LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md))。
## 接口 ## 接口
......
...@@ -19,7 +19,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ...@@ -19,7 +19,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | | ----------- | --------------------------------- | ---- | ---------------------------------------- |
| barPosition | BarPosition | 否 | 设置Tabs的页签位置。<br/>默认值:BarPosition.Start | | barPosition | BarPosition | 否 | 设置Tabs的页签位置。<br/>默认值:BarPosition.Start |
| index | number | 否 | 设置初始页签索引。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时按默认值显示。<br/>可选值为[0, TabContent子节点数量-1]。<br/>设置不同值时,默认生效切换动效,可以设置animationDuration为0关闭动画。 | | index | number | 否 | 设置初始页签索引。<br/>默认值:0<br/>**说明:** <br/>设置为小于0的值时按默认值显示。<br/>可选值为[0, TabContent子节点数量-1]。<br/>设置不同值时,默认生效切换动效,可以设置animationDuration为0关闭动画。 |
| controller | [TabsController](#tabscontroller) | 否 | 设置Tabs控制器。 | | controller | [TabsController](#tabscontroller) | 否 | 设置Tabs控制器。 |
...@@ -27,7 +27,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ...@@ -27,7 +27,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
## BarPosition枚举说明 ## BarPosition枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | ----- | ---------------------------------------- |
| Start | vertical属性方法设置为true时,页签位于容器左侧;vertical属性方法设置为false时,页签位于容器顶部。 | | Start | vertical属性方法设置为true时,页签位于容器左侧;vertical属性方法设置为false时,页签位于容器顶部。 |
| End | vertical属性方法设置为true时,页签位于容器右侧;vertical属性方法设置为false时,页签位于容器底部。 | | End | vertical属性方法设置为true时,页签位于容器右侧;vertical属性方法设置为false时,页签位于容器底部。 |
...@@ -37,20 +37,20 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ...@@ -37,20 +37,20 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性: 除支持[通用属性](ts-universal-attributes-size.md)外,还支持以下属性:
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| -------- | -------- | -------- | | ------------------------ | ---------------------------------------- | ---------------------------------------- |
| vertical | boolean | 设置为false是为横向Tabs,设置为true时为纵向Tabs。<br/>默认值:false | | vertical | boolean | 设置为false是为横向Tabs,设置为true时为纵向Tabs。<br/>默认值:false |
| scrollable | boolean | 设置为true时可以通过滑动页面进行页面切换,为false时不可滑动切换页面。<br/>默认值:true | | scrollable | boolean | 设置为true时可以通过滑动页面进行页面切换,为false时不可滑动切换页面。<br/>默认值:true |
| barMode | BarMode | TabBar布局模式,具体描述见BarMode枚举说明。<br/>默认值:BarMode.Fixed | | barMode | BarMode | TabBar布局模式,具体描述见BarMode枚举说明。<br/>默认值:BarMode.Fixed |
| barWidth | number&nbsp;\|&nbsp;Length<sup>8+</sup> | TabBar的宽度值。<br/>**说明:** <br/>设置为小于0或大于Tabs宽度值时,按默认值显示。 | | barWidth | number&nbsp;\|&nbsp;Length<sup>8+</sup> | TabBar的宽度值。<br/>**说明:** <br/>设置为小于0或大于Tabs宽度值时,按默认值显示。 |
| barHeight | number&nbsp;\|&nbsp;Length<sup>8+</sup> | TabBar的高度值。<br/>**说明:** <br/>设置为小于0或大于Tabs宽度值时,按默认值显示。 | | barHeight | number&nbsp;\|&nbsp;Length<sup>8+</sup> | TabBar的高度值。<br/>**说明:** <br/>设置为小于0或大于Tabs宽度值时,按默认值显示。 |
| animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。<br/>默认值:300 <br/>**说明:** <br/>设置为小于0或百分比时,按默认值显示。| | animationDuration | number | TabContent滑动动画时长。不设置时,点击切换页签无动画,滑动切换有动画;设置时,点击切换和滑动切换都有动画。<br/>默认值:300 <br/>**说明:** <br/>设置为小于0或百分比时,按默认值显示。 |
| divider<sup>10+</sup> | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。<br/> DividerStyle: 分割线的样式;<br/> null: 不显示分割线。 | | divider<sup>10+</sup> | [DividerStyle](#dividerstyle10对象说明) \| null | 用于设置区分TabBar和TabContent的分割线样式设置分割线样式,默认不显示分割线。<br/> DividerStyle: 分割线的样式;<br/> null: 不显示分割线。 |
| FadingEdge<sup>10+</sup> | boolean | 设置页签超过容器宽度时是否渐隐消失<br />默认值:true | | FadingEdge<sup>10+</sup> | boolean | 设置页签超过容器宽度时是否渐隐消失<br />默认值:true |
## DividerStyle<sup>10+</sup>对象说明 ## DividerStyle<sup>10+</sup>对象说明
| 名称 | 参数类型 | 必填 | 描述 | | 名称 | 参数类型 | 必填 | 描述 |
| -------- | -------- | -------- | -------- | | ----------- | ---------------------------------------- | ---- | ----------------------------------- |
| strokeWidth | [Length](ts-types.md#length) | 是 | 分割线的线宽。 | | strokeWidth | [Length](ts-types.md#length) | 是 | 分割线的线宽。 |
| color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 分割线的颜色。<br/>默认值:#33182431 | | color | [ResourceColor](ts-types.md#resourcecolor) | 否 | 分割线的颜色。<br/>默认值:#33182431 |
| startMargin | [Length](ts-types.md#length) | 否 | 分割线与侧边栏顶端的距离。<br/>默认值:0.0<br/>单位:vp | | startMargin | [Length](ts-types.md#length) | 否 | 分割线与侧边栏顶端的距离。<br/>默认值:0.0<br/>单位:vp |
...@@ -59,7 +59,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ...@@ -59,7 +59,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
## BarMode枚举说明 ## BarMode枚举说明
| 名称 | 描述 | | 名称 | 描述 |
| -------- | -------- | | ---------- | ---------------------------------------- |
| Scrollable | 每一个TabBar均使用实际布局宽度,超过总长度(横向Tabs的barWidth,纵向Tabs的barHeight)后可滑动。 | | Scrollable | 每一个TabBar均使用实际布局宽度,超过总长度(横向Tabs的barWidth,纵向Tabs的barHeight)后可滑动。 |
| Fixed | 所有TabBar平均分配barWidth宽度(纵向时平均分配barHeight高度)。 | | Fixed | 所有TabBar平均分配barWidth宽度(纵向时平均分配barHeight高度)。 |
...@@ -68,8 +68,8 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr ...@@ -68,8 +68,8 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件: 除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------- | -------- | | ---------------------------------------- | ---------------------------------------- |
| onChange(event:&nbsp;(index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | Tab页签切换后触发的事件。<br>-&nbsp;index:当前显示的index索引,索引从0开始计算。<br/>触发该事件的条件:<br/>1、TabContent支持滑动时,组件触发滑动时触发。<br/>2、通过[控制器](#tabscontroller)API接口调用。<br/>3、通过[状态变量](../../quick-start/arkts-state-mgmt-page-level.md)构造的属性值进行修改。<br/>4、通过页签处点击触发。 | | onChange(event:&nbsp;(index:&nbsp;number)&nbsp;=&gt;&nbsp;void) | Tab页签切换后触发的事件。<br>-&nbsp;index:当前显示的index索引,索引从0开始计算。<br/>触发该事件的条件:<br/>1、TabContent支持滑动时,组件触发滑动时触发。<br/>2、通过[控制器](#tabscontroller)API接口调用。<br/>3、通过[状态变量](../../quick-start/arkts-state.md)构造的属性值进行修改。<br/>4、通过页签处点击触发。 |
## TabsController ## TabsController
...@@ -90,7 +90,7 @@ changeIndex(value: number): void ...@@ -90,7 +90,7 @@ changeIndex(value: number): void
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| -------- | -------- | -------- | -------- | | ----- | ------ | ---- | ---------------------------------------- |
| value | number | 是 | 页签在Tabs里的索引值,索引值从0开始。<br/>**说明:** <br/>设置小于0或大于最大数量的值时,该事件失效。 | | value | number | 是 | 页签在Tabs里的索引值,索引值从0开始。<br/>**说明:** <br/>设置小于0或大于最大数量的值时,该事件失效。 |
......
...@@ -17,18 +17,18 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, aut ...@@ -17,18 +17,18 @@ CustomDialogController(value:{builder: CustomDialog, cancel?: () =&gt; void, aut
**参数:** **参数:**
| 参数名 | 参数类型 | 必填 | 参数描述 | | 参数名 | 参数类型 | 必填 | 参数描述 |
| ---------------------- | ---------------------------------------- | ------------------------- | ---------------------- | | ----------------------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| builder | [CustomDialog](../../quick-start/arkts-dynamic-ui-elememt-building.md#customdialog) | 是 | 自定义弹窗内容构造器。 | | builder | CustomDialog | 是 | 自定义弹窗内容构造器。 |
| cancel | ()&nbsp;=&gt;&nbsp;void | 否 | 点击遮障层退出时的回调。 | | cancel | ()&nbsp;=&gt;&nbsp;void | 否 | 点击遮障层退出时的回调。 |
| autoCancel | boolean | 否 | 是否允许点击遮障层退出。<br>默认值:true | | autoCancel | boolean | 否 | 是否允许点击遮障层退出。<br>默认值:true |
| alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default | | alignment | [DialogAlignment](ts-methods-alert-dialog-box.md#dialogalignment枚举说明) | 否 | 弹窗在竖直方向上的对齐方式。<br>默认值:DialogAlignment.Default |
| offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 | | offset | [Offset](ts-types.md#offset) | 否 | 弹窗相对alignment所在位置的偏移量。 |
| customStyle | boolean | 否 | 弹窗容器样式是否自定义。<br>默认值:false,弹窗容器的宽度根据栅格系统自适应,不跟随子节点;高度自适应子节点,最大为窗口高度的90%;圆角为24vp。 | | customStyle | boolean | 否 | 弹窗容器样式是否自定义。<br>默认值:false,弹窗容器的宽度根据栅格系统自适应,不跟随子节点;高度自适应子节点,最大为窗口高度的90%;圆角为24vp。 |
| gridCount<sup>8+</sup> | number | 否 | 弹窗宽度占[栅格宽度](../../ui/ui-ts-layout-grid-container-new.md)的个数。<br>默认值为4,异常值按默认值处理,最大栅格数为系统最大栅格数。 | | gridCount<sup>8+</sup> | number | 否 | 弹窗宽度占[栅格宽度](../../ui/arkts-layout-development-grid-layout.md)的个数。<br>默认值为4,异常值按默认值处理,最大栅格数为系统最大栅格数。 |
| maskColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | 否 | 自定义蒙层颜色。<br>默认值: 0x33000000 | | maskColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | 否 | 自定义蒙层颜色。<br>默认值: 0x33000000 |
| openAnimation<sup>10+</sup> | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗弹出的动画效果相关参数。<br>注意:当iterations为奇数,playMode设置为Reverse,动画结束时,弹窗不显示。 | | openAnimation<sup>10+</sup> | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗弹出的动画效果相关参数。<br>注意:当iterations为奇数,playMode设置为Reverse,动画结束时,弹窗不显示。 |
| closeAniamtion<sup>10+</sup>| [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗关闭的动画效果相关参数。 | | closeAniamtion<sup>10+</sup> | [AnimateParam](ts-explicit-animation.md#animateparam对象说明) | 否 | 自定义设置弹窗关闭的动画效果相关参数。 |
| showInSubWindow<sup>10+</sup>| boolean | 否 | 是否在子窗口显示弹窗。<br>默认值:false,在子窗口不显示弹窗。<br>**说明**:showInSubWindow为true的弹窗无法触发显示另一个showInSubWindow为true的弹窗。 | | showInSubWindow<sup>10+</sup> | boolean | 否 | 是否在子窗口显示弹窗。<br>默认值:false,在子窗口不显示弹窗。<br>**说明**:showInSubWindow为true的弹窗无法触发显示另一个showInSubWindow为true的弹窗。 |
## CustomDialogController ## CustomDialogController
......
...@@ -352,7 +352,7 @@ let res: boolean = AppStorage.IsMutable('simpleProp'); ...@@ -352,7 +352,7 @@ let res: boolean = AppStorage.IsMutable('simpleProp');
static Size(): number static Size(): number
返回LocalStorage中的属性数量。 返回AppStorage中的属性数量。
**返回值:** **返回值:**
...@@ -487,7 +487,7 @@ let res1: boolean = storage.set('PropB', 47); // false ...@@ -487,7 +487,7 @@ let res1: boolean = storage.set('PropB', 47); // false
### setOrCreate<sup>9+</sup> ### setOrCreate<sup>9+</sup>
setOrCreate&lt;T&gt;(propName: string, newValue?: T): boolean setOrCreate&lt;T&gt;(propName: string, newValue: T): boolean
propName如果已经在LocalStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,初始化为newValue。 propName如果已经在LocalStorage中存在,则设置propName对应是属性的值为newValue。如果不存在,则创建propName属性,初始化为newValue。
...@@ -496,7 +496,7 @@ propName如果已经在LocalStorage中存在,则设置propName对应是属性 ...@@ -496,7 +496,7 @@ propName如果已经在LocalStorage中存在,则设置propName对应是属性
| 参数名 | 类型 | 必填 | 参数描述 | | 参数名 | 类型 | 必填 | 参数描述 |
| -------- | ------ | ---- | ----------------------- | | -------- | ------ | ---- | ----------------------- |
| propName | string | 是 | LocalStorage中的属性名。 | | propName | string | 是 | LocalStorage中的属性名。 |
| newValue | T | | 属性值,不能为undefined或者null。 | | newValue | T | | 属性值,不能为undefined或者null。 |
**返回值:** **返回值:**
...@@ -573,7 +573,7 @@ var link2: SubscribedAbstractProperty<number> = storage.setAndLink('PropA', 50); ...@@ -573,7 +573,7 @@ var link2: SubscribedAbstractProperty<number> = storage.setAndLink('PropA', 50);
### prop<sup>9+</sup> ### prop<sup>9+</sup>
prop&lt;T&gt;(propName: string): SubscribedAbstractProperty&lt;T&gt; prop&lt;S&gt;(propName: string): SubscribedAbstractProperty&lt;S&gt;
如果给定的propName在LocalStorage存在,则返回与LocalStorage中propName对应属性的单向绑定数据。如果LocalStorage中不存在propName,则返回undefined。单向绑定数据的修改不会被同步回LocalStorage中。 如果给定的propName在LocalStorage存在,则返回与LocalStorage中propName对应属性的单向绑定数据。如果LocalStorage中不存在propName,则返回undefined。单向绑定数据的修改不会被同步回LocalStorage中。
...@@ -587,7 +587,7 @@ prop&lt;T&gt;(propName: string): SubscribedAbstractProperty&lt;T&gt; ...@@ -587,7 +587,7 @@ prop&lt;T&gt;(propName: string): SubscribedAbstractProperty&lt;T&gt;
| 类型 | 描述 | | 类型 | 描述 |
| ----------------------------------- | ---------------------------------------- | | ----------------------------------- | ---------------------------------------- |
| SubscribedAbstractProperty&lt;T&gt; | SubscribedAbstractProperty&lt;T&gt;的实例,如果AppStorage不存在对应的propName,在返回undefined。 | | SubscribedAbstractProperty&lt;S&gt; | SubscribedAbstractProperty&lt;S&gt;的实例,如果AppStorage不存在对应的propName,在返回undefined。 |
```ts ```ts
...@@ -600,7 +600,7 @@ prop1.set(1); // one-way sync: prop1.get()=1; but prop2.get() == 47 ...@@ -600,7 +600,7 @@ prop1.set(1); // one-way sync: prop1.get()=1; but prop2.get() == 47
### setAndProp<sup>9+</sup> ### setAndProp<sup>9+</sup>
setAndProp&lt;T&gt;(propName: string, defaultValue: T): SubscribedAbstractProperty&lt;T&gt; setAndProp&lt;S&gt;(propName: string, defaultValue: S): SubscribedAbstractProperty&lt;S&gt;
propName在LocalStorage存在,则返回该propName对应的属性的单向绑定数据。如果不存在,则使用defaultValue在LocalStorage创建和初始化propName对应的属性,返回其单向绑定数据。 propName在LocalStorage存在,则返回该propName对应的属性的单向绑定数据。如果不存在,则使用defaultValue在LocalStorage创建和初始化propName对应的属性,返回其单向绑定数据。
...@@ -609,13 +609,13 @@ propName在LocalStorage存在,则返回该propName对应的属性的单向绑 ...@@ -609,13 +609,13 @@ propName在LocalStorage存在,则返回该propName对应的属性的单向绑
| 参数名 | 类型 | 必填 | 参数描述 | | 参数名 | 类型 | 必填 | 参数描述 |
| ------------ | ------ | ---- | ---------------------------------------- | | ------------ | ------ | ---- | ---------------------------------------- |
| propName | string | 是 | LocalStorage中的属性名。 | | propName | string | 是 | LocalStorage中的属性名。 |
| defaultValue | T | 是 | 当propName在AppStorage中不存在,使用default在AppStorage中初始化对应的propName。 | | defaultValue | S | 是 | 当propName在AppStorage中不存在,使用default在AppStorage中初始化对应的propName。 |
**返回值:** **返回值:**
| 类型 | 描述 | | 类型 | 描述 |
| ----------------------------------- | ---------------------------------------- | | ----------------------------------- | ---------------------------------------- |
| SubscribedAbstractProperty&lt;T&gt; | SubscribedAbstractProperty&lt;T&gt;的实例,和AppStorage中propName对应属性的单向绑定的数据。 | | SubscribedAbstractProperty&lt;S&gt; | SubscribedAbstractProperty&lt;S&gt;的实例,和AppStorage中propName对应属性的单向绑定的数据。 |
```ts ```ts
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
| 名称 | 参数类型 | 描述 | | 名称 | 参数类型 | 描述 |
| ---------- | ---------------------------- | ------------------------------------------ | | ---------- | ---------------------------- | ------------------------------------------ |
| visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../quick-start/arkts-rendering-control.md#条件渲染)代替。<br>默认值:Visibility.Visible<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 | | visibility | [Visibility](ts-appendix-enums.md#visibility) | 控制当前组件显示或隐藏。注意,即使组件处于隐藏状态,在页面刷新时仍存在重新创建过程,因此当对性能有严格要求时建议使用[条件渲染](../../quick-start/arkts-rendering-control-ifelse.md)代替。<br>默认值:Visibility.Visible<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
## 示例 ## 示例
......
...@@ -60,4 +60,4 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下: ...@@ -60,4 +60,4 @@ JS服务卡片(entry/src/main/js/Widget)的典型开发目录结构如下:
FA卡片需要在应用配置文件config.json中进行配置。详细的配置内容请参考[FA卡片配置文件说明](../../application-models/widget-development-fa.md#配置卡片配置文件) FA卡片需要在应用配置文件config.json中进行配置。详细的配置内容请参考[FA卡片配置文件说明](../../application-models/widget-development-fa.md#配置卡片配置文件)
Stage卡片需要在应用配置文件module.json5中的extensionAbilities标签下,配置ExtensionAbility相关信息。详细的配置内容请参考[Stage卡片配置文件说明](../../application-models/widget-development-stage.md#配置卡片配置文件) Stage卡片需要在应用配置文件module.json5中的extensionAbilities标签下,配置ExtensionAbility相关信息。详细的配置内容请参考[Stage卡片配置文件说明](../../application-models/arkts-ui-widget-configuration.md)
\ No newline at end of file
...@@ -1767,3 +1767,13 @@ ...@@ -1767,3 +1767,13 @@
**授权方式**:system_grant **授权方式**:system_grant
**ACL使能**:TRUE **ACL使能**:TRUE
## ohos.permission.PROXY_AUTHORIZATION_URI
允许应用代理授权URI。
**权限级别**:system_basic
**授权方式**:system_grant
**ACL使能**:FALSE
# 焦点事件(毕雪峰 00579046) # 焦点事件
## 基本概念 ## 基本概念
- 焦点 - 焦点
指向当前应用界面上唯一的一个可交互元素,当用户使用键盘、电视遥控器、车机摇杆/旋钮等非指向性输入设备与应用程序进行间接交互时,基于焦点的导航和交互是重要的输入手段。 指向当前应用界面上唯一的一个可交互元素,当用户使用键盘、电视遥控器、车机摇杆/旋钮等非指向性输入设备与应用程序进行间接交互时,基于焦点的导航和交互是重要的输入手段。
- 默认焦点 - 默认焦点
应用打开或切换页面后,若当前页上存在可获焦的组件,则树形结构的组件树中第一个可获焦的组件默认获得焦点。可以使用[自定义默认焦点](#自定义默认焦点)进行自定义指定。 应用打开或切换页面后,若当前页上存在可获焦的组件,则树形结构的组件树中第一个可获焦的组件默认获得焦点。可以使用[自定义默认焦点](#自定义默认焦点)进行自定义指定。
- 获焦 - 获焦
指组件获得了焦点,同一时刻,应用中最多只有1个末端组件是获焦的,且此时它的所有祖宗组件(整个组件链)均是获焦的。当期望某个组件获焦,须确保该组件及其所有的祖宗节点均是可获焦的([focusable](#设置组件是否获焦)属性为true)。 指组件获得了焦点,同一时刻,应用中最多只有1个末端组件是获焦的,且此时它的所有祖宗组件(整个组件链)均是获焦的。当期望某个组件获焦,须确保该组件及其所有的祖宗节点均是可获焦的([focusable](#设置组件是否获焦)属性为true)。
- 失焦 - 失焦
指组件从获焦状态变成了非获焦状态,失去了焦点。组件失焦时,它的所有祖宗组件(失焦组件链)与新的获焦组件链不相同的节点都会失焦。 指组件从获焦状态变成了非获焦状态,失去了焦点。组件失焦时,它的所有祖宗组件(失焦组件链)与新的获焦组件链不相同的节点都会失焦。
- 走焦 - 走焦
表示焦点在当前应用中转移的过程,走焦会带来原焦点组件的失焦和新焦点组件的获焦。应用中焦点发生变化的方式按行为可分为两类: 表示焦点在当前应用中转移的过程,走焦会带来原焦点组件的失焦和新焦点组件的获焦。应用中焦点发生变化的方式按行为可分为两类:
- 主动走焦:指开发者/用户主观的行为导致焦点移动,包含:外接键盘上按下TAB/方向键、使用[requestFocus](#focuscontrolrequestfocus)主动给指定组件申请焦点、组件[focusOnTouch](#focusontouch)属性为true后点击组件。 - 主动走焦:指开发者/用户主观的行为导致焦点移动,包含:外接键盘上按下TAB/方向键、使用[requestFocus](#focuscontrolrequestfocus)主动给指定组件申请焦点、组件[focusOnTouch](#focusontouch)属性为true后点击组件。
- 被动走焦:指组件焦点因其他操作被动的转移焦点,此特性为焦点系统默认行为,无法由开发者自由设定,例如当使用if-else语句将处于获焦的组件删除/将处于获焦的组件(或其父组件)置成不可获焦时、当页面切换时。 - 被动走焦:指组件焦点因其他操作被动的转移焦点,此特性为焦点系统默认行为,无法由开发者自由设定,例如当使用if-else语句将处于获焦的组件删除/将处于获焦的组件(或其父组件)置成不可获焦时、当页面切换时。
- 焦点态 - 焦点态
获焦组件的样式,不同组件的焦点态样式大同小异,默认情况下焦点态不显示,仅使用外接键盘按下TAB键/方向键时才会触发焦点态样式出现。首次触发焦点态显示的TAB键/方向键不会触发走焦。当应用接收到点击事件时(包括手指触屏的按下事件和鼠标左键的按下事件),自动隐藏焦点态样式。焦点态样式由后端组件定义,开发者无法修改。 获焦组件的样式,不同组件的焦点态样式大同小异,默认情况下焦点态不显示,仅使用外接键盘按下TAB键/方向键时才会触发焦点态样式出现。首次触发焦点态显示的TAB键/方向键不会触发走焦。当应用接收到点击事件时(包括手指触屏的按下事件和鼠标左键的按下事件),自动隐藏焦点态样式。焦点态样式由后端组件定义,开发者无法修改。
......
...@@ -140,7 +140,7 @@ Grid() { ...@@ -140,7 +140,7 @@ Grid() {
网格布局采用二维布局的方式组织其内部元素,如下图所示。 网格布局采用二维布局的方式组织其内部元素,如下图所示。
**图7** 通用办公服务   **图7** 通用办公服务  
![zh-cn_image_0000001563060729](figures/zh-cn_image_0000001563060729.png) ![zh-cn_image_0000001563060729](figures/zh-cn_image_0000001563060729.png)
...@@ -206,9 +206,10 @@ struct OfficeService { ...@@ -206,9 +206,10 @@ struct OfficeService {
在两个网格单元之间的网格横向间距称为行间距,网格纵向间距称为列间距,如下图所示。 在两个网格单元之间的网格横向间距称为行间距,网格纵向间距称为列间距,如下图所示。
**图8** 网格的行列间距   **图8** 网格的行列间距  
![zh-cn_image_0000001511580908](figures/zh-cn_image_0000001511580908.png) ![zh-cn_image_0000001511580908](figures/zh-cn_image_0000001511580908.png)
通过Grid的rowsGap和columnsGap可以设置网格布局的行列间距。在图5所示的计算器中,行间距为15vp,列间距为10vp。 通过Grid的rowsGap和columnsGap可以设置网格布局的行列间距。在图5所示的计算器中,行间距为15vp,列间距为10vp。
...@@ -225,7 +226,7 @@ Grid() { ...@@ -225,7 +226,7 @@ Grid() {
可滚动的网格布局常用在文件管理、购物或视频列表等页面中,如下图所示。在设置Grid的行列数量与占比时,如果仅设置行、列数量与占比中的一个,即仅设置rowsTemplate或仅设置columnsTemplate属性,网格单元按照设置的方向排列,超出Grid显示区域后,Grid拥有可滚动能力。 可滚动的网格布局常用在文件管理、购物或视频列表等页面中,如下图所示。在设置Grid的行列数量与占比时,如果仅设置行、列数量与占比中的一个,即仅设置rowsTemplate或仅设置columnsTemplate属性,网格单元按照设置的方向排列,超出Grid显示区域后,Grid拥有可滚动能力。
**图9** 横向可滚动网格布局 **图9** 横向可滚动网格布局
![zh-cn_image_0000001511740512](figures/zh-cn_image_0000001511740512.gif) ![zh-cn_image_0000001511740512](figures/zh-cn_image_0000001511740512.gif)
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
列表是一种复杂的容器,当列表项达到一定数量,内容超过屏幕大小时,可以自动提供滚动功能。它适合用于呈现同类数据类型或数据类型集,例如图片和文本。在列表中显示数据集合是许多应用程序中的常见要求(如通讯录、音乐列表、购物清单等)。 列表是一种复杂的容器,当列表项达到一定数量,内容超过屏幕大小时,可以自动提供滚动功能。它适合用于呈现同类数据类型或数据类型集,例如图片和文本。在列表中显示数据集合是许多应用程序中的常见要求(如通讯录、音乐列表、购物清单等)。
使用列表可以轻松高效地显示结构化、可滚动的信息。通过在[List](../reference/arkui-ts/ts-container-list.md/)组件中按垂直或者水平方向线性排列子组件[ListItemGroup](../reference/arkui-ts/ts-container-listitemgroup.md/)[ListItem](../reference/arkui-ts/ts-container-listitem.md),为列表中的行或列提供单个视图,或使用[循环渲染](../quick-start/arkts-rendering-control-foreach.md)迭代一组行或列,或混合任意数量的单个视图和ForEach结构,构建一个列表。List组件支持使用条件渲染、循环渲染、懒加载等[渲染控制](../quick-start/arkts-rendering-control-overview.md)方式生成子组件。 使用列表可以轻松高效地显示结构化、可滚动的信息。通过在[List](../reference/arkui-ts/ts-container-list.md)组件中按垂直或者水平方向线性排列子组件[ListItemGroup](../reference/arkui-ts/ts-container-listitemgroup.md)[ListItem](../reference/arkui-ts/ts-container-listitem.md),为列表中的行或列提供单个视图,或使用[循环渲染](../quick-start/arkts-rendering-control-foreach.md)迭代一组行或列,或混合任意数量的单个视图和ForEach结构,构建一个列表。List组件支持使用条件渲染、循环渲染、懒加载等[渲染控制](../quick-start/arkts-rendering-control-overview.md)方式生成子组件。
## 布局与约束 ## 布局与约束
...@@ -27,7 +27,7 @@ ListItemGroup用于列表数据的分组展示,其子组件也是ListItem。Li ...@@ -27,7 +27,7 @@ ListItemGroup用于列表数据的分组展示,其子组件也是ListItem。Li
### 布局 ### 布局
List除了提供垂直和水平布局能力、超出屏幕时可以滚动的自适应[延伸能力](../key-features/multi-device-app-dev/adaptive-layout.md/#%E5%BB%B6%E4%BC%B8%E8%83%BD%E5%8A%9B)之外,还提供了自适应交叉轴方向上排列个数的布局能力。 List除了提供垂直和水平布局能力、超出屏幕时可以滚动的自适应[延伸能力](../key-features/multi-device-app-dev/adaptive-layout.md)之外,还提供了自适应交叉轴方向上排列个数的布局能力。
利用垂直布局能力可以构建单列或者多列垂直滚动列表,如下图所示。 利用垂直布局能力可以构建单列或者多列垂直滚动列表,如下图所示。
...@@ -95,7 +95,7 @@ List() { ...@@ -95,7 +95,7 @@ List() {
List组件的交叉轴布局可以通过lanes和alignListItem属性进行设置,lanes属性用于确定交叉轴排列的列表项数量,alignListItem用于设置子组件在交叉轴方向的对齐方式。 List组件的交叉轴布局可以通过lanes和alignListItem属性进行设置,lanes属性用于确定交叉轴排列的列表项数量,alignListItem用于设置子组件在交叉轴方向的对齐方式。
List组件的lanes属性通常用于在不同尺寸的设备自适应构建不同行数或列数的列表,即一次开发、多端部署的场景,例如[歌单列表](../key-features/multi-device-app-dev/music-album-page.md#%E6%AD%8C%E5%8D%95%E5%88%97%E8%A1%A8)。lanes属性的取值类型是"number | [LengthConstrain](../reference/arkui-ts/ts-types.md/#lengthconstrain)",即整数或者LengthConstrain类型。以垂直列表为例,如果将lanes属性设为2,表示构建的是一个两列的垂直列表,如图2中右图所示。lanes的默认值为1,即默认情况下,垂直列表的列数是1。 List组件的lanes属性通常用于在不同尺寸的设备自适应构建不同行数或列数的列表,即一次开发、多端部署的场景,例如[歌单列表](../key-features/multi-device-app-dev/music-album-page.md)。lanes属性的取值类型是"number | [LengthConstrain](../reference/arkui-ts/ts-types.md#lengthconstrain)",即整数或者LengthConstrain类型。以垂直列表为例,如果将lanes属性设为2,表示构建的是一个两列的垂直列表,如图2中右图所示。lanes的默认值为1,即默认情况下,垂直列表的列数是1。
```ts ```ts
...@@ -318,7 +318,7 @@ List() { ...@@ -318,7 +318,7 @@ List() {
![zh-cn_image_0000001511740544](figures/zh-cn_image_0000001511740544.gif) ![zh-cn_image_0000001511740544](figures/zh-cn_image_0000001511740544.gif)
在使用List组件时,可通过scrollBar属性控制列表滚动条的显示。scrollBar的取值类型为[BarState](../reference/arkui-ts/ts-appendix-enums.md/#barstate),当取值为BarState.Auto表示按需显示滚动条。此时,当触摸到滚动条区域时显示控件,可上下拖拽滚动条快速浏览内容,拖拽时会变粗。若不进行任何操作,2秒后滚动条自动消失。 在使用List组件时,可通过scrollBar属性控制列表滚动条的显示。scrollBar的取值类型为[BarState](../reference/arkui-ts/ts-appendix-enums.md#barstate),当取值为BarState.Auto表示按需显示滚动条。此时,当触摸到滚动条区域时显示控件,可上下拖拽滚动条快速浏览内容,拖拽时会变粗。若不进行任何操作,2秒后滚动条自动消失。
```ts ```ts
...@@ -478,7 +478,7 @@ struct ContactsList { ...@@ -478,7 +478,7 @@ struct ContactsList {
![zh-cn_image_0000001511900520](figures/zh-cn_image_0000001511900520.gif) ![zh-cn_image_0000001511900520](figures/zh-cn_image_0000001511900520.gif)
List组件初始化时,可以通过scroller参数绑定一个[Scroller](../reference/arkui-ts/ts-container-scroll.md/#scroller)对象,进行列表的滚动控制。例如,用户在新闻应用中,点击新闻页面底部的返回顶部按钮时,就可以通过Scroller对象的scrollToIndex方法使列表滚动到指定的列表项索引位置。 List组件初始化时,可以通过scroller参数绑定一个[Scroller](../reference/arkui-ts/ts-container-scroll.md#scroller)对象,进行列表的滚动控制。例如,用户在新闻应用中,点击新闻页面底部的返回顶部按钮时,就可以通过Scroller对象的scrollToIndex方法使列表滚动到指定的列表项索引位置。
首先,需要创建一个Scroller的对象listScroller。 首先,需要创建一个Scroller的对象listScroller。
...@@ -516,11 +516,11 @@ Stack({ alignContent: Alignment.BottomEnd }) { ...@@ -516,11 +516,11 @@ Stack({ alignContent: Alignment.BottomEnd }) {
除了字母索引之外,滚动列表结合多级分类索引在应用开发过程中也很常见,例如购物应用的商品分类页面,多级分类也需要监听列表的滚动位置。 除了字母索引之外,滚动列表结合多级分类索引在应用开发过程中也很常见,例如购物应用的商品分类页面,多级分类也需要监听列表的滚动位置。
**图14** 字母索引响应联系人列表滚动   **图14** 字母索引响应联系人列表滚动  
![zh-cn_image_0000001563060769](figures/zh-cn_image_0000001563060769.gif) ![zh-cn_image_0000001563060769](figures/zh-cn_image_0000001563060769.gif)
如上图所示,当联系人列表从A滚动到B时,右侧索引栏也需要同步从选中A状态变成选中B状态。此场景可以通过监听List组件的onScrollIndex事件来实现,右侧索引栏需要使用字母表索引组件[AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md/) 如上图所示,当联系人列表从A滚动到B时,右侧索引栏也需要同步从选中A状态变成选中B状态。此场景可以通过监听List组件的onScrollIndex事件来实现,右侧索引栏需要使用字母表索引组件[AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md)
在列表滚动时,根据列表此时所在的索引值位置firstIndex,重新计算字母索引栏对应字母的位置selectedIndex。由于AlphabetIndexer组件通过selected属性设置了选中项索引值,当selectedIndex变化时会触发AlphabetIndexer组件重新渲染,从而显示为选中对应字母的状态。 在列表滚动时,根据列表此时所在的索引值位置firstIndex,重新计算字母索引栏对应字母的位置selectedIndex。由于AlphabetIndexer组件通过selected属性设置了选中项索引值,当selectedIndex变化时会触发AlphabetIndexer组件重新渲染,从而显示为选中对应字母的状态。
...@@ -566,9 +566,10 @@ struct ContactsList { ...@@ -566,9 +566,10 @@ struct ContactsList {
侧滑菜单在许多应用中都很常见。例如,通讯类应用通常会给消息列表提供侧滑删除功能,即用户可以通过向左侧滑列表的某一项,再点击删除按钮删除消息,如下图所示。 侧滑菜单在许多应用中都很常见。例如,通讯类应用通常会给消息列表提供侧滑删除功能,即用户可以通过向左侧滑列表的某一项,再点击删除按钮删除消息,如下图所示。
**图15** 侧滑删除列表项   **图15** 侧滑删除列表项  
![zh-cn_image_0000001563060773](figures/zh-cn_image_0000001563060773.gif) ![zh-cn_image_0000001563060773](figures/zh-cn_image_0000001563060773.gif)
ListItem的swipeAction属性可用于实现列表项的左右滑动功能。swipeAction属性方法初始化时有必填参数SwipeActionOptions,其中,start参数表示设置列表项右滑时起始端滑出的组件,end参数表示设置列表项左滑时尾端滑出的组件。 ListItem的swipeAction属性可用于实现列表项的左右滑动功能。swipeAction属性方法初始化时有必填参数SwipeActionOptions,其中,start参数表示设置列表项右滑时起始端滑出的组件,end参数表示设置列表项左滑时尾端滑出的组件。
在消息列表中,end参数表示设置ListItem左滑时尾端划出自定义组件,即删除按钮。在初始化end方法时,将滑动列表项的索引传入删除按钮组件,当用户点击删除按钮时,可以根据索引值来删除列表项对应的数据,从而实现侧滑删除功能。 在消息列表中,end参数表示设置ListItem左滑时尾端划出自定义组件,即删除按钮。在初始化end方法时,将滑动列表项的索引传入删除按钮组件,当用户点击删除按钮时,可以根据索引值来删除列表项对应的数据,从而实现侧滑删除功能。
...@@ -620,7 +621,7 @@ struct MessageList { ...@@ -620,7 +621,7 @@ struct MessageList {
![zh-cn_image_0000001511580952](figures/zh-cn_image_0000001511580952.png) ![zh-cn_image_0000001511580952](figures/zh-cn_image_0000001511580952.png)
在ListItem中使用[Badge](../reference/arkui-ts/ts-container-badge.md/)组件可实现给列表项添加标记功能。Badge是可以附加在单个组件上用于信息标记的容器组件。 在ListItem中使用[Badge](../reference/arkui-ts/ts-container-badge.md)组件可实现给列表项添加标记功能。Badge是可以附加在单个组件上用于信息标记的容器组件。
在消息列表中,若希望在联系人头像右上角添加标记,可在实现消息列表项ListItem的联系人头像时,将头像Image组件作为Badge的子组件。 在消息列表中,若希望在联系人头像右上角添加标记,可在实现消息列表项ListItem的联系人头像时,将头像Image组件作为Badge的子组件。
...@@ -642,7 +643,7 @@ Badge({ ...@@ -642,7 +643,7 @@ Badge({
## 下拉刷新与上拉加载 ## 下拉刷新与上拉加载
页面的下拉刷新与上拉加载功能在移动应用中十分常见,例如,新闻页面的内容刷新和加载。这两种操作的原理都是通过响应用户的[触摸事件](../reference/arkui-ts/ts-universal-events-touch.md/),在顶部或者底部显示一个刷新或加载视图,完成后再将此视图隐藏。 页面的下拉刷新与上拉加载功能在移动应用中十分常见,例如,新闻页面的内容刷新和加载。这两种操作的原理都是通过响应用户的[触摸事件](../reference/arkui-ts/ts-universal-events-touch.md),在顶部或者底部显示一个刷新或加载视图,完成后再将此视图隐藏。
以下拉刷新为例,其实现主要分成三步: 以下拉刷新为例,其实现主要分成三步:
...@@ -838,5 +839,3 @@ List() { ...@@ -838,5 +839,3 @@ List() {
- [新闻数据加载](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/NewsDataArkTS) - [新闻数据加载](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/NewsDataArkTS)
- [音乐专辑页](../key-features/multi-device-app-dev/music-album-page.md) - [音乐专辑页](../key-features/multi-device-app-dev/music-album-page.md)
[../reference/arkui-ts/ts-container-listitem.md]:
\ No newline at end of file
...@@ -5,24 +5,31 @@ ...@@ -5,24 +5,31 @@
- **ArkTS** - **ArkTS**
ArkTS是UI开发语言,基于TypeScript(简称TS)语言扩展而来,是TS的超集。扩展能力包含各种装饰器、自定义组件、UI描述机制。状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get-started.md) ArkTS是UI开发语言,基于TypeScript(简称TS)语言扩展而来,是TS的超集。扩展能力包含各种装饰器、自定义组件、UI描述机制。状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。ArkTS语言的基础知识请参考[学习ArkTS语言](../quick-start/arkts-get-started.md)
- **布局** - **布局**
布局是UI的必要元素,它定义了组件在界面中的位置。ArkUI框架提供了多种布局方式,除了基础的线性布局、层叠布局、弹性布局、相对布局、栅格布局外,也提供了相对复杂的列表、宫格、轮播。 布局是UI的必要元素,它定义了组件在界面中的位置。ArkUI框架提供了多种布局方式,除了基础的线性布局、层叠布局、弹性布局、相对布局、栅格布局外,也提供了相对复杂的列表、宫格、轮播。
- **组件** - **组件**
组件是UI的必要元素,形成了在界面中的样子,由框架直接提供的称为**系统组件**,由开发者定义的称为**自定义组件**。系统内置组件包括按钮、单选框、进度条、文本等。开发者可以通过链式调用的方式设置系统内置组件的渲染效果。开发者可以将系统内置组件组合为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,具有更强的工程性。 组件是UI的必要元素,形成了在界面中的样子,由框架直接提供的称为**系统组件**,由开发者定义的称为**自定义组件**。系统内置组件包括按钮、单选框、进度条、文本等。开发者可以通过链式调用的方式设置系统内置组件的渲染效果。开发者可以将系统内置组件组合为自定义组件,通过这种方式将页面组件化为一个个独立的UI单元,实现页面不同单元的独立创建、开发和复用,具有更强的工程性。
- **页面路由和组件导航** - **页面路由和组件导航**
应用可能包含多个页面,可通过页面路由实现页面间的跳转。一个页面内可能存在组件间的导航如典型的分栏,可通过导航组件实现组件间的导航。 应用可能包含多个页面,可通过页面路由实现页面间的跳转。一个页面内可能存在组件间的导航如典型的分栏,可通过导航组件实现组件间的导航。
- **图形** - **图形**
方舟开发框架提供了多种类型图片的显示能力和多种自定义绘制的能力,以满足开发者的自定义绘图需求,支持绘制形状、填充颜色、绘制文本、变形与裁剪、嵌入图片等。 方舟开发框架提供了多种类型图片的显示能力和多种自定义绘制的能力,以满足开发者的自定义绘图需求,支持绘制形状、填充颜色、绘制文本、变形与裁剪、嵌入图片等。
- **动画** - **动画**
动画是UI的重要元素之一。优秀的动画设计能够极大地提升用户体验,框架提供了丰富的动画能力,除了组件内置动画效果外,还包括属性动画、显式动画、自定义转场动画以及动画API等,开发者可以通过封装的物理模型或者调用动画能力API来实现自定义动画轨迹。 动画是UI的重要元素之一。优秀的动画设计能够极大地提升用户体验,框架提供了丰富的动画能力,除了组件内置动画效果外,还包括属性动画、显式动画、自定义转场动画以及动画API等,开发者可以通过封装的物理模型或者调用动画能力API来实现自定义动画轨迹。
- **交互事件** - **交互事件**
交互事件是UI和用户交互的必要元素。方舟开发框架提供了多种交互事件,除了触摸事件、鼠标事件、键盘按键事件、焦点事件等通用事件外,还包括基于通用事件进行进一步识别的手势事件。手势事件有单一手势如点击手势、长按手势、拖动手势、捏合手势、旋转手势、滑动手势,以及通过单一手势事件进行组合的组合手势事件。 交互事件是UI和用户交互的必要元素。方舟开发框架提供了多种交互事件,除了触摸事件、鼠标事件、键盘按键事件、焦点事件等通用事件外,还包括基于通用事件进行进一步识别的手势事件。手势事件有单一手势如点击手势、长按手势、拖动手势、捏合手势、旋转手势、滑动手势,以及通过单一手势事件进行组合的组合手势事件。
......
...@@ -43,7 +43,7 @@ struct WebComponent { ...@@ -43,7 +43,7 @@ struct WebComponent {
### Cache ### Cache
使用[cacheMode()](../reference/arkui-ts/ts-basic-components-web.md#cachemode%E6%9E%9A%E4%B8%BE%E8%AF%B4%E6%98%8E)配置页面资源的缓存模式,Web组件为开发者提供四种缓存模式,分别为: 使用[cacheMode()](../reference/arkui-ts/ts-basic-components-web.md#cachemode)配置页面资源的缓存模式,Web组件为开发者提供四种缓存模式,分别为:
- Default : 优先使用未过期的缓存,如果缓存不存在,则从网络获取。 - Default : 优先使用未过期的缓存,如果缓存不存在,则从网络获取。
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
Web组件支持对前端页面进行深色模式配置。 Web组件支持对前端页面进行深色模式配置。
- 通过[darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9)接口可以配置不同的深色模式,[WebDarkMode.Off](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9%E6%9E%9A%E4%B8%BE%E8%AF%B4%E6%98%8E)模式表示关闭深色模式。[WebDarkMode.On](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9%E6%9E%9A%E4%B8%BE%E8%AF%B4%E6%98%8E)表示开启深色模式,并且深色模式跟随前端页面。[WebDarkMode.Auto](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9%E6%9E%9A%E4%B8%BE%E8%AF%B4%E6%98%8E)表示开启深色模式,并且深色模式跟随系统。 - 通过[darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9)接口可以配置不同的深色模式,[WebDarkMode.Off](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9)模式表示关闭深色模式。[WebDarkMode.On](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9)表示开启深色模式,并且深色模式跟随前端页面。[WebDarkMode.Auto](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9)表示开启深色模式,并且深色模式跟随系统。
在下面的示例中, 通过[darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9)接口将页面深色模式配置为跟随系统。 在下面的示例中, 通过[darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9)接口将页面深色模式配置为跟随系统。
```ts ```ts
......
...@@ -110,3 +110,5 @@ ...@@ -110,3 +110,5 @@
- [充电限流限压定制开发指导](subsys-power-charge-current-voltage-limit.md) - [充电限流限压定制开发指导](subsys-power-charge-current-voltage-limit.md)
- [充电类型定制开发指导](subsys-power-charge-type-customization.md) - [充电类型定制开发指导](subsys-power-charge-type-customization.md)
- [关机充电动画开发指导](subsys-power-poweroff-charge-animation.md) - [关机充电动画开发指导](subsys-power-poweroff-charge-animation.md)
- 耗电统计
- [耗电统计定制开发指导](subsys-power-stats-power-average-customization.md)
# 耗电统计定制开发指导
## 概述
### 简介
OpenHarmony默认提供了耗电统计的特性。由于不同产品的硬件规格是不同的,各个硬件的耗电基准也不同。产品希望根据产品的设计规格来定制耗电基准。OpenHarmony提供了耗电基准的定制方式,产品定制开发者可根据产品的设计规格来定制。
### 基本概念
耗电统计:在用户使用设备的过程中,各种软硬件服务会通过[HiSysEvent](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-overview.md)上报软硬件的使用事件,根据这些事件可以计算软硬件的使用时长,然后基于硬件的耗电基准,统计所得软硬件的耗电量。
耗电基准:产品硬件在各种状态下的基准耗电量(单位:毫安时),如相机打开时的基准耗电量,CPU在各种频率下的基准耗电量等。
### 约束与限制
按照[配置策略组件介绍](https://gitee.com/openharmony/customization_config_policy)的说明,设定产品定制的配置路径,需要根据配置策略决定。本开发指南中的定制路径以`/vendor`进行举例,请开发者根据具体的产品配置策略,修改定制路径。
## 开发指导
### 搭建环境
设备要求:
标准系统开发板,如DAYU200/Hi3516DV300开源套件。
环境要求:
Linux调测环境,相关要求和配置可参考《[快速入门](../quick-start/quickstart-overview.md)》。
### 开发步骤
本文以[DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568)为例介绍耗电统计的定制方法。
1. 在产品目录[(vendor/hihope/rk3568)](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568)下创建battery_statistics文件夹。
2. 参考[默认耗电统计配置文件夹](https://gitee.com/openharmony/powermgr_battery_statistics/tree/master/services/profile)创建目标文件夹,并安装到`vendor/hihope/rk3568/battery_statistics`目录,文件格式如下:
```shell
profile
├── BUILD.gn # BUILD.gn文件
└── power_average.json # 耗电统计配置文件,包含硬件的耗电基准
```
3. 参考[默认耗电统计配置文件夹中的power_average.json](https://gitee.com/openharmony/powermgr_battery_statistics/blob/master/services/profile/power_average.json)编写定制的power_average.json,包含定制后的耗电基准。详细说明如下:
**表1** 耗电基准配置项说明
| 配置项 | 硬件类型 | 数据类型 | 描述 |
|----------|------|---------|-------------------------------------------------------------------------|
| alarm_on | - | Double | 定时器Timer触发一次耗电量,即基准耗电量,用于计算系统或者应用对Timer使用的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 触发次数 * 耗电基准 |
| bluetooth_br_on | Bluetooth | Double | 蓝牙开启时的基准耗电量,用于计算蓝牙开启过程中的功耗。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| bluetooth_br_scan | Bluetooth | Double | 蓝牙扫描状态的基准耗电量,用于计算蓝牙扫描过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| bluetooth_ble_on | Bluetooth | Double | 低功耗蓝牙开启时的基准耗电量,用于计算蓝牙开启过程中的功耗。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| bluetooth_ble_scan | Bluetooth | Double | 低功耗蓝牙扫描状态的基准耗电量,用于计算蓝牙扫描过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| wifi_on | WIFI | Double | WIFI开启时的基准耗电量,用于计算WIFI开启过程中的功耗。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| wifi_scan | WIFI | Double | WIFI扫描一次耗电量,用于计算WIFI扫描时的功耗。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 触发次数 * 耗电基准 |
| radio_on | Phone | Double数组 | 通话开启时的基准耗电量,数组形式,用于配置不同等级信号强度的基准耗电量。默认配置包括4个信号等级的基准耗电信息。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| radio_data | Phone | Double数组 | 网络开启时的基准耗电量,数组形式,用于配置不同等级信号强度的基准耗电量。默认配置包括4个信号等级的基准耗电信息。<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| camera_on | Camera | Double | 相机开启时的基准耗电量,用于计算相机开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| flashlight_on | Flashlight | Double | 闪光灯开启时的基准耗电量,用于计算闪光灯开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| gnss_on | GNSS | Double | GNSS(Global Navigation Satellite System)开启时的基准耗电量,用于计算GNSS开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| sensor_gravity_on | Gravity Sensor | Double | 重力传感器开启时的基准耗电量,用于计算重力传感器开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| sensor_proximity_on | Proximity Sensor | Double | 接近传感器开启时的基准耗电量,用于计算接近传感器开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| audio_on | Audio | Double | 音响开启时的基准耗电量,用于计算音响开启过程中的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| screen_on<br/>screen_brightness | Screen | Double | screen_on:屏幕的基础状态下的基准耗电量(不包括屏幕亮度产生的耗电量);<br/>screen_brightness:屏幕亮度每提升一个等级,需要额外增加的基准耗电量;<br/>例如:假定条件,screen_on = 90,screen_brightness = 2,屏幕亮度为100,屏幕亮度100时的基准耗电量:90 + 2 * 100 = 290<br/>-&nbsp;功耗类型:硬件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| cpu_awake | CPU | Double | CPU唤醒锁持锁状态时的基准耗电量,用于计算CPU唤醒锁持锁状态时的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| cpu_idle | CPU | Double | CPU空闲状态时的基准耗电量,用于计算CPU空闲状态的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| cpu_suspend | CPU | Double | CPU休眠状态时的基准耗电量,用于计算CPU休眠状态的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| cpu_active | CPU | Double | CPU活动状态时的基准耗电量,用于计算CPU活动状态的功耗。<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
| cpu_clusters<br/>cpu_speed_clusterX | CPU | Double数组 | cpu_clusters:cpu cluster的基准耗电量,数组形式,用于配置不同cpu cluster基准耗电量。默认配置包括3个不同cpu cluster基准耗电信息。<br/>cpu_speed_clusterX:cpu cluster不同频率的基准耗电量,数组形式。X代表序号,默认配置中X的范围0~2,对应cpu_clusters数组大小。例如:默认配置cpu_clusters的数组大小为3,顺序对应配置项cpu_speed_cluster0、cpu_speed_cluster1、cpu_speed_cluster2。<br/>-&nbsp;扩展性:可扩展<br/>-&nbsp;功耗类型:软件功耗<br/>-&nbsp;统计方法:耗电量 = 持续时间 * 耗电基准 |
>说明:表格中描述的硬件类型为真实硬件名称,不代表耗电统计类型,具体的耗电统计类型,请参考[ConsumptionType](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-batteryStatistics.md#consumptiontype)定义。
4. 参考[默认耗电统计配置文件夹中的BUILD.gn](https://gitee.com/openharmony/powermgr_battery_statistics/blob/master/services/profile/BUILD.gn)编写BUILD.gn文件,将power_average.json打包安装到`/vendor/etc/profile`目录下,例如:
```shell
import("//build/ohos.gni") # 引用build/ohos.gni
# Install power_average.json to /vendor/etc/profile/power_average.json
ohos_prebuilt_etc("power_average_config") { # 自定义名称,例子中用名:power_average_config
source = "power_average.json"
relative_install_dir = "profile"
install_images = [ chipset_base_dir ] # 安装到vendor目录下的必要配置,chipset_base_dir = “vendor”, 如果不配置,默认安装到system目录
part_name = "product_rk3568" # part_name为product_rk3568,以实现后续编译
}
```
5. 将编译目标添加到`/vendor/hihope/rk3568`目录下[ohos.build](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/ohos.build)的“module_list”中,例如:
```json
{
"parts": {
"product_rk3568": {
"module_list": [
"//vendor/hihope/rk3568/default_app_config:default_app_config",
"//vendor/hihope/rk3568/image_conf:custom_image_conf",
"//vendor/hihope/rk3568/battery_statistics/profile:power_average_config", # 添加power_average_config的编译
"//vendor/hihope/rk3568/preinstall-config:preinstall-config",
"//vendor/hihope/rk3568/resourceschedule:resourceschedule",
"//vendor/hihope/rk3568/etc:product_etc_conf"
]
}
},
"subsystem": "product_hihope"
}
```
“//vendor/hihope/rk3568/power/battery_statistics/”为文件夹路径,“profile”为创建的文件夹名字,“power_average_config”为编译目标。
6. 参考《[快速入门](../quick-start/quickstart-overview.md)》编译定制版本,编译命令如下:
```shell
./build.sh --product-name rk3568 --ccache
```
7. 将定制版本烧录到DAYU200开发板中。
### 调测验证
1. 开机后,先进入shell命令行。
```shell
hdc shell
```
2. 执行下列命令,观察vendor目录下power_average.json是否创建成功。
```shell
ls -l /vendor/etc/profile/
```
创建成功,在/vendor/etc/profile/存在配置文件power_average.json。
```shell
# ls -l /vendor/etc/profile/
total 4
-rw-r--r-- 1 root root 1446 2023-03-26 16:47 power_average.json
#
```
3. 如果创建成功,执行下列命令,观察vendor目录下power_average.json中的信息是否与定制信息一致。
```shell
cat /vendor/etc/profile/power_average.json
```
4. 如果信息一致,执行执行下列命令,观察console输出。
```shell
hidumper -s 3304 -a -poweraverage
```
5. console输出的是定制后的耗电基准信息,如:
定制耗电统计之前,使用默认耗电基准为:
```shell
# hidumper -s 3304 -a -poweraverage
-------------------------------[ability]-------------------------------
----------------------------------BatteryStatisticsService---------------------------------
POWER AVERAGE CONFIGATION DUMP:
······(省略其他,只显示camera的配置)
camera_on : 810.000000
······
```
本节以“camera_on”:3000为例(默认值为810),更改之后:
```shell
# hidumper -s 3304 -a -poweraverage
-------------------------------[ability]-------------------------------
----------------------------------BatteryStatisticsService---------------------------------
POWER AVERAGE CONFIGATION DUMP:
······(省略其他,只显示camera的配置)
camera_on : 3000.000000 # 修改后,“camera_on”:3000
······
```
6. 耗电统计配置文件定制成功后,耗电统计会根据定制的耗电基准进行计算。
7. 通过batterystatistics模块提供的[JS API](https://gitee.com/openharmony/interface_sdk-js/blob/master/api/@ohos.batteryStatistics.d.ts)[Inner API](https://gitee.com/openharmony/powermgr_battery_statistics/blob/master/interfaces/innerkits/include/battery_stats_client.h)可以获得详细的耗电信息,验证定制的耗电基准。
## 参考
开发过程中可参考的配置文件路径:[系统默认耗电统计配置源码路径](https://gitee.com/openharmony/powermgr_battery_statistics/tree/master/services/profile)
默认打包路径:/system/etc/profile
定制路径:/vendor/etc/profile
...@@ -475,6 +475,9 @@ ...@@ -475,6 +475,9 @@
- [HiChecker开发指导](subsystems/subsys-dfx-hichecker.md) - [HiChecker开发指导](subsystems/subsys-dfx-hichecker.md)
- [Faultlogger开发指导](subsystems/subsys-dfx-faultlogger.md) - [Faultlogger开发指导](subsystems/subsys-dfx-faultlogger.md)
- [Hiview开发指导](subsystems/subsys-dfx-hiview.md) - [Hiview开发指导](subsystems/subsys-dfx-hiview.md)
- 电源
- 耗电统计
- [耗电统计定制开发指导](subsystems/subsys-power-stats-power-average-customization.md)
- 专题 - 专题
- HPM Part - HPM Part
......
...@@ -45,9 +45,9 @@ ArkUI适配了根据资源名称获取资源的能力。 ...@@ -45,9 +45,9 @@ ArkUI适配了根据资源名称获取资源的能力。
| 软件 | 版本 | 备注 | | 软件 | 版本 | 备注 |
| -------- | -------- | -------- | | -------- | -------- | -------- |
| OpenHarmony | 3.2 Beta5 | NA | | OpenHarmony | 3.2 Beta5 | NA |
| Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。通过DevEco Studio默认获取的SDK为Public SDK。 | | Public SDK | Ohos_sdk_public 3.2.10.6 (API Version 9 Beta5) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。<br />通过DevEco Studio默认获取的SDK为Public SDK。 |
| HUAWEI DevEco Studio(可选) | *待发布* | OpenHarmony应用开发推荐使用。 | | HUAWEI DevEco Studio(可选) | 3.1 Beta1 | OpenHarmony应用开发推荐使用。 <br />[请点击此处获取](https://developer.harmonyos.com/cn/develop/deveco-studio#download) |
| HUAWEI DevEco Device Tool(可选) | *待发布* | OpenHarmony智能设备集成开发环境推荐使用。 | | HUAWEI DevEco Device Tool(可选) | 3.1 Beta2 | OpenHarmony智能设备集成开发环境推荐使用。 <br />[请点击此处获取](https://device.harmonyos.com/cn/develop/ide#download) |
## 源码获取 ## 源码获取
...@@ -137,9 +137,9 @@ ArkUI适配了根据资源名称获取资源的能力。 ...@@ -137,9 +137,9 @@ ArkUI适配了根据资源名称获取资源的能力。
### SDK变更 ### SDK变更
从本版本起,SDK仅发布提供Public SDK,也可通过DevEcoStudio下载使用 从本版本起,仅发布Public SDK,开发者可从镜像站点获取或通过DevEco Studio下载Public SDK用于应用开发
Full SDK需下载源码编译构建并替换使用,源码编译指导见[full-SDK编译指南](../application-dev/quick-start/full-sdk-compile-guide.md) 包含系统接口的全量SDK(Full SDK)需下载全量代码后编译构建出SDK文件,并在DevEco Studio中替换。通过源码编译Full SDK的指导请参见[Full-SDK编译指南](../application-dev/quick-start/full-sdk-compile-guide.md)
### 特性变更 ### 特性变更
...@@ -162,6 +162,11 @@ Full SDK需下载源码编译构建并替换使用,源码编译指导见[full- ...@@ -162,6 +162,11 @@ Full SDK需下载源码编译构建并替换使用,源码编译指导见[full-
| 文件存储 | - 新增应用文件统一URI处理能力。<br/>- 新增支持公共数据的临时授权和统一的打开入口。<br/>主要涉及以下需求:<br/>I687C8【新增能力】支持应用文件统一URI处理能力<br/>I64U8W【基础能力】支持公共数据的临时授权和统一open入口 | NA | | 文件存储 | - 新增应用文件统一URI处理能力。<br/>- 新增支持公共数据的临时授权和统一的打开入口。<br/>主要涉及以下需求:<br/>I687C8【新增能力】支持应用文件统一URI处理能力<br/>I64U8W【基础能力】支持公共数据的临时授权和统一open入口 | NA |
| 元能力 | - 新增常驻进程重启优化。<br/>- 支持卡片数据库切换。<br/>- 支持异步onConnected等能力。<br/>主要涉及以下需求:<br/>I65M3F 【基础能力】执行ShellCommand命令管控<br/>I65V83 【基础能力】ServiceExtensionAbility支持异步onConnected生命周期<br/>I61H21 【基础能力】卡片本地数据库切换<br/>I63UJ5 【元能力】【ability_runtime】API8及以前API 支持异常处理<br/>I6BDCW 【基础能力】应用加载禁止加载data目录下的代码<br/>I6BDDU 【基础能力】FA模型默认启动方式为Standard<br/>I6BDE2 【基础能力】常驻应用异常频繁重启保护 | NA | | 元能力 | - 新增常驻进程重启优化。<br/>- 支持卡片数据库切换。<br/>- 支持异步onConnected等能力。<br/>主要涉及以下需求:<br/>I65M3F 【基础能力】执行ShellCommand命令管控<br/>I65V83 【基础能力】ServiceExtensionAbility支持异步onConnected生命周期<br/>I61H21 【基础能力】卡片本地数据库切换<br/>I63UJ5 【元能力】【ability_runtime】API8及以前API 支持异常处理<br/>I6BDCW 【基础能力】应用加载禁止加载data目录下的代码<br/>I6BDDU 【基础能力】FA模型默认启动方式为Standard<br/>I6BDE2 【基础能力】常驻应用异常频繁重启保护 | NA |
API变更清单请参考:[API差异报告](api-change/v3.2-beta5/Readme.md)
各子系统API详细变更说明请参考:[变更说明](changelogs/v3.2-beta5/Readme.md)
### 芯片及开发板适配 ### 芯片及开发板适配
...@@ -174,16 +179,13 @@ Full SDK需下载源码编译构建并替换使用,源码编译指导见[full- ...@@ -174,16 +179,13 @@ Full SDK需下载源码编译构建并替换使用,源码编译指导见[full-
| 子系统 | 名称 | 简介 | 开发语言 | | 子系统 | 名称 | 简介 | 开发语言 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| web | [JS注入与执行](https://gitee.com/openharmony/applications_app_samples/tree/master/Web/RunJsInWeb) | 本示例基于H5游戏,通过ArkUI的button实现对游戏实现基本控制,展示webview的JS注入与执行能力,及native应用与H5的通信能力。 | ArkTs | | 媒体子系统 | [二维码扫描](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/media/Scan) | 本示例展示二维码扫描,从文件中选择二维码图片进行解析和读取,识别二维码信息。 | ArkTs |
| 媒体子系统 | [二维码扫描](https://gitee.com/openharmony/applications_app_samples/tree/master/media/QRCodeScan) | 本示例展示二维码扫描,从文件中选择二维码图片进行解析和读取,识别二维码信息。 | ArkTs | | ArkUI | [一多应用市场首页](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/MultiDeviceAppDev/AppMarket) | 本示例展示了应用市场首页,其在小窗口和大窗口有不同的显示效果,体现一次开发、多端部署的能力。 | ArkTs |
| ArkUI | [一多设置典型页面](https://gitee.com/openharmony/applications_app_samples/tree/master/MultiDeviceAppDev/Settings) | 本示例展示了设置应用的典型页面,其在小窗口和大窗口有不同的显示效果,体现一次开发、多端部署的能力。 | ArkTs | | 文件管理 | [文件管理](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/FileManager/FileIo) | 本示例主要展示了文件管理相关的功能,使用[mediaLibrary](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md)[userFileManager](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md)[fileio](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-fileio.md)等接口,实现了媒体库文件、应用沙箱内文件的添加和访问等功能。 | ArkTs |
| 文件管理 | [文件管理](https://gitee.com/openharmony/applications_app_samples/tree/master/FileManager/FileManager) | 本示例主要展示了文件管理相关的功能,使用[mediaLibrary](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-medialibrary.md)[userFileManager](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md)[fileio](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-fileio.md)等接口,实现了媒体库文件、应用沙箱内文件的添加和访问等功能。 | ArkTs | | 元能力 | [图库卡片](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Beta5/ability/GalleryForm) | 本示例是模拟图库卡片,实现对图库中的照片在卡片中显示,定时刷新卡片内容等功能。 | ArkTs |
| 媒体子系统 | [录屏](https://gitee.com/openharmony/applications_app_samples/tree/master/media/ScreenRecorder) | 该示例展示设备屏幕(含音频)录制功能。屏幕录制的主要工作是通过创建一个虚拟屏,捕获屏幕显示图形帧,完成视频编码并保存到文件中,帮助OEM设备厂家系统应用实现屏幕录制功能,也可以通过此应用抓取屏幕帧用于问题复现录制。 | ArkTs |
| 窗口子系统 | [屏幕探测](https://gitee.com/openharmony/applications_app_samples/tree/master/device/ScreenDetector) | 本示例实时监测连接的屏幕数量状态,支持创建至多5个虚拟屏幕,点击对应的屏幕矩形能显示该屏幕的相关属性。 | ArkTs |
| 元能力 | [Stage模型卡片小游戏](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormGame) | 本示例展示了如何通过Stage模型实现一个简单的游戏卡片。 | ArkTs |
请访问[Samples](https://gitee.com/openharmony/app_samples)仓了解更多信息。 请访问[Samples](https://gitee.com/openharmony/applications_app_samples)仓了解更多信息。
## 修复缺陷列表 ## 修复缺陷列表
......
# JS API差异报告
- [元能力](js-apidiff-ability.md)
- [帐号](js-apidiff-account.md)
- [应用](js-apidiff-application.md)
- [ArkUI](js-apidiff-arkui.md)
- [电源服务](js-apidiff-battery.md)
- [包管理](js-apidiff-bundle.md)
- [网络及通信](js-apidiff-communication.md)
- [语言编译器运行时](js-apidiff-compiler-and-runtime.md)
- [DFX](js-apidiff-dfx.md)
- [分布式数据](js-apidiff-distributed-data.md)
- [文件管理](js-apidiff-file-management.md)
- [Misc软件](js-apidiff-misc.md)
- [媒体服务](js-apidiff-multimedia.md)
- [事件与通知](js-apidiff-notification.md)
- [资源调度](js-apidiff-resource-scheduler.md)
- [安全](js-apidiff-security.md)
- [泛Sensor](js-apidiff-sensor.md)
- [启动](js-apidiff-start-up.md)
- [电话服务](js-apidiff-telephony.md)
- [测试服务](js-apidiff-unitest.md)
- [升级](js-apidiff-update.md)
- [USB服务](js-apidiff-usb.md)
- [用户IAM](js-apidiff-user-iam.md)
- [Web](js-apidiff-web.md)
- [窗口](js-apidiff-window.md)
# JS API差异报告
- [元能力](js-apidiff-ability.md)
- [无障碍](js-apidiff-accessibility.md)
- [帐号](js-apidiff-account.md)
- [应用](js-apidiff-application.md)
- [ArkUI](js-apidiff-arkui.md)
- [电源服务](js-apidiff-battery.md)
- [包管理](js-apidiff-bundle.md)
- [网络及通信](js-apidiff-communication.md)
- [语言编译器运行时](js-apidiff-compiler-and-runtime.md)
- [定制](js-apidiff-customization.md)
- [DFX](js-apidiff-dfx.md)
- [分布式数据](js-apidiff-distributed-data.md)
- [分布式硬件](js-apidiff-distributed-hardware.md)
- [文件管理](js-apidiff-file-management.md)
- [位置服务](js-apidiff-geolocation.md)
- [全球化](js-apidiff-global.md)
- [图形图像](js-apidiff-graphic.md)
- [Misc软件](js-apidiff-misc.md)
- [MSDP](js-apidiff-msdp.md)
- [多模输入](js-apidiff-multi-modal-input.md)
- [媒体服务](js-apidiff-multimedia.md)
- [事件与通知](js-apidiff-notification.md)
- [资源调度](js-apidiff-resource-scheduler.md)
- [安全](js-apidiff-security.md)
- [泛Sensor](js-apidiff-sensor.md)
- [启动](js-apidiff-start-up.md)
- [电话服务](js-apidiff-telephony.md)
- [测试服务](js-apidiff-unitest.md)
- [升级](js-apidiff-update.md)
- [USB服务](js-apidiff-usb.md)
- [用户IAM](js-apidiff-user-iam.md)
- [Web](js-apidiff-web.md)
- [窗口](js-apidiff-window.md)
# Readme # JS API差异报告
* JS API接口变更清单 - [元能力](js-apidiff-ability.md)
- [元能力](js-apidiff-ability.md) - [无障碍](js-apidiff-accessibility.md)
- [无障碍](js-apidiff-accessibility.md) - [帐号](js-apidiff-account.md)
- [帐号](js-apidiff-account.md) - [应用](js-apidiff-application.md)
- [应用](js-apidiff-application.md) - [ArkUI](js-apidiff-arkui.md)
- [ArkUI](js-apidiff-arkui.md) - [电源服务](js-apidiff-battery.md)
- [电源服务](js-apidiff-battery.md) - [包管理](js-apidiff-bundle.md)
- [包管理](js-apidiff-bundle.md) - [网络及通信](js-apidiff-communication.md)
- [网络及通信](js-apidiff-communication.md) - [语言编译器运行时](js-apidiff-compiler-and-runtime.md)
- [语言编译器运行时](js-apidiff-compiler-and-runtime.md) - [定制](js-apidiff-customization.md)
- [定制](js-apidiff-customization.md) - [DFX](js-apidiff-dfx.md)
- [DFX](js-apidiff-dfx.md) - [分布式数据](js-apidiff-distributed-data.md)
- [分布式数据](js-apidiff-distributed-data.md) - [分布式硬件](js-apidiff-distributed-hardware.md)
- [分布式硬件](js-apidiff-distributed-hardware.md) - [文件管理](js-apidiff-file-management.md)
- [文件管理](js-apidiff-file-management.md) - [位置服务](js-apidiff-geolocation.md)
- [位置服务](js-apidiff-geolocation.md) - [全球化](js-apidiff-global.md)
- [全球化](js-apidiff-global.md) - [Misc软件](js-apidiff-misc.md)
- [Misc软件](js-apidiff-misc.md) - [MSDP](js-apidiff-msdp.md)
- [MSDP](js-apidiff-msdp.md) - [多模输入](js-apidiff-multi-modal-input.md)
- [多模输入](js-apidiff-multi-modal-input.md) - [媒体服务](js-apidiff-multimedia.md)
- [媒体服务](js-apidiff-multimedia.md) - [事件与通知](js-apidiff-notification.md)
- [事件与通知](js-apidiff-notification.md) - [资源调度](js-apidiff-resource-scheduler.md)
- [资源调度](js-apidiff-resource-scheduler.md) - [安全](js-apidiff-security.md)
- [安全](js-apidiff-security.md) - [泛Sensor](js-apidiff-sensor.md)
- [泛Sensor](js-apidiff-sensor.md) - [启动](js-apidiff-start-up.md)
- [启动](js-apidiff-start-up.md) - [电话服务](js-apidiff-telephony.md)
- [电话服务](js-apidiff-telephony.md) - [测试服务](js-apidiff-unitest.md)
- [测试服务](js-apidiff-unitest.md) - [升级](js-apidiff-update.md)
- [升级](js-apidiff-update.md) - [USB服务](js-apidiff-usb.md)
- [USB服务](js-apidiff-usb.md) - [用户IAM](js-apidiff-user-iam.md)
- [用户IAM](js-apidiff-user-iam.md) - [Web](js-apidiff-web.md)
- [Web](js-apidiff-web.md) - [窗口](js-apidiff-window.md)
- [窗口](js-apidiff-window.md)
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册