diff --git a/CODEOWNERS b/CODEOWNERS
index b72c72a8ae022c5afcc7f3553ce039ef6c13547d..b9dc401e4f05c544e1d852ee80637dc4c9ae38f7 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -275,6 +275,8 @@ zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @RayShi
zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @RayShih
zh-cn/application-dev/reference/apis/js-apis-application-Want.md @RayShih
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
+zh-cn/application-dev/reference/apis/js-apis-inner-application-windowExtensionContext.md @ge-yafang
+zh-cn/application-dev/application-models/windowextensionability.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-appmanager.md @RayShih
zh-cn/application-dev/reference/apis/js-apis-arraylist.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
@@ -476,6 +478,7 @@ zh-cn/application-dev/reference/apis/js-apis-wifiext.md @RayShih
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-worker.md @ge-yafang
+zh-cn/application-dev/reference/apis/js-apis-taskpool.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @ningningW
zh-cn/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @ningningW
zh-cn/application-dev/reference/apis/js-apis-xml.md @ge-yafang
diff --git a/README_zh.md b/README_zh.md
index 386fa1d7449553f92f399839d947a0dacd4e18b8..6e71a0abd9fba5cbe4b4de47c77437d3a851aa45 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -18,7 +18,7 @@
- master:最新开发版本。
- - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。
+ - OpenHarmony 3.2 Beta5版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta5.md)了解版本详情。
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
diff --git a/en/application-dev/application-models/ability-startup-with-implicit-want.md b/en/application-dev/application-models/ability-startup-with-implicit-want.md
index f163b035c7b759fab03ee3fcd455e3dcb77b5515..6550e5c628c642cf227cfde5f74eef7b61c8a52b 100644
--- a/en/application-dev/application-models/ability-startup-with-implicit-want.md
+++ b/en/application-dev/application-models/ability-startup-with-implicit-want.md
@@ -73,4 +73,5 @@ The **module.json5** of a browser application is as follows:
4. If **type** in the passed **want** parameter is specified and is included in **type** under **skills**, the matching is successful.
2. When there are multiple matching applications, a dialog box is displayed for you to select one of them.
-
+
+ 
diff --git a/en/application-dev/application-models/application-context-stage.md b/en/application-dev/application-models/application-context-stage.md
index 8d49b7369bb93e26f4407313f2d9352acd7380e1..0bd91dbd92d4621dbd59fe4bbb77d40a8fbaa77f 100644
--- a/en/application-dev/application-models/application-context-stage.md
+++ b/en/application-dev/application-models/application-context-stage.md
@@ -6,10 +6,12 @@
[Context](../reference/apis/js-apis-inner-application-context.md) is the context of an object in an application. It provides basic information about the application, for example, **resourceManager**, **applicationInfo**, **dir** (application development path), and **area** (encrypted area). It also provides basic methods such as **createBundleContext()** and **getApplicationContext()**. The UIAbility component and ExtensionAbility derived class components have their own **Context** classes, for example, the base class **Context**, **ApplicationContext**, **AbilityStageContext**, **UIAbilityContext**, **ExtensionContext**, and **ServiceExtensionContext**.
- The figure below illustrates the inheritance relationship of contexts.
-
+
+ 
- The figure below illustrates the holding relationship of contexts.
-
+
+ 
- The following describes the information provided by different contexts.
- [UIAbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md): Each UIAbility has the **Context** attribute, which provides APIs to operate the ability, obtain the ability configuration, and more.
@@ -89,7 +91,8 @@ The following table describes the application development paths obtained from co
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.
**Figure 1** Application development paths obtained from context
-
+
+
- Obtain the application-level path through **ApplicationContext**. It is recommended that global application information be stored in this path. Files stored in this path will be deleted only when the application is uninstalled.
| Name| Path|
@@ -174,7 +177,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
>
> - 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).
>
-> - 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.
@@ -189,7 +192,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
// ...
}
}
-```
+ ```
- Call **createModuleContext(bundleName:string, moduleName:string)** to obtain the context of a specified module of another application. After obtaining the context, you can obtain the resource information of that module.
> **NOTE**
@@ -198,7 +201,7 @@ The base class **Context** provides the [createBundleContext(bundleName:string)]
>
> - 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).
>
-> - 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
import UIAbility from '@ohos.app.ability.UIAbility';
diff --git a/en/application-dev/application-models/data-share-via-want.md b/en/application-dev/application-models/data-share-via-want.md
index 4ecdf35ead5482d4b4b2e0d0a2a4544e75686612..c04bea2916647804b51022cee1853f3b5d0a7d90 100644
--- a/en/application-dev/application-models/data-share-via-want.md
+++ b/en/application-dev/application-models/data-share-via-want.md
@@ -67,7 +67,7 @@ Users often need to share data (such as a text or an image) from one application
For example, when **"ability.picker.type"** is **"application/pdf"**, **"ability.picker.fileNames"** is **"["APIs.pdf"]"**, and **"ability.picker.fileSizes"** is **"[350 \* 1024]"**, the application selector is displayed as follows:
-
+ 
In the preceding code, the **ability.want.params.INTENT** field is nested Want. In this field, **action** and **type** are used for implicit matching by the application selector. For details about implicit matching, see [Matching Rules of Implicit Want](explicit-implicit-want-mappings.md#matching-rules-of-implicit-want). After the user selects an application, the nested Want of the **ability.want.params.INTENT** field is passed to that application.
diff --git a/en/application-dev/application-models/explicit-implicit-want-mappings.md b/en/application-dev/application-models/explicit-implicit-want-mappings.md
index ccf33e07d1b389eb1246a89a377febb1e7d24a78..d2c44bb4b47eff6347d6b4a6c098feadb7a9eead 100644
--- a/en/application-dev/application-models/explicit-implicit-want-mappings.md
+++ b/en/application-dev/application-models/explicit-implicit-want-mappings.md
@@ -61,7 +61,8 @@ The system matches the [action](../reference/apis/js-apis-ability-wantConstant.m
- If **action** in the passed **want** parameter is specified, and **actions** under **skills** of an ability is specified but does not contain **action** in the passed **want** parameter, the matching fails.
**Figure 1** Matching rules of action in the want parameter
-
+
+ 
### Matching Rules of entities in the want Parameter
@@ -78,8 +79,9 @@ The system matches the [entities](../reference/apis/js-apis-ability-wantConstant
- 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
+
+ 
### Matching Rules of uri and type in the want Parameter
@@ -87,7 +89,8 @@ The system matches the [entities](../reference/apis/js-apis-ability-wantConstant
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
-
+
+
There are four combinations of **uri** and **type** settings. The matching rules are as follows:
@@ -113,7 +116,8 @@ To simplify the description, **uri** and **type** passed in the **want** paramet
Figure 4 Matching rules of uri and type in the want parameter
-
+
+
### Matching Rules of uri
diff --git a/en/application-dev/application-models/inter-device-interaction-hop-overview.md b/en/application-dev/application-models/inter-device-interaction-hop-overview.md
index 6b1fd28b489f0d6d891abd9dffa0bcaf0f1b9ead..8a6cb49f86ff60655037955aaba1b00a5ff40a17 100644
--- a/en/application-dev/application-models/inter-device-interaction-hop-overview.md
+++ b/en/application-dev/application-models/inter-device-interaction-hop-overview.md
@@ -35,8 +35,9 @@ OpenHarmony provides a set of APIs for you to implement continuation in your app
The following figure shows the continuation architecture.
- **Figure 1** Continuation architecture
-
+ **Figure 1** Continuation architecture
+
+ 
- Cross-device migration task management: The initiator accepts a migration request from the user, provides a migration entry, and displays the migration result. (This capability is unavailable yet.)
diff --git a/en/application-dev/application-models/uiability-data-sync-with-ui.md b/en/application-dev/application-models/uiability-data-sync-with-ui.md
index 981a9212892a8bc1a920ac929608685c3eafeb00..f53627e974a0f9b4b1323d7694f94e07ebf51753 100644
--- a/en/application-dev/application-models/uiability-data-sync-with-ui.md
+++ b/en/application-dev/application-models/uiability-data-sync-with-ui.md
@@ -92,7 +92,8 @@ Before using EventHub, you must obtain an EventHub object, which is provided by
**globalThis** is a global object inside the [ArkTS engine instance](thread-model-stage.md) and can be used by UIAbility, ExtensionAbility, and Page inside the engine. Therefore, you can use **globalThis** for data synchronization.
**Figure 1** Using globalThis for data synchronization
-
+
+ 
The following describes how to use **globalThis** in three scenarios. Precautions are provided as well.
@@ -209,6 +210,7 @@ To implement data synchronization between the UIAbility and ExtensionAbility com
### Precautions for Using globalThis
**Figure 2** Precautions for globalThis
+

- In the stage model, all the UIAbility components in a process share one ArkTS engine instance. When using **globalThis**, do not store objects with the same name. For example, if AbilityA and AbilityB use **globalThis** to store two objects with the same name, the object stored earlier will be overwritten.
diff --git a/en/application-dev/application-models/uiability-intra-device-interaction.md b/en/application-dev/application-models/uiability-intra-device-interaction.md
index ea6b8bbecfa4a9a4f5434fb0aa5aad6184f38c9f..78363a3a2b65bee17a2ea7524b2fe7180de38909 100644
--- a/en/application-dev/application-models/uiability-intra-device-interaction.md
+++ b/en/application-dev/application-models/uiability-intra-device-interaction.md
@@ -197,7 +197,7 @@ This section describes how to start the UIAbility of another application through
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
-
+ 
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**.
@@ -445,7 +445,7 @@ The following figure shows the ability call process.
**Figure 1** Ability call process
-
+
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
diff --git a/en/application-dev/application-models/uiability-launch-type.md b/en/application-dev/application-models/uiability-launch-type.md
index cda8307ddd3dae6f7cceac3fad134ef510d7383c..70c212ed46e769dbdf4e0c1fd347403c463f6004 100644
--- a/en/application-dev/application-models/uiability-launch-type.md
+++ b/en/application-dev/application-models/uiability-launch-type.md
@@ -19,7 +19,7 @@ Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbility
**Figure 1** Demonstration effect in singleton mode
-
+
> **NOTE**
>
@@ -49,7 +49,7 @@ In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-app
**Figure 2** Demonstration effect in standard mode
-
+
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
@@ -75,7 +75,7 @@ The **specified** mode is used in some special scenarios. For example, in a docu
**Figure 3** Demonstration effect in specified mode
-
+
For example, there are EntryAbility and SpecifiedAbility, and the launch type of SpecifiedAbility is set to **specified**. You are required to start SpecifiedAbility from EntryAbility.
diff --git a/en/application-dev/application-models/uiability-lifecycle.md b/en/application-dev/application-models/uiability-lifecycle.md
index 9ec701cbffd4da51098d5dc448addd88f26ee47e..57200abb8fbfb625e2e6c8999da5ad817e2e85b4 100644
--- a/en/application-dev/application-models/uiability-lifecycle.md
+++ b/en/application-dev/application-models/uiability-lifecycle.md
@@ -7,8 +7,9 @@ When a user opens, switches, and returns to an application, the UIAbility instan
The lifecycle of UIAbility has four states: **Create**, **Foreground**, **Background**, and **Destroy**, as shown in the figure below.
-**Figure 1** UIAbility lifecycle states
-
+**Figure 1** UIAbility lifecycle states
+
+
## Description of Lifecycle States
@@ -36,8 +37,9 @@ export default class EntryAbility extends UIAbility {
After the UIAbility instance is created but before it enters the **Foreground** state, the system creates a WindowStage instance and triggers the **onWindowStageCreate()** callback. You can set UI loading and WindowStage event subscription in the callback.
-**Figure 2** WindowStageCreate and WindowStageDestory
-
+**Figure 2** WindowStageCreate and WindowStageDestory
+
+
In the **onWindowStageCreate()** callback, use [loadContent()](../reference/apis/js-apis-window.md#loadcontent9-2) to set the page to be loaded, and call [on('windowStageEvent')](../reference/apis/js-apis-window.md#onwindowstageevent9) to subscribe to [WindowStage events](../reference/apis/js-apis-window.md#windowstageeventtype9), for example, having or losing focus, or becoming visible or invisible.
diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md
index f8239c64cf43a0df0acca0bc1ec0e3be914eecfe..21c79d517fc237cae9b9bab7d5347ffc82766d5a 100644
--- a/en/application-dev/application-models/want-overview.md
+++ b/en/application-dev/application-models/want-overview.md
@@ -5,8 +5,9 @@
[Want](../reference/apis/js-apis-app-ability-want.md) is used as the carrier to transfer information between application components. It is used as a parameter of **startAbility()** to specify the startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. For example, when UIAbilityA starts UIAbilityB and needs to transfer some data to UIAbilityB, it can use Want to transfer the data.
-**Figure 1** Want usage
-
+**Figure 1** Want usage
+
+
## Types of Want
diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md
index 95001df839e0d5ef56bc12126f0fdcd59c72db30..f0011c591effd0b65df7d1d7911c63907d6e73f8 100644
--- a/en/application-dev/database/database-datashare-guidelines.md
+++ b/en/application-dev/database/database-datashare-guidelines.md
@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|
-For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md).
+For details about the data provider APIs, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
**Table 2** APIs of the data consumer
@@ -29,7 +29,7 @@ For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataS
## When to Use
-There are two roles in **DataShare**:
+There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
@@ -38,16 +38,16 @@ Examples are given below.
### Data Provider Application Development (Only for System Applications)
-1. Import the dependencies.
+1. Import dependencies.
```ts
import Extension from '@ohos.application.DataShareExtensionAbility';
- import rdb from '@ohos.data.rdb';
+ import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
-2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API.
+2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.
@@ -64,13 +64,14 @@ Examples are given below.
export default class DataShareExtAbility extends Extension {
private rdbStore_;
- // Override the onCreate() API.
+ // Override onCreate().
onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt'
- // Create an RDB.
+ // Create an RDB store.
rdb.getRdbStore(this.context, {
- name: DB_NAME
- }, 1, function (err, data) {
+ name: DB_NAME,
+ securityLevel: rdb.SecurityLevel.S1
+ }, function (err, data) {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
@@ -79,7 +80,7 @@ Examples are given below.
});
}
- // Override the query() API.
+ // Override query().
query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) {
console.info('invalid predicates');
@@ -108,8 +109,8 @@ Examples are given below.
| ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
- | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
- | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**. |
+ | "uri" | URI used for communication. It is the unique identifier for the data consumer to connect to the provider. |
+ | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
**module.json5 example**
@@ -132,7 +133,7 @@ Examples are given below.
1. Import dependencies.
```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
+ import Ability from '@ohos.application.Ability';
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
```
@@ -150,7 +151,7 @@ Examples are given below.
let dsHelper;
let abilityContext;
- export default class EntryAbility extends UIAbility {
+ export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
@@ -180,7 +181,7 @@ Examples are given below.
dsHelper.query(dseUri, predicates, valArray, (err, data) => {
console.log("dsHelper query result: " + data);
});
- // Delete specified data.
+ // Delete data.
dsHelper.delete(dseUri, predicates, (err, data) => {
console.log("dsHelper delete result: " + data);
});
diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md
index 73f785de4ddccaa1e10c6049066a5f3908d85fc6..0fc524a18d5228c5f243f751d32e191856f3d257 100644
--- a/en/application-dev/database/database-mdds-guidelines.md
+++ b/en/application-dev/database/database-mdds-guidelines.md
@@ -14,12 +14,12 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KvManager** object for database management. |
-| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.|
+| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. |
-| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. |
+| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Obtains data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. |
-| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
+| sync(deviceIdList: string[], mode: SyncMode, delayMs?: number): void | Triggers database synchronization in manual mode. |
## How to Develop
@@ -61,32 +61,32 @@ The following uses a single KV store as an example to describe the development p
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666).then((data) => {
console.info('success: ${data}');
}).catch((error) => {
- console.info('failed: ${error}');
+ console.error('failed: ${error}');
})
}
grantPermission();
// Stage model
- import Ability from '@ohos.application.Ability';
+ import AbilityStage from '@ohos.application.Ability';
let context = null;
-
- function grantPermission() {
- class MainAbility extends Ability {
- onWindowStageCreate(windowStage) {
+
+ class MainAbility extends AbilityStage {
+ onWindowStageCreate(windowStage) {
let context = this.context;
- }
+ }
}
-
- let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
- context.requestPermissionsFromUser(permissions).then((data) => {
+
+ function grantPermission() {
+ let permissions = ['ohos.permission.DISTRIBUTED_DATASYNC'];
+ context.requestPermissionsFromUser(permissions).then((data) => {
console.log('success: ${data}');
- }).catch((error) => {
- console.log('failed: ${error}');
- });
+ }).catch((error) => {
+ console.error('failed: ${error}');
+ });
}
-
+
grantPermission();
```
@@ -119,7 +119,7 @@ The following uses a single KV store as an example to describe the development p
}
distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) {
if (err) {
- console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`);
+ console.error(`Failed to create KVManager. code is ${err.code},message is ${err.message}`);
return;
}
console.log('Created KVManager successfully');
diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md
index 2b8b7a562a7e896db40faba9de194777c4d1c170..3adf91286aaf410d7862c60320878e57acb359e8 100644
--- a/en/application-dev/dfx/hitracemeter-guidelines.md
+++ b/en/application-dev/dfx/hitracemeter-guidelines.md
@@ -20,16 +20,16 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs
Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
## Available APIs
-
-The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
-**Table 1** APIs for performance tracing
+The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
+
+**APIs for performance tracing**
-| API| Return Value| Description|
+| API | Return Value | Description |
| ---------------------------------------------------------------------------- | --------- | ------------ |
-| hiTraceMeter.startTrace(name: string, taskId: number) | void | Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same task ID can be used.|
-| hiTraceMeter.finishTrace(name: string, taskId: number) | void | Stops a trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**.|
-| hiTraceMeter.traceByValue(name: string, value: number) | void | Traces the value changes of a variable.|
+| hiTraceMeter.startTrace(name: string, taskId: number) | void | Marks the start of a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same task ID can be used.|
+| hiTraceMeter.finishTrace(name: string, taskId: number) | void | Marks the end of a trace task. The values of **name** and **taskId** must be the same as those of **hiTraceMeter.startTrace**.|
+| hiTraceMeter.traceByValue(name: string, value: number) | void | Marks the value changes of a numeric variable in a trace task.|
## How to Develop
@@ -46,12 +46,12 @@ In this example, distributed call chain tracing begins when the application star
},
onInit() {
this.title = this.$t('strings.world');
-
- // Start track tasks with the same name concurrently.
+
+ // Start trace tasks with the same name concurrently.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
- hiTraceMeter.startTrace("business", 2); // Start the second trace task while the first task is still running. The first and second tasks have the same name but different task IDs.
+ hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different.
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1);
@@ -59,14 +59,14 @@ In this example, distributed call chain tracing begins when the application star
console.log(`business running`);
hiTraceMeter.finishTrace("business", 2);
- // Start track tasks with the same name at different times.
+ // Start trace tasks with the same name in serial mode.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1); // End the first trace task.
// Keep the service process running.
console.log(`business running`);
- hiTraceMeter.startTrace("business", 1); // Start the second trace task after the first trace task ends. The two tasks have the same name and task ID.
+ hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode.
// Keep the service process running.
console.log(`business running`);
@@ -79,4 +79,95 @@ In this example, distributed call chain tracing begins when the application star
}
```
-2. Click the run button on the application page. Then, you'll obtain the log information for service analysis.
+2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
+
+ ```ts
+ import hitrace from '@ohos.hiTraceMeter';
+
+ @Entry
+ @Component
+ struct Index {
+ @State message: string = 'Hello World';
+
+ build() {
+ Row() {
+ Column() {
+ Text(this.message)
+ .fontSize(50)
+ .fontWeight(FontWeight.Bold)
+ .onClick(() => {
+ this.message = 'Hello ArkUI';
+
+ // Start trace tasks with the same name concurrently.
+ hitrace.startTrace("HITRACE_TAG_APP", 1001);
+ // Keep the service process running.
+ console.log(`HITRACE_TAG_APP running`);
+
+ // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different.
+ hitrace.startTrace("HITRACE_TAG_APP", 1002);
+ // Keep the service process running.
+ console.log(`HITRACE_TAG_APP running`);
+
+ hitrace.finishTrace("HITRACE_TAG_APP", 1001);
+ hitrace.finishTrace("HITRACE_TAG_APP", 1002);
+
+ // If trace tasks with the same name are not run concurrently, the same taskId can be used.
+ hitrace.startTrace("HITRACE_TAG_APP", 1003);
+ // Keep the service process running.
+ console.log(`HITRACE_TAG_APP running`);
+ // End the first trace task.
+ hitrace.finishTrace("HITRACE_TAG_APP", 1003);
+
+ // Start the second trace task with the same name in serial mode. It uses a taskId different from the first trace task.
+ hitrace.startTrace("HITRACE_TAG_APP", 1004);
+ // Keep the service process running.
+ console.log(`HITRACE_TAG_APP running`);
+ let traceCount = 3;
+ hitrace.traceByValue("myTestCount", traceCount);
+ hitrace.finishTrace("HITRACE_TAG_APP", 1004);
+
+ // Start the third trace task with the same name in serial mode. It uses a taskId same as the second trace task.
+ hitrace.startTrace("HITRACE_TAG_APP", 1004);
+ // Keep the service process running.
+ console.log(`HITRACE_TAG_APP running`);
+ // End the third trace task.
+ hitrace.finishTrace("HITRACE_TAG_APP", 1004);
+
+ })
+ }
+ .width('100%')
+ }
+ .height('100%')
+ }
+ }
+ ```
+
+3. Click the run button on the application page. Then, run the following commands in sequence in shell:
+
+ ```shell
+ hdc shell
+ hitrace --trace_begin app
+ ```
+
+ After the trace command is executed, call the hiTraceMeter APIs in your own service logic on the device. Then, run the following commands in sequence:
+
+ ```shell
+ hitrace --trace_dump | grep tracing_mark_write
+ hitrace --trace_finish
+ ```
+
+ The following is an example of the captured trace data:
+
+ ```
+ <...>-3310 (-------) [005] .... 351382.921936: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1001
+ <...>-3310 (-------) [005] .... 351382.922138: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1002
+ <...>-3310 (-------) [005] .... 351382.922165: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1001
+ <...>-3310 (-------) [005] .... 351382.922175: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1002
+ <...>-3310 (-------) [005] .... 351382.922182: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1003
+ <...>-3310 (-------) [005] .... 351382.922203: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1003
+ <...>-3310 (-------) [005] .... 351382.922210: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1004
+ <...>-3310 (-------) [005] .... 351382.922233: tracing_mark_write: C|3310|H:myTestCount 3
+ <...>-3310 (-------) [005] .... 351382.922240: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1004
+ <...>-3310 (-------) [005] .... 351382.922247: tracing_mark_write: S|3310|H:HITRACE_TAG_APP 1004
+ <...>-3310 (-------) [005] .... 351382.922266: tracing_mark_write: F|3310|H:HITRACE_TAG_APP 1004
+ ```
diff --git a/en/application-dev/media/avplayer-playback.md b/en/application-dev/media/avplayer-playback.md
new file mode 100644
index 0000000000000000000000000000000000000000..270081373fb500877ca4352366982b66f72bc09a
--- /dev/null
+++ b/en/application-dev/media/avplayer-playback.md
@@ -0,0 +1,507 @@
+# AVPlayer Development
+
+## Introduction
+
+The AVPlayer converts audio or video resources into audible analog signals or renderable images and plays the signals or images using output devices. You can manage playback tasks on the AVPlayer. For example, you can control the playback (start/pause/stop/seek), set the volume, obtain track information, and release resources.
+
+## Working Principles
+
+The following figures show the [AVPlayer state](../reference/apis/js-apis-media.md#avplayerstate9) transition and interaction with external audio and video playback modules.
+
+**Figure 1** AVPlayer state transition
+
+
+
+**Figure 2** Interaction with external modules for audio playback
+
+
+
+**NOTE**: When an application calls the **AVPlayer** JS APIs at the JS interface layer to implement a feature, the framework layer parses the resources into audio data streams through the playback service of the player framework. The audio data streams are then decoded by software and output to the audio service of the audio framework. The audio framework outputs the audio data streams to the audio HDI at the hardware interface layer to implement audio playback. A complete audio playback process requires the cooperation of the application (application adaptation required), player framework, audio framework, and audio HDI (driver adaptation required).
+
+1. An application passes a URL into the **AVPlayer** JS API.
+2. The playback service outputs the audio PCM data streams to the audio service, and the audio service outputs the data streams to the audio HDI.
+
+
+**Figure 3** Interaction with external modules for video playback
+
+
+
+**NOTE**: When an application calls the **AVPlayer** JS APIs at the JS interface layer to implement a feature, the framework layer parses the resources into separate audio data streams and video data streams through the playback service of the player framework. The audio data streams are then decoded by software and output to the audio service of the audio framework. The audio framework outputs the audio data streams to the audio HDI at the hardware interface layer to implement audio playback. The video data streams are then decoded by hardware (recommended) or software and output to the renderer service of the graphic framework. The renderer service outputs the video data streams to the display HDI at the hardware interface layer. A complete video playback process requires the cooperation of the application (application adaptation required), XComponent, player framework, graphic framework, audio framework, display HDI (driver adaptation required), and audio HDI (driver adaptation required).
+
+1. An application obtains the surface ID from the XComponent. For details about the obtaining method, see [XComponent](../reference/arkui-ts/ts-basic-components-xcomponent.md).
+2. The application passes a URL and the surface ID into the **AVPlayer** JS API.
+3. The playback service outputs video elementary streams (ESs) to the codec HDI, which decodes the ESs to obtain video frames (NV12/NV21/RGBA).
+4. The playback service outputs the audio PCM data streams to the audio service, and the audio service outputs the data streams to the audio HDI.
+5. The playback service outputs video frames (NV12/NV21/RGBA) to the renderer service, and the renderer service outputs the video frames to the display HDI.
+
+## Compatibility
+
+Use the mainstream playback formats and resolutions, rather than custom ones to avoid playback failures, frame freezing, and artifacts. The system will not be affected by incompatibility issues. If such an issue occurs, you can exit stream playback.
+
+The table below lists the mainstream playback formats and resolutions.
+
+| Video Container Format| Description | Resolution |
+| :----------: | :-----------------------------------------------: | :--------------------------------: |
+| mp4 | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
+| mkv | Video format: H.264/MPEG-2/MPEG-4/H.263; audio format: AAC/MP3| Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
+| ts | Video format: H.264/MPEG-2/MPEG-4; audio format: AAC/MP3 | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
+| webm | Video format: VP8; audio format: VORBIS | Mainstream resolutions, such as 1080p, 720p, 480p, and 270p|
+
+| Audio Container Format | Description |
+| :----------: | :----------: |
+| m4a | Audio format: AAC|
+| aac | Audio format: AAC|
+| mp3 | Audio format: MP3|
+| ogg | Audio format: VORBIS |
+| wav | Audio format: PCM |
+
+## How to Develop
+
+For details about the APIs, see the [AVPlayer APIs in the Media Class](../reference/apis/js-apis-media.md#avplayer9).
+
+### Full-Process Scenario
+
+The full playback process includes creating an instance, setting resources, setting a video window, preparing for playback, controlling playback, and resetting or releasing the resources. (During the preparation, you can obtain track information, volume, speed, focus mode, and zoom mode, and set bit rates. To control the playback, you can start, pause, and stop the playback, seek to a playback position, and set the volume.)
+
+1. Call [createAVPlayer()](../reference/apis/js-apis-media.md#mediacreateavplayer9) to create an **AVPlayer** instance. The AVPlayer is initialized to the [idle](#avplayer_state) state.
+
+2. Set the events to listen for, which will be used in the full-process scenario.
+
+3. Set the resource [URL](../reference/apis/js-apis-media.md#avplayer_attributes). When the AVPlayer enters the [initialized](#avplayer_state) state, you can set the [surface ID](../reference/apis/js-apis-media.md#avplayer_attributes) for the video window. For details about the supported specifications, see [AVPlayer Attributes](../reference/apis/js-apis-media.md#avplayer_attributes).
+
+4. Call [prepare()](../reference/apis/js-apis-media.md#avplayer_prepare) to switch the AVPlayer to the [prepared](#avplayer_state) state.
+
+5. Perform video playback control. For example, you can call [play()](../reference/apis/js-apis-media.md#avplayer_play), [pause()](../reference/apis/js-apis-media.md#avplayer_pause), [seek()](../reference/apis/js-apis-media.md#avplayer_seek), and [stop()](../reference/apis/js-apis-media.md#avplayer_stop) to control the playback.
+
+6. Call [reset()](../reference/apis/js-apis-media.md#avplayer_reset) to reset resources. The AVPlayer enters the [idle](#avplayer_state) state again, and you can change the resource [URL](../reference/apis/js-apis-media.md#avplayer_attributes).
+
+7. Call [release()](../reference/apis/js-apis-media.md#avplayer_release) to release the instance. The AVPlayer enters the [released](#avplayer_state) state and exits the playback.
+
+> **NOTE**
+>
+> When the AVPlayer is in the prepared, playing, paused, or completed state, the playback engine is working and a large amount of system running memory is occupied. If your application does not need to use the AVPlayer, call **reset()** or **release()** to release the resources.
+
+### Listening Events
+
+| Event Type | Description |
+| ------------------------------------------------- | ------------------------------------------------------------ |
+| stateChange | Mandatory; used to listen for player state changes. |
+| error | Mandatory; used to listen for player error information. |
+| durationUpdate | Used to listen for progress bar updates to refresh the resource duration. |
+| timeUpdate | Used to listen for the current position of the progress bar to refresh the current time. |
+| seekDone | Used to listen for the completion status of the **seek()** request. |
+| speedDone | Used to listen for the completion status of the **setSpeed()** request. |
+| volumeChange | Used to listen for the completion status of the **setVolume()** request. |
+| bitrateDone | Used to listen for the completion status of the **setBitrate()** request, which is used for HTTP Live Streaming (HLS) streams. |
+| availableBitrates | Used to listen for available bit rates of HLS resources. The available bit rates are provided for **setBitrate()**. |
+| bufferingUpdate | Used to listen for network playback buffer information. |
+| startRenderFrame | Used to listen for the rendering time of the first frame during video playback. |
+| videoSizeChange | Used to listen for the width and height of video playback and adjust the window size and ratio.|
+| audioInterrupt | Used to listen for audio interruption during video playback. This event is used together with the **audioInterruptMode** attribute.|
+
+### Full-Process Scenario API Example
+
+```js
+import media from '@ohos.multimedia.media'
+import audio from '@ohos.multimedia.audio';
+import fileIO from '@ohos.fileio'
+
+const TAG = 'AVPlayerDemo:'
+export class AVPlayerDemo {
+ private count:number = 0
+ private avPlayer
+ private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API.
+
+ // Set AVPlayer callback functions.
+ setAVPlayerCallback() {
+ // Callback function for state changes.
+ this.avPlayer.on('stateChange', async (state, reason) => {
+ switch (state) {
+ case 'idle': // This state is reported upon a successful callback of reset().
+ console.info(TAG + 'state idle called')
+ this.avPlayer.release() // Release the AVPlayer instance.
+ break;
+ case 'initialized': // This state is reported when the AVPlayer sets the playback source.
+ console.info(TAG + 'state initialized called ')
+ this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played.
+ this.avPlayer.prepare().then(() => {
+ console.info(TAG+ 'prepare success');
+ }, (err) => {
+ console.error(TAG + 'prepare filed,error message is :' + err.message)
+ })
+ break;
+ case 'prepared': // This state is reported upon a successful callback of prepare().
+ console.info(TAG + 'state prepared called')
+ this.avPlayer.play() // Call play() to start playback.
+ break;
+ case 'playing': // This state is reported upon a successful callback of play().
+ console.info(TAG + 'state playing called')
+ if (this.count == 0) {
+ this.avPlayer.pause() // Call pause() to pause the playback.
+ } else {
+ this.avPlayer.seek(10000, media.SeekMode.SEEK_PREV_SYNC) // Seek to 10 seconds. The seekDone callback is triggered.
+ }
+ break;
+ case 'paused': // This state is reported upon a successful callback of pause().
+ console.info(TAG + 'state paused called')
+ if (this.count == 0) {
+ this.count++
+ this.avPlayer.play() // Call play() to continue the playback.
+ }
+ break;
+ case 'completed': // This state is reported upon the completion of the playback.
+ console.info(TAG + 'state completed called')
+ this.avPlayer.stop() // Call stop() to stop the playback.
+ break;
+ case 'stopped': // This state is reported upon a successful callback of stop().
+ console.info(TAG + 'state stopped called')
+ this.avPlayer.reset() // Call reset() to initialize the AVPlayer state.
+ break;
+ case 'released':
+ console.info(TAG + 'state released called')
+ break;
+ case 'error':
+ console.info(TAG + 'state error called')
+ break;
+ default:
+ console.info(TAG + 'unkown state :' + state)
+ break;
+ }
+ })
+ // Callback function for time updates.
+ this.avPlayer.on('timeUpdate', (time:number) => {
+ console.info(TAG + 'timeUpdate success,and new time is :' + time)
+ })
+ // Callback function for volume updates.
+ this.avPlayer.on('volumeChange', (vol:number) => {
+ console.info(TAG + 'volumeChange success,and new volume is :' + vol)
+ this.avPlayer.setSpeed(media.AVPlayerSpeed.SPEED_FORWARD_2_00_X) // Double the playback speed. The speedDone callback is triggered.
+ })
+ // Callback function for the video playback completion event.
+ this.avPlayer.on('endOfStream', () => {
+ console.info(TAG + 'endOfStream success')
+ })
+ // Callback function for the seek operation.
+ this.avPlayer.on('seekDone', (seekDoneTime:number) => {
+ console.info(TAG + 'seekDone success,and seek time is:' + seekDoneTime)
+ this.avPlayer.setVolume(0.5) // Set the volume to 0.5. The volumeChange callback is triggered.
+ })
+ // Callback function for the speed setting operation.
+ this.avPlayer.on('speedDone', (speed:number) => {
+ console.info(TAG + 'speedDone success,and speed value is:' + speed)
+ })
+ // Callback function for successful bit rate setting.
+ this.avPlayer.on('bitrateDone', (bitrate:number) => {
+ console.info(TAG + 'bitrateDone success,and bitrate value is:' + bitrate)
+ })
+ // Callback function for buffering updates.
+ this.avPlayer.on('bufferingUpdate', (infoType: media.BufferingInfoType, value: number) => {
+ console.info(TAG + 'bufferingUpdate success,and infoType value is:' + infoType + ', value is :' + value)
+ })
+ // Callback function invoked when frame rendering starts.
+ this.avPlayer.on('startRenderFrame', () => {
+ console.info(TAG + 'startRenderFrame success')
+ })
+ // Callback function for video width and height changes.
+ this.avPlayer.on('videoSizeChange', (width: number, height: number) => {
+ console.info(TAG + 'videoSizeChange success,and width is:' + width + ', height is :' + height)
+ })
+ // Callback function for the audio interruption event.
+ this.avPlayer.on('audioInterrupt', (info: audio.InterruptEvent) => {
+ console.info(TAG + 'audioInterrupt success,and InterruptEvent info is:' + info)
+ })
+ // Callback function to report the available bit rates of HLS.
+ this.avPlayer.on('availableBitrates', (bitrates: Array) => {
+ console.info(TAG + 'availableBitrates success,and availableBitrates length is:' + bitrates.length)
+ })
+ }
+
+ async avPlayerDemo() {
+ // Create an AVPlayer instance.
+ this.avPlayer = await media.createAVPlayer()
+ let fdPath = 'fd://'
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
+ let path = pathDir + '/H264_AAC.mp4'
+ await fileIO.open(path).then((fdNumber) => {
+ fdPath = fdPath + '' + fdNumber
+ console.info('open fd success fd is' + fdPath)
+ }, (err) => {
+ console.info('open fd failed err is' + err)
+ }).catch((err) => {
+ console.info('open fd failed err is' + err)
+ });
+ this.avPlayer.url = fdPath
+ }
+}
+```
+
+### Normal Playback Scenario
+
+```js
+import media from '@ohos.multimedia.media'
+import fileIO from '@ohos.fileio'
+
+const TAG = 'AVPlayerDemo:'
+export class AVPlayerDemo {
+ private avPlayer
+ private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API.
+
+ // Set AVPlayer callback functions.
+ setAVPlayerCallback() {
+ // Callback function for state changes.
+ this.avPlayer.on('stateChange', async (state, reason) => {
+ switch (state) {
+ case 'idle': // This state is reported upon a successful callback of reset().
+ console.info(TAG + 'state idle called')
+ break;
+ case 'initialized': // This state is reported when the AVPlayer sets the playback source.
+ console.info(TAG + 'state initialized called ')
+ this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played.
+ this.avPlayer.prepare().then(() => {
+ console.info(TAG+ 'prepare success');
+ }, (err) => {
+ console.error(TAG + 'prepare filed,error message is :' + err.message)
+ })
+ break;
+ case 'prepared': // This state is reported upon a successful callback of prepare().
+ console.info(TAG + 'state prepared called')
+ this.avPlayer.play() // Call play() to start playback.
+ break;
+ case 'playing': // This state is reported upon a successful callback of play().
+ console.info(TAG + 'state playing called')
+ break;
+ case 'paused': // This state is reported upon a successful callback of pause().
+ console.info(TAG + 'state paused called')
+ break;
+ case 'completed': // This state is reported upon the completion of the playback.
+ console.info(TAG + 'state completed called')
+ this.avPlayer.stop() // Call stop() to stop the playback.
+ break;
+ case 'stopped': // This state is reported upon a successful callback of stop().
+ console.info(TAG + 'state stopped called')
+ this.avPlayer.reset() // Call reset() to initialize the AVPlayer state.
+ break;
+ case 'released':
+ console.info(TAG + 'state released called')
+ break;
+ case 'error':
+ console.info(TAG + 'state error called')
+ break;
+ default:
+ console.info(TAG + 'unkown state :' + state)
+ break;
+ }
+ })
+ }
+
+ async avPlayerDemo() {
+ // Create an AVPlayer instance.
+ this.avPlayer = await media.createAVPlayer()
+ let fdPath = 'fd://'
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
+ let path = pathDir + '/H264_AAC.mp4'
+ await fileIO.open(path).then((fdNumber) => {
+ fdPath = fdPath + '' + fdNumber
+ console.info('open fd success fd is' + fdPath)
+ }, (err) => {
+ console.info('open fd failed err is' + err)
+ }).catch((err) => {
+ console.info('open fd failed err is' + err)
+ });
+ this.avPlayer.url = fdPath
+ }
+}
+```
+
+### Switching to the Next Video Clip
+
+```js
+import media from '@ohos.multimedia.media'
+import fileIO from '@ohos.fileio'
+
+const TAG = 'AVPlayerDemo:'
+export class AVPlayerDemo {
+ private count:number = 0
+ private avPlayer
+ private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API.
+
+ // Set AVPlayer callback functions.
+ setAVPlayerCallback() {
+ // Callback function for state changes.
+ this.avPlayer.on('stateChange', async (state, reason) => {
+ switch (state) {
+ case 'idle': // This state is reported upon a successful callback of reset().
+ console.info(TAG + 'state idle called')
+ break;
+ case 'initialized': // This state is reported when the AVPlayer sets the playback source.
+ console.info(TAG + 'state initialized called ')
+ this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played.
+ this.avPlayer.prepare().then(() => {
+ console.info(TAG+ 'prepare success');
+ }, (err) => {
+ console.error(TAG + 'prepare filed,error message is :' + err.message)
+ })
+ break;
+ case 'prepared': // This state is reported upon a successful callback of prepare().
+ console.info(TAG + 'state prepared called')
+ this.avPlayer.loop = true // Set the AVPlayer to loop a single item. The endOfStream callback is triggered when the previous round of the playback is complete.
+ this.avPlayer.play() // Call play() to start playback.
+ break;
+ case 'playing': // This state is reported upon a successful callback of play().
+ console.info(TAG + 'state playing called')
+ break;
+ case 'paused': // This state is reported upon a successful callback of pause().
+ console.info(TAG + 'state paused called')
+ break;
+ case 'completed': // This state is reported upon the completion of the playback.
+ console.info(TAG + 'state completed called')
+ // Cancel the loop playback when the endOfStream callback is triggered for the second time. The completed state is reported when the next round of the playback is complete.
+ this.avPlayer.stop() // Call stop() to stop the playback.
+ break;
+ case 'stopped': // This state is reported upon a successful callback of stop().
+ console.info(TAG + 'state stopped called')
+ this.avPlayer.reset() // Call reset() to initialize the AVPlayer state.
+ break;
+ case 'released':
+ console.info(TAG + 'state released called')
+ break;
+ case 'error':
+ console.info(TAG + 'state error called')
+ break;
+ default:
+ console.info(TAG + 'unkown state :' + state)
+ break;
+ }
+ })
+ // Callback function for the video playback completion event.
+ this.avPlayer.on('endOfStream', () => {
+ console.info(TAG + 'endOfStream success')
+ if (this.count == 1) {
+ this.avPlayer.loop = false // Cancel loop playback.
+ } else {
+ this.count++
+ }
+ })
+ }
+
+ async avPlayerDemo() {
+ // Create an AVPlayer instance.
+ this.avPlayer = await media.createAVPlayer()
+ let fdPath = 'fd://'
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
+ let path = pathDir + '/H264_AAC.mp4'
+ await fileIO.open(path).then((fdNumber) => {
+ fdPath = fdPath + '' + fdNumber
+ console.info('open fd success fd is' + fdPath)
+ }, (err) => {
+ console.info('open fd failed err is' + err)
+ }).catch((err) => {
+ console.info('open fd failed err is' + err)
+ });
+ this.avPlayer.url = fdPath
+ }
+}
+```
+### Looping a Song
+
+```js
+import media from '@ohos.multimedia.media'
+import fileIO from '@ohos.fileio'
+
+const TAG = 'AVPlayerDemo:'
+export class AVPlayerDemo {
+ private count:number = 0
+ private avPlayer
+ private surfaceID:string // The surfaceID parameter is used for screen display. Its value is obtained through the XComponent API.
+
+ async nextVideo() {
+ let fdPath = 'fd://'
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_MP3.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
+ let path = pathDir + '/H264_MP3.mp4'
+ await fileIO.open(path).then((fdNumber) => {
+ fdPath = fdPath + '' + fdNumber
+ console.info('open fd success fd is' + fdPath)
+ }, (err) => {
+ console.info('open fd failed err is' + err)
+ }).catch((err) => {
+ console.info('open fd failed err is' + err)
+ });
+ this.avPlayer.url = fdPath // The initialized state is reported again.
+ }
+
+ // Set AVPlayer callback functions.
+ setAVPlayerCallback() {
+ // Callback function for state changes.
+ this.avPlayer.on('stateChange', async (state, reason) => {
+ switch (state) {
+ case 'idle': // This state is reported upon a successful callback of reset().
+ console.info(TAG + 'state idle called')
+ await this.nextVideo() // Switch to the next video.
+ break;
+ case 'initialized': // This state is reported when the AVPlayer sets the playback source.
+ console.info(TAG + 'state initialized called ')
+ this.avPlayer.surfaceId = this.surfaceID // Set the image to be displayed. This setting is not required when a pure audio resource is to be played.
+ this.avPlayer.prepare().then(() => {
+ console.info(TAG+ 'prepare success');
+ }, (err) => {
+ console.error(TAG + 'prepare filed,error message is :' + err.message)
+ })
+ break;
+ case 'prepared': // This state is reported upon a successful callback of prepare().
+ console.info(TAG + 'state prepared called')
+ this.avPlayer.play() // Call play() to start playback.
+ break;
+ case 'playing': // This state is reported upon a successful callback of play().
+ console.info(TAG + 'state playing called')
+ break;
+ case 'paused': // This state is reported upon a successful callback of pause().
+ console.info(TAG + 'state paused called')
+ break;
+ case 'completed': // This state is reported upon the completion of the playback.
+ console.info(TAG + 'state completed called')
+ if (this.count == 0) {
+ this.count++
+ this.avPlayer.reset() // Call reset() to prepare for switching to the next video.
+ } else {
+ this.avPlayer.release() // Release the AVPlayer instance when the new video finishes playing.
+ }
+ break;
+ case 'stopped': // This state is reported upon a successful callback of stop().
+ console.info(TAG + 'state stopped called')
+ break;
+ case 'released':
+ console.info(TAG + 'state released called')
+ break;
+ case 'error':
+ console.info(TAG + 'state error called')
+ break;
+ default:
+ console.info(TAG + 'unkown state :' + state)
+ break;
+ }
+ })
+ }
+
+ async avPlayerDemo() {
+ // Create an AVPlayer instance.
+ this.avPlayer = await media.createAVPlayer()
+ let fdPath = 'fd://'
+ let pathDir = "/data/storage/el2/base/haps/entry/files" // The path used here is an example. Obtain the path based on project requirements.
+ // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\H264_AAC.mp4 /data/app/el2/100/base/ohos.acts.multimedia.media.avplayer/haps/entry/files" command.
+ let path = pathDir + '/H264_AAC.mp4'
+ await fileIO.open(path).then((fdNumber) => {
+ fdPath = fdPath + '' + fdNumber
+ console.info('open fd success fd is' + fdPath)
+ }, (err) => {
+ console.info('open fd failed err is' + err)
+ }).catch((err) => {
+ console.info('open fd failed err is' + err)
+ });
+ this.avPlayer.url = fdPath
+ }
+}
+```
diff --git a/en/application-dev/media/avrecorder.md b/en/application-dev/media/avrecorder.md
new file mode 100644
index 0000000000000000000000000000000000000000..6378b7515e675fcc0b924fc47a4af9db60707a47
--- /dev/null
+++ b/en/application-dev/media/avrecorder.md
@@ -0,0 +1,486 @@
+# AVRecorder Development
+
+## Introduction
+
+The AVRecorder captures audio signals, receives video signals, encodes audio and video signals, and saves them to files. With the AVRecorder, you can easily implement audio and video recording, including starting, pausing, resuming, and stopping recording, and releasing resources. You can also specify parameters such as the encoding format, encapsulation format, and file path for recording.
+
+## Working Principles
+
+The following figures show the AVRecorder state transition and the interaction with external modules for audio and video recording.
+
+**Figure 1** AVRecorder state transition
+
+
+
+**Figure 2** Interaction between external modules for audio and video recording
+
+
+
+**NOTE**: During audio recording, the framework layer calls the audio subsystem through the media service of the native framework to capture audio data through the audio HDI, encodes and encapsulates the data by using software, and saves the data to a file. During video recording, the camera subsystem captures image data through the video HDI. The media service encodes the image data through the video encoding HDI and encapsulates the encoded image data into a file. With the AVRecorder, you can implement pure audio recording, pure video recording, and audio and video recording.
+
+## Constraints
+
+Before developing the recording feature, configure the permissions **ohos.permission.MICROPHONE** and **ohos.permission.CAMERA** for your application. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md).
+
+## How to Develop
+
+For details about the AVRecorder APIs, see the [AVRecorder APIs in the Media Class](../reference/apis/js-apis-media.md#avrecorder9).
+
+For details about the processes related to the media library, see [Media Library Management](../reference/apis/js-apis-medialibrary.md).
+
+For details about the camera-related process, see [Camera Management](../reference/apis/js-apis-camera.md).
+
+### Full-Process Scenario of Audio and Video Recording
+
+The full audio and video recording process includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources.
+
+The value range that can be set for the audio recording parameters is restricted by the codec performance of the device and the performance of the audio subsystem.
+
+The video range that can be set for the video recording parameters is restricted by the codec performance of the device and the performance of the camera subsystem.
+
+```
+import media from '@ohos.multimedia.media'
+import camera from '@ohos.multimedia.camera'
+import mediaLibrary from '@ohos.multimedia.mediaLibrary'
+
+export class AVRecorderDemo {
+ private testFdNumber; // Used to save the File Descriptor (FD) address.
+
+ // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
+ async getFd(fileName) {
+ // For details about the implementation mode, see the media library documentation.
+ this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54
+ }
+
+ // Error callback triggered in the case of an error in the promise mode.
+ failureCallback(error) {
+ console.info('error happened, error message is ' + error.message);
+ }
+
+ // Error callback triggered in the case of an exception in the promise mode.
+ catchCallback(error) {
+ console.info('catch error happened, error message is ' + error.message);
+ }
+
+ async AVRecorderDemo() {
+ let AVRecorder; // Assign a value to the empty AVRecorder instance upon a successful call of createAVRecorder().
+ let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
+ await this.getFd('01.mp4');
+
+ // Configure the parameters related to audio and video recording.
+ let avProfile = {
+ audioBitrate : 48000,
+ audioChannels : 2,
+ audioCodec : media.CodecMimeType.AUDIO_AAC,
+ audioSampleRate : 48000,
+ fileFormat : media.ContainerFormatType.CFT_MPEG_4,
+ videoBitrate : 48000,
+ videoCodec : media.CodecMimeType.VIDEO_MPEG4,
+ videoFrameWidth : 640,
+ videoFrameHeight : 480,
+ videoFrameRate : 30
+ }
+ let avConfig = {
+ audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
+ videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
+ profile : avProfile,
+ url : 'fd://',
+ rotation : 0,
+ location : { latitude : 30, longitude : 130 }
+ }
+
+ // Create an AVRecorder instance.
+ await media.createAVRecorder().then((recorder) => {
+ console.info('case createAVRecorder called');
+ if (typeof (recorder) != 'undefined') {
+ AVRecorder = recorder;
+ console.info('createAVRecorder success');
+ } else {
+ console.info('createAVRecorder failed');
+ }
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors.
+ AVRecorder.on('stateChange', async (state, reason) => {
+ console.info('case state has changed, new state is :' + state);
+ switch (state) {
+ // Your can set the desired behavior in different states as required.
+ case 'idle':
+ // This state is reported upon a successful call of rest() or create().
+ break;
+ case 'prepared':
+ // This state is reported upon a successful call of prepare().
+ break;
+ case 'started':
+ // This state is reported upon a successful call of start().
+ break;
+ case 'paused':
+ // This state is reported upon a successful call of pause().
+ break;
+ case 'stopped':
+ // This state is reported upon a successful call of stop().
+ break;
+ case 'released':
+ // This state is reported upon a successful call of release().
+ break;
+ case 'error':
+ // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create an AVRecorder instance again.
+ break;
+ default:
+ console.info('case state is unknown');
+ }
+ });
+ AVRecorder.on('error', (err) => {
+ // Listen for non-interface errors.
+ console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
+ });
+
+ // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare().
+ await AVRecorder.prepare(avConfig).then(() => {
+ console.info('prepare success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // If video recording is involved, call getInputSurface to obtain the input surface and pass the returned surface ID to the related camera API.
+ await AVRecorder.getInputSurface().then((surface) => {
+ console.info('getInputSurface success');
+ surfaceID = surface; // The surfaceID is passed into createVideoOutput() of the camera as an input parameter.
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Video recording depends on camera-related APIs. The following operations can be performed only after the video output start API is invoked.
+ // Start video recording.
+ await AVRecorder.start().then(() => {
+ console.info('start success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Pause video recording before the video output stop API of the camera is invoked.
+ await AVRecorder.pause().then(() => {
+ console.info('pause success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Resume video recording after the video output start API of the camera is invoked.
+ await AVRecorder.resume().then(() => {
+ console.info('resume success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Stop video recording after the video output stop API of the camera is invoked.
+ await AVRecorder.stop().then(() => {
+ console.info('stop success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Reset the recording configuration.
+ await AVRecorder.reset().then(() => {
+ console.info('reset success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off().
+ AVRecorder.off('stateChange');
+ AVRecorder.off('error');
+
+ // Release the video recording resources and camera object resources.
+ await AVRecorder.release().then(() => {
+ console.info('release success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Set the AVRecorder instance to null.
+ AVRecorder = undefined;
+ surfaceID = undefined;
+ }
+}
+```
+
+### Full-Process Scenario of Pure Audio Recording
+
+The full audio recording process includes creating an instance, setting recording parameters, starting, pausing, resuming, and stopping recording, and releasing resources.
+
+The value range that can be set for the audio recording parameters is restricted by the codec performance of the device and the performance of the audio subsystem.
+
+```
+import media from '@ohos.multimedia.media'
+import mediaLibrary from '@ohos.multimedia.mediaLibrary'
+
+export class AudioRecorderDemo {
+ private testFdNumber; // Used to save the FD address.
+
+ // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
+ async getFd(fileName) {
+ // For details about the implementation mode, see the media library documentation.
+ this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54
+ }
+
+ // Error callback triggered in the case of an error in the promise mode.
+ failureCallback(error) {
+ console.info('error happened, error message is ' + error.message);
+ }
+
+ // Error callback triggered in the case of an exception in the promise mode.
+ catchCallback(error) {
+ console.info('catch error happened, error message is ' + error.message);
+ }
+
+ async audioRecorderDemo() {
+ let audioRecorder; // Assign a value to the empty AudioRecorder instance upon a successful call of createAVRecorder().
+ await this.getFd('01.m4a');
+ // Configure the parameters related to audio recording.
+ let audioProfile = {
+ audioBitrate : 48000,
+ audioChannels : 2,
+ audioCodec : media.CodecMimeType.AUDIO_AAC,
+ audioSampleRate : 48000,
+ fileFormat : media.ContainerFormatType.CFT_MPEG_4,
+ }
+ let audioConfig = {
+ audioSourceType : media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC,
+ profile : audioProfile,
+ url : this.testFdNumber,
+ rotation : 0,
+ location : { latitude : 30, longitude : 130 }
+ }
+
+ // Create an AudioRecorder instance.
+ await media.createAVRecorder().then((recorder) => {
+ console.info('case createAVRecorder called');
+ if (typeof (recorder) != 'undefined') {
+ audioRecorder = recorder;
+ console.info('createAudioRecorder success');
+ } else {
+ console.info('createAudioRecorder failed');
+ }
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors.
+ audioRecorder.on('stateChange', async (state, reason) => {
+ console.info('case state has changed, new state is :' + state);
+ switch (state) {
+ // Your can set the desired behavior in different states as required.
+ case 'idle':
+ // This state is reported upon a successful call of rest() or create().
+ break;
+ case 'prepared':
+ // This state is reported upon a successful call of prepare().
+ break;
+ case 'started':
+ // This state is reported upon a successful call of start().
+ break;
+ case 'paused':
+ // This state is reported upon a successful call of pause().
+ break;
+ case 'stopped':
+ // This state is reported upon a successful call of stop().
+ break;
+ case 'released':
+ // This state is reported upon a successful call of release().
+ break;
+ case 'error':
+ // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create an AudioRecorder instance again.
+ break;
+ default:
+ console.info('case state is unknown');
+ }
+ });
+ audioRecorder.on('error', (err) => {
+ // Listen for non-interface errors.
+ console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
+ });
+
+ // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare().
+ await audioRecorder.prepare(audioConfig).then(() => {
+ console.info('prepare success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Call start() to start audio recording.
+ await audioRecorder.start().then(() => {
+ console.info('start success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Call pause() to pause audio recording.
+ await audioRecorder.pause().then(() => {
+ console.info('pause success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Call resume() to resume audio recording.
+ await audioRecorder.resume().then(() => {
+ console.info('resume success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Call stop() to stop audio recording.
+ await audioRecorder.stop().then(() => {
+ console.info('stop success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Call reset() to reset the recording configuration.
+ await audioRecorder.reset().then(() => {
+ console.info('reset success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off().
+ avRecorder.off('stateChange');
+ avRecorder.off('error');
+
+ // Call release() to release audio recording resources.
+ await audioRecorder.release().then(() => {
+ console.info('release success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Set the AudioRecorder instance to null.
+ audioRecorder = undefined;
+ }
+}
+
+```
+
+### Full-Process Scenario of Pure Video Recording
+
+The full video recording process includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources.
+
+The video range that can be set for the video recording parameters is restricted by the codec performance of the device and the performance of the camera subsystem.
+
+```
+import media from '@ohos.multimedia.media'
+import camera from '@ohos.multimedia.camera'
+import mediaLibrary from '@ohos.multimedia.mediaLibrary'
+
+export class VideoRecorderDemo {
+ private testFdNumber; // Used to save the FD address.
+
+ // Obtain the FD corresponding to fileName of the recorded file. The media library capability is required. To use the media library, configure the following permissions: ohos.permission.MEDIA_LOCATION, ohos.permission.WRITE_MEDIA, and ohos.permission.READ_MEDIA.
+ async getFd(fileName) {
+ // For details about the implementation mode, see the media library documentation.
+ this.testFdNumber = "fd://" + fdNumber.toString(); // e.g. fd://54
+ }
+
+ // Error callback triggered in the case of an error in the promise mode.
+ failureCallback(error) {
+ console.info('error happened, error message is ' + error.message);
+ }
+
+ // Error callback triggered in the case of an exception in the promise mode.
+ catchCallback(error) {
+ console.info('catch error happened, error message is ' + error.message);
+ }
+
+ async videoRecorderDemo() {
+ let videoRecorder; // Assign a value to the empty VideoRecorder instance upon a successful call of createAVRecorder().
+ let surfaceID; // The surface ID is obtained by calling getInputSurface and transferred to the videoOutput object of the camera.
+ await this.getFd('01.mp4');
+
+ // Configure the parameters related to video recording.
+ let videoProfile = {
+ fileFormat : media.ContainerFormatType.CFT_MPEG_4,
+ videoBitrate : 48000,
+ videoCodec : media.CodecMimeType.VIDEO_MPEG4,
+ videoFrameWidth : 640,
+ videoFrameHeight : 480,
+ videoFrameRate : 30
+ }
+ let videoConfig = {
+ videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV,
+ profile : videoProfile,
+ url : 'fd://',
+ rotation : 0,
+ location : { latitude : 30, longitude : 130 }
+ }
+
+ // Create a VideoRecorder instance.
+ await media.createAVRecorder().then((recorder) => {
+ console.info('case createVideoRecorder called');
+ if (typeof (recorder) != 'undefined') {
+ videoRecorder = recorder;
+ console.info('createVideoRecorder success');
+ } else {
+ console.info('createVideoRecorder failed');
+ }
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // After the instance is created, use the on('stateChange') and on('error') callbacks to listen for state changes and errors.
+ videoRecorder.on('stateChange', async (state, reason) => {
+ console.info('case state has changed, new state is :' + state);
+ switch (state) {
+ // Your can set the desired behavior in different states as required.
+ case 'idle':
+ // This state is reported upon a successful call of rest() or create().
+ break;
+ case 'prepared':
+ // This state is reported upon a successful call of prepare().
+ break;
+ case 'started':
+ // This state is reported upon a successful call of start().
+ break;
+ case 'paused':
+ // This state is reported upon a successful call of pause().
+ break;
+ case 'stopped':
+ // This state is reported upon a successful call of stop().
+ break;
+ case 'released':
+ // This state is reported upon a successful call of release().
+ break;
+ case 'error':
+ // The error state indicates that an error occurs at the bottom layer. You must rectify the fault and create a VideoRecorder instance again.
+ break;
+ default:
+ console.info('case state is unknown');
+ }
+ });
+ videoRecorder.on('error', (err) => {
+ // Listen for non-interface errors.
+ console.info('case avRecorder.on(error) called, errMessage is ' + err.message);
+ });
+
+ // Call prepare() to prepare for recording. The bottom layer determines whether to record audio, video, or audio and video based on the input parameters of prepare().
+ await videoRecorder.prepare(videoConfig).then(() => {
+ console.info('prepare success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // If video recording is involved, call getInputSurface to obtain the input surface and pass the returned surface ID to the related camera API.
+ await videoRecorder.getInputSurface().then((surface) => {
+ console.info('getInputSurface success');
+ surfaceID = surface; // The surfaceID is passed into createVideoOutput() of the camera as an input parameter.
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Video recording depends on camera-related APIs. The following operations can be performed only after the video output start API is invoked.
+ // Start video recording.
+ await videoRecorder.start().then(() => {
+ console.info('start success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Pause video recording before the video output stop API of the camera is invoked.
+ await videoRecorder.pause().then(() => {
+ console.info('pause success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Resume video recording after the video output start API of the camera is invoked.
+ await videoRecorder.resume().then(() => {
+ console.info('resume success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Stop video recording after the video output stop API of the camera is invoked.
+ await videoRecorder.stop().then(() => {
+ console.info('stop success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Reset the recording configuration.
+ await videoRecorder.reset().then(() => {
+ console.info('reset success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Disable the listeners. The configured callbacks will be invalid after release() is invoked, even if you do not call off().
+ videoRecorder.off('stateChange');
+ videoRecorder.off('error');
+
+ // Release the video recording resources and camera object resources.
+ await videoRecorder.release().then(() => {
+ console.info('release success');
+ }, this.failureCallback).catch(this.catchCallback);
+
+ // Set the VideoRecorder instance to null.
+ videoRecorder = undefined;
+ surfaceID = undefined;
+ }
+}
+```
+
+### AVRecorder App
+
+The AVRecorder app provides a complete audio and video recording process, which includes creating an instance, setting recording parameters, obtaining the input surface, starting, pausing, resuming, and stopping recording, and releasing resources.
+
+For details about the code, see [AVRecorderDemo]([multimedia_player_framework: Implementation of media playback and recording](https://gitee.com/openharmony/multimedia_player_framework/tree/master/test/appdemo/AVRecorderDemo)).
diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md
index 8032348105eb70a3b5dbfd431de3632d6d04cb8a..0622db9c3ce6d962001b47ca6d2e6d1bc2aaff7c 100644
--- a/en/application-dev/media/camera.md
+++ b/en/application-dev/media/camera.md
@@ -2,13 +2,13 @@
## When to Use
-With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zooming control, and many others.
+With the APIs provided by the **Camera** module, you can access and operate camera devices and develop new functions. Common operations include preview, photographing, and video recording. You can also implement flash control, exposure time control, focus mode control, zoom control, and much more.
Before calling camera APIs, be familiar with the following concepts:
- **Static camera capabilities**: A series of parameters used to describe inherent capabilities of a camera, such as orientation and supported resolution.
- **Physical camera**: An independent camera device. The physical camera ID is a string that uniquely identifies a physical camera.
-- **Asynchronous operation**: To prevent the UI thread from being blocked, most **Camera** calls are asynchronous. Each API provides the callback and promise functions.
+- **Asynchronous operation**: A non-blocking operation that allows other operations to execute before it completes. To prevent the UI thread from being blocked, some **Camera** calls are asynchronous. Each asynchronous API provides the callback and promise functions.
## How to Develop
@@ -22,7 +22,7 @@ The full process includes applying for permissions, creating an instance, settin
#### Applying for Permissions
-You must apply for the permission for your application to access the camera device and other functions. The following table lists camera-related permissions.
+You must apply for the permissions for your application to access the camera device and other functions. The following table lists camera-related permissions.
| Permission| Attribute Value |
| -------- | ------------------------------ |
@@ -51,82 +51,108 @@ function applyPermission() {
#### Creating an Instance
-You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. If the list is not empty, each ID in the list can be used to create an independent camera instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows:
+You must create an independent **CameraManager** instance before performing camera operations. If this operation fails, the camera may be occupied or unusable. If the camera is occupied, wait until it is released. You can call **getSupportedCameras()** to obtain the list of cameras supported by the current device. The list stores all camera IDs of the current device. Each of these IDs can be used to create an independent **CameraManager** instance. If the list is empty, no camera is available for the current device and subsequent operations cannot be performed. The camera has preview, shooting, video recording, and metadata output streams. You can use **getSupportedOutputCapability()** to obtain the output stream capabilities of the camera and configure them in the **profile** field in **CameraOutputCapability**. The procedure for creating a **CameraManager** instance is as follows:
```typescript
import camera from '@ohos.multimedia.camera'
import image from '@ohos.multimedia.image'
import media from '@ohos.multimedia.media'
-// Create a CameraManager object.
+// Create a CameraManager instance.
context: any = getContext(this)
-let cameraManager = await camera.getCameraManager(this.context)
+let cameraManager = camera.getCameraManager(this.context)
if (!cameraManager) {
- console.error('Failed to get the CameraManager instance');
-}
+ console.error("camera.getCameraManager error")
+ return;
+}
+// Listen for camera state changes.
+cameraManager.on('cameraStatus', (cameraStatusInfo) => {
+ console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
+ console.log(`status: ${cameraStatusInfo.status}`);
+})
// Obtain the camera list.
-let cameraArray = await cameraManager.getSupportedCameras()
-if (!cameraArray) {
- console.error('Failed to get the cameras');
-}
+let cameraArray = cameraManager.getSupportedCameras();
+if (cameraArray.length <= 0) {
+ console.error("cameraManager.getSupportedCameras error")
+ return;
+}
for (let index = 0; index < cameraArray.length; index++) {
- console.log('cameraId : ' + cameraArray[index].cameraId) // Obtain the camera ID.
- console.log('cameraPosition : ' + cameraArray[index].cameraPosition) // Obtain the camera position.
- console.log('cameraType : ' + cameraArray[index].cameraType) // Obtain the camera type.
- console.log('connectionType : ' + cameraArray[index].connectionType) // Obtain the camera connection type.
+ console.log('cameraId : ' + cameraArray[index].cameraId); // Obtain the camera ID.
+ console.log('cameraPosition : ' + cameraArray[index].cameraPosition); // Obtain the camera position.
+ console.log('cameraType : ' + cameraArray[index].cameraType); // Obtain the camera type.
+ console.log('connectionType : ' + cameraArray[index].connectionType); // Obtain the camera connection type.
}
// Create a camera input stream.
-let cameraInput = await cameraManager.createCameraInput(cameraArray[0])
+let cameraInput
+try {
+ cameraInput = cameraManager.createCameraInput(cameraArray[0]);
+} catch () {
+ console.error('Failed to createCameraInput errorCode = ' + error.code);
+}
+
+// Listen for CameraInput errors.
+let cameraDevice = cameraArray[0];
+cameraInput.on('error', cameraDevice, (error) => {
+ console.log(`Camera input error code: ${error.code}`);
+})
-// Open camera
+// Open the camera.
await cameraInput.open();
// Obtain the output stream capabilities supported by the camera.
-let cameraOutputCap = await cameraManager.getSupportedOutputCapability(cameraArray[0]);
+let cameraOutputCap = cameraManager.getSupportedOutputCapability(cameraArray[0]);
if (!cameraOutputCap) {
- console.error("outputCapability outputCapability == null || undefined")
-} else {
- console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
+ console.error("cameraManager.getSupportedOutputCapability error")
+ return;
}
+console.info("outputCapability: " + JSON.stringify(cameraOutputCap));
-let previewProfilesArray = cameraOutputCap.GetPreviewProfiles();
+let previewProfilesArray = cameraOutputCap.previewProfiles;
if (!previewProfilesArray) {
console.error("createOutput previewProfilesArray == null || undefined")
}
-let photoProfilesArray = cameraOutputCap.GetPhotoProfiles();
+let photoProfilesArray = cameraOutputCap.photoProfiles;
if (!photoProfilesArray) {
console.error("createOutput photoProfilesArray == null || undefined")
}
-let videoProfilesArray = cameraOutputCap.GetVideoProfiles();
+let videoProfilesArray = cameraOutputCap.videoProfiles;
if (!videoProfilesArray) {
console.error("createOutput videoProfilesArray == null || undefined")
}
-let metadataObjectTypesArray = cameraOutputCap.GetSupportedMetadataObjectType();
+let metadataObjectTypesArray = cameraOutputCap.supportedMetadataObjectTypes;
if (!metadataObjectTypesArray) {
console.error("createOutput metadataObjectTypesArray == null || undefined")
}
// Create a preview stream. For details about the surfaceId parameter, see the XComponent section. The preview stream is the surface provided by the XComponent.
-let previewOutput = await cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
-if (!previewOutput) {
+let previewOutput
+try {
+ previewOutput = cameraManager.createPreviewOutput(previewProfilesArray[0], surfaceId)
+} catch (error) {
console.error("Failed to create the PreviewOutput instance.")
}
-// Create an ImageReceiver object and set photo parameters. The resolution is set based on the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
+// Listen for PreviewOutput errors.
+previewOutput.on('error', (error) => {
+ console.log(`Preview output error code: ${error.code}`);
+})
+
+// Create an ImageReceiver instance and set photo parameters. Wherein, the resolution must be one of the photographing resolutions supported by the current device, which are obtained by photoProfilesArray.
let imageReceiver = await image.createImageReceiver(1920, 1080, 4, 8)
// Obtain the surface ID for displaying the photos.
let photoSurfaceId = await imageReceiver.getReceivingSurfaceId()
// Create a photographing output stream.
-let photoOutput = await cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
-if (!photoOutput) {
- console.error('Failed to create the PhotoOutput instance.');
- return;
+let photoOutput
+try {
+ photoOutput = cameraManager.createPhotoOutput(photoProfilesArray[0], photoSurfaceId)
+} catch (error) {
+ console.error('Failed to createPhotoOutput errorCode = ' + error.code);
}
// Define video recording parameters.
@@ -168,12 +194,18 @@ videoRecorder.getInputSurface().then((id) => {
videoSurfaceId = id
})
-// Create a VideoOutput object.
-let videoOutput = await cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
-if (!videoOutput) {
- console.error('Failed to create the videoOutput instance.');
- return;
+// Create a VideoOutput instance.
+let videoOutput
+try {
+ videoOutput = cameraManager.createVideoOutput(videoProfilesArray[0], videoSurfaceId)
+} catch (error) {
+ console.error('Failed to create the videoOutput instance. errorCode = ' + error.code);
}
+
+// Listen for VideoOutput errors.
+videoOutput.on('error', (error) => {
+ console.log(`Preview output error code: ${error.code}`);
+})
```
Surfaces must be created in advance for the preview, shooting, and video recording stream. The preview stream is the surface provided by the **XComponent**, the shooting stream is the surface provided by **ImageReceiver**, and the video recording stream is the surface provided by **VideoRecorder**.
@@ -247,24 +279,45 @@ function getVideoRecorderSurface() {
```typescript
// Create a session.
-let captureSession = await camera.createCaptureSession()
-if (!captureSession) {
- console.error('Failed to create the CaptureSession instance.');
- return;
+let captureSession
+try {
+ captureSession = cameraManager.createCaptureSession()
+} catch (error) {
+ console.error('Failed to create the CaptureSession instance. errorCode = ' + error.code);
}
-console.log('Callback returned with the CaptureSession instance.' + session);
+
+// Listen for session errors.
+captureSession.on('error', (error) => {
+ console.log(`Capture session error code: ${error.code}`);
+})
// Start configuration for the session.
-await captureSession.beginConfig()
+try {
+ captureSession.beginConfig()
+} catch (error) {
+ console.error('Failed to beginConfig. errorCode = ' + error.code);
+}
// Add the camera input stream to the session.
-await captureSession.addInput(cameraInput)
+try {
+ captureSession.addInput(cameraInput)
+} catch (error) {
+ console.error('Failed to addInput. errorCode = ' + error.code);
+}
// Add the preview input stream to the session.
-await captureSession.addOutput(previewOutput)
+try {
+ captureSession.addOutput(previewOutput)
+} catch (error) {
+ console.error('Failed to addOutput(previewOutput). errorCode = ' + error.code);
+}
// Add the photographing output stream to the session.
-await captureSession.addOutput(photoOutput)
+try {
+ captureSession.addOutput(photoOutput)
+} catch (error) {
+ console.error('Failed to addOutput(photoOutput). errorCode = ' + error.code);
+}
// Commit the session configuration.
await captureSession.commitConfig()
@@ -282,13 +335,25 @@ await captureSession.start().then(() => {
await captureSession.stop()
// Start configuration for the session.
-await captureSession.beginConfig()
+try {
+ captureSession.beginConfig()
+} catch (error) {
+ console.error('Failed to beginConfig. errorCode = ' + error.code);
+}
// Remove the photographing output stream from the session.
-await captureSession.removeOutput(photoOutput)
+try {
+ captureSession.removeOutput(photoOutput)
+} catch (error) {
+ console.error('Failed to removeOutput(photoOutput). errorCode = ' + error.code);
+}
// Add a video recording output stream to the session.
-await captureSession.addOutput(videoOutput)
+try {
+ captureSession.addOutput(videoOutput)
+} catch (error) {
+ console.error('Failed to addOutput(videoOutput). errorCode = ' + error.code);
+}
// Commit the session configuration.
await captureSession.commitConfig()
@@ -303,71 +368,65 @@ await captureSession.start().then(() => {
```typescript
// Check whether the camera has flash.
-let flashStatus = await captureSession.hasFlash()
-if (!flashStatus) {
- console.error('Failed to check whether the device has the flash mode.');
+let flashStatus
+try {
+ flashStatus = captureSession.hasFlash()
+} catch (error) {
+ console.error('Failed to hasFlash. errorCode = ' + error.code);
}
console.log('Promise returned with the flash light support status:' + flashStatus);
if (flashStatus) {
// Check whether the auto flash mode is supported.
let flashModeStatus
- captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, async (err, status) => {
- if (err) {
- console.error('Failed to check whether the flash mode is supported. ${err.message}');
- return;
- }
- console.log('Callback returned with the flash mode support status: ' + status);
+ try {
+ let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO)
flashModeStatus = status
- })
+ } catch (error) {
+ console.error('Failed to check whether the flash mode is supported. errorCode = ' + error.code);
+ }
if(flashModeStatus) {
// Set the flash mode to auto.
- captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, async (err) => {
- if (err) {
- console.error('Failed to set the flash mode ${err.message}');
- return;
- }
- console.log('Callback returned with the successful execution of setFlashMode.');
- })
+ try {
+ captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO)
+ } catch (error) {
+ console.error('Failed to set the flash mode. errorCode = ' + error.code);
+ }
}
}
// Check whether the continuous auto focus is supported.
let focusModeStatus
-captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err, status) => {
- if (err) {
- console.error('Failed to check whether the focus mode is supported. ${err.message}');
- return;
- }
- console.log('Callback returned with the focus mode support status: ' + status);
+try {
+ let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
focusModeStatus = status
-})
+} catch (error) {
+ console.error('Failed to check whether the focus mode is supported. errorCode = ' + error.code);
+}
+
if (focusModeStatus) {
// Set the focus mode to continuous auto focus.
- captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO, async (err) => {
- if (err) {
- console.error('Failed to set the focus mode ${err.message}');
- return;
- }
- console.log('Callback returned with the successful execution of setFocusMode.');
- })
+ try {
+ captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_CONTINUOUS_AUTO)
+ } catch (error) {
+ console.error('Failed to set the focus mode. errorCode = ' + error.code);
+ }
}
// Obtain the zoom ratio range supported by the camera.
-let zoomRatioRange = await captureSession.getZoomRatioRange()
-if (!zoomRatioRange) {
- console.error('Failed to get the zoom ratio range.');
- return;
+let zoomRatioRange
+try {
+ zoomRatioRange = captureSession.getZoomRatioRange()
+} catch (error) {
+ console.error('Failed to get the zoom ratio range. errorCode = ' + error.code);
}
// Set a zoom ratio.
-captureSession.setZoomRatio(zoomRatioRange[0], async (err) => {
- if (err) {
- console.error('Failed to set the zoom ratio value ${err.message}');
- return;
- }
- console.log('Callback returned with the successful execution of setZoomRatio.');
-})
+try {
+ captureSession.setZoomRatio(zoomRatioRange[0])
+} catch (error) {
+ console.error('Failed to set the zoom ratio value. errorCode = ' + error.code);
+}
```
#### Taking Photos
@@ -428,7 +487,7 @@ For details about the APIs used for saving photos, see [Image Processing](image.
captureSession.stop()
// Release the camera input stream.
-cameraInput.release()
+cameraInput.close()
// Release the preview output stream.
previewOutput.release()
@@ -449,4 +508,4 @@ captureSession = null
## Process Flowchart
The following figure shows the process of using the camera.
-
+
diff --git a/en/application-dev/media/figures/camera_framework_process.jpg b/en/application-dev/media/figures/camera_framework_process.jpg
deleted file mode 100644
index 1207a9a4adb5d5886f9427b07f0ec7d717fc5bf8..0000000000000000000000000000000000000000
Binary files a/en/application-dev/media/figures/camera_framework_process.jpg and /dev/null differ
diff --git a/en/application-dev/media/figures/camera_framework_process.png b/en/application-dev/media/figures/camera_framework_process.png
new file mode 100644
index 0000000000000000000000000000000000000000..bf4b6806fb19e087318306dbc7f9a4b0576273cd
Binary files /dev/null and b/en/application-dev/media/figures/camera_framework_process.png differ
diff --git a/en/application-dev/media/figures/en-us_image_avplayer_audio.png b/en/application-dev/media/figures/en-us_image_avplayer_audio.png
new file mode 100644
index 0000000000000000000000000000000000000000..b5eb9b02a977d0e4551a236c7cc8a154710f5517
Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_audio.png differ
diff --git a/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png b/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png
new file mode 100644
index 0000000000000000000000000000000000000000..aa8afdbcbf142fd745cee03fc422caec51cfe41b
Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_state_machine.png differ
diff --git a/en/application-dev/media/figures/en-us_image_avplayer_video.png b/en/application-dev/media/figures/en-us_image_avplayer_video.png
new file mode 100644
index 0000000000000000000000000000000000000000..54525ebed1d1792f43156ffbeb1ffa37f56d8237
Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avplayer_video.png differ
diff --git a/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png b/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png
new file mode 100644
index 0000000000000000000000000000000000000000..7d5da3bdc91fe8fb7be9f0b4054f934ec054b8e6
Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avrecorder_module_interaction.png differ
diff --git a/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png b/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png
new file mode 100644
index 0000000000000000000000000000000000000000..7ffcb21f09365e9b072bdaf48f8b98d7d45a8aaa
Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_avrecorder_state_machine.png differ
diff --git a/en/application-dev/napi/mindspore-lite-guidelines.md b/en/application-dev/napi/mindspore-lite-guidelines.md
index 3dde56c84f321a6200c45b1839eccdabcba942aa..f91d4145a856b925d3172fb990ba90ccca2a5b20 100644
--- a/en/application-dev/napi/mindspore-lite-guidelines.md
+++ b/en/application-dev/napi/mindspore-lite-guidelines.md
@@ -61,7 +61,7 @@ The development process consists of the following main steps:
The required model can be downloaded directly or obtained using the model conversion tool.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example.
- - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the `.ms` format.
+ - If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/downloads.html#id1) to convert it to the `.ms` format.
2. Create a context, and set parameters such as the number of runtime threads and device type.
diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md
index d0ff5a8c183d8efba03b12f7343f001a3ba31fe5..0cb38c2c123171b7ebe05df263b7275445542986 100644
--- a/en/application-dev/quick-start/arkts-rendering-control.md
+++ b/en/application-dev/quick-start/arkts-rendering-control.md
@@ -263,11 +263,11 @@ struct MyComponent {
>
> - **LazyForEach** must be used in the container component. Currently, only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time.
>
-> - **LazyForEach** must create and only one child component in each iteration.
+> - **LazyForEach** must create one and only one child component in each iteration.
>
-> - The generated child components must be allowed in the parent container component of **LazyForEach**.
+> - The generated child components must be the ones allowed in the parent container component of **LazyForEach**.
>
-> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement.
+> - **LazyForEach** can be included in an **if/else** statement.
>
> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**.
>
diff --git a/en/application-dev/quick-start/arkts-restrictions-and-extensions.md b/en/application-dev/quick-start/arkts-restrictions-and-extensions.md
index 1cb3b0fa04aedd8df61a660993e7f67e48c03c98..fa62ed392100f7ff0b60dcc6e8ee66ef465fbb3a 100644
--- a/en/application-dev/quick-start/arkts-restrictions-and-extensions.md
+++ b/en/application-dev/quick-start/arkts-restrictions-and-extensions.md
@@ -46,35 +46,79 @@ struct bindPopupPage {
## Restrictions on Data Type Declarations of State Variables
-The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
-
-Example:
-
-```ts
-// xxx.ets
-@Entry
-@Component
-struct IndexPage {
- // Incorrect: @State message: string | Resource = 'Hello World'
- @State message: string = 'Hello World'
-
- build() {
- Row() {
- Column() {
- Text(`${this.message}`)
- .fontSize(50)
- .fontWeight(FontWeight.Bold)
+1. The data types of state variables decorated by state decorators must be explicitly declared. They cannot be declared as **any** or **Date**.
+
+ Example:
+
+ ```ts
+ // xxx.ets
+ @Entry
+ @Component
+ struct DatePickerExample {
+ // Incorrect: @State isLunar: any = false
+ @State isLunar: boolean = false
+ // Incorrect: @State selectedDate: Date = new Date('2021-08-08')
+ private selectedDate: Date = new Date('2021-08-08')
+
+ build() {
+ Column() {
+ Button('Switch Calendar')
+ .margin({ top: 30 })
+ .onClick(() => {
+ this.isLunar = !this.isLunar
+ })
+ DatePicker({
+ start: new Date('1970-1-1'),
+ end: new Date('2100-1-1'),
+ selected: this.selectedDate
+ })
+ .lunar(this.isLunar)
+ .onChange((value: DatePickerResult) => {
+ this.selectedDate.setFullYear(value.year, value.month, value.day)
+ console.info('select current date is: ' + JSON.stringify(value))
+ })
+
+ }.width('100%')
}
- .width('100%')
}
- .height('100%')
- }
-}
-```
+ ```
+
+ 
+
+2. The data type declaration of the **@State**, **@Provide**, **@Link**, or **@Consume** decorated state variables can consist of only one of the primitive data types or reference data types.
+
+ The **Length**, **ResourceStr**, and **ResourceColor** types are combinations of primitive data types or reference data types. Therefore, they cannot be used by the aforementioned types of state variables.
+ For details about the definitions of **Length**, **ResourceStr**, and **ResourceColor**, see [Types](../../application-dev/reference/arkui-ts/ts-types.md).
+
+ Example:
+
+ ```ts
+ // xxx.ets
+ @Entry
+ @Component
+ struct IndexPage {
+ // Incorrect: @State message: string | Resource = 'Hello World'
+ @State message: string = 'Hello World'
+ // Incorrect: @State message: ResourceStr = $r('app.string.hello')
+ @State resourceStr: Resource = $r('app.string.hello')
+
+ build() {
+ Row() {
+ Column() {
+ Text(`${this.message}`)
+ .fontSize(50)
+ .fontWeight(FontWeight.Bold)
+ }
+ .width('100%')
+ }
+ .height('100%')
+ }
+ }
+ ```
-
+ 
-## Initialization and Restrictions of Custom Components' Member Variables
+## Initialization Rules and Restrictions of Custom Components' Member Variables
The member variables of a component can be initialized in either of the following ways:
@@ -89,7 +133,7 @@ The member variables of a component can be initialized in either of the followin
MyComponent({counter: $myCounter})
```
-The allowed method depends on the decorator of the state variable, as shown in the following table.
+The allowed method depends on the decorator of the state variable, as described in the following table.
| Decorator | Local Initialization| Initialization Using Constructor Parameters|
| ------------ | ----- | ----------- |
@@ -98,6 +142,8 @@ The allowed method depends on the decorator of the state variable, as shown in t
| @Link | Forbidden | Mandatory |
| @StorageLink | Mandatory | Forbidden |
| @StorageProp | Mandatory | Forbidden |
+| @LocalStorageLink | Mandatory | Forbidden |
+| @LocalStorageProp | Mandatory | Forbidden |
| @Provide | Mandatory | Optional |
| @Consume | Forbidden | Forbidden |
| @ObjectLink | Forbidden | Mandatory |
@@ -111,25 +157,78 @@ As indicated by the preceding table:
Comply with the following rules when using constructors to initialize member variables:
-| From the Variable in the Parent Component (Below) to the Variable in the Child Component (Right)| @State | @Link | @Prop | Normal Variable|
-| -------------------------------------------- | ------ | ------ | ------ | -------- |
-| @State | Not allowed| Allowed | Allowed | Allowed |
-| @Link | Not allowed| Allowed | Not recommended| Allowed |
-| @Prop | Not allowed| Not allowed| Allowed | Allowed |
-| @StorageLink | Not allowed| Allowed | Not allowed| Not allowed |
-| @StorageProp | Not allowed| Not allowed| Not allowed| Allowed |
-| Normal variable | Allowed | Not allowed| Not allowed| Allowed |
+| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
+|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
+| **regular** | Supported | Supported | Supported | Supported | Not supported | Not supported | Supported |
+| **@State** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
+| **@Link** | Not supported | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
+| **@Prop** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
+| **@Provide** | Supported | Supported | Supported | Supported | Supported | Supported | Supported |
+| **@Consume** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
+| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported | Not supported |
-As indicated by the preceding table:
+| **From the Variable in the Parent Component (Right) to the Variable in the Child Component (Below)**| **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
+|------------------|------------------|------------------|-----------------------|------------------------|
+| **regular** | Supported | Not supported | Not supported | Not supported |
+| **@State** | Supported | Supported | Supported | Supported |
+| **@Link** | Supported (1) | Supported (1) | Supported (1) | Supported (1) |
+| **@Prop** | Supported | Supported | Supported | Supported |
+| **@Provide** | Supported | Supported | Supported | Supported |
+| **@Consume** | Not supported | Not supported | Not supported | Not supported |
+| **@ObjectLink** | Not supported | Not supported | Not supported | Not supported |
+
+> **NOTE**
+>
+> **Supported (1)**: The dollar sign ($) must be used, for example, **this.$varA**.
+>
+> **regular**: refers to a regular variable that is not decorated by any decorator.
+
+As indicated by the preceding tables:
+
+- The **@ObjectLink** decorated variable cannot be directly initialized from a decorated variable in the parent component. The source of the parent component must be an array item or object attribute decorated by **@State**, **@Link**, **@Provide**, **@Consume**, or **@ObjectLink**.
-- The normal variables of the parent component can be used to initialize the **@State** decorated variables of the child component, but not the **@Link** or **@Prop** decorated variables.
+- The regular variables of the parent component can be used to initialize the **@State** variable of the child component, but cannot be used to initialize the **@Link**, **@Consume**, and **@ObjectLink** variables.
-- The **@State** decorated variable of the parent component can be used to initialize the **@Prop**, **@Link** (using **$**), or normal variables of the child component, but not the **@State** decorated variables of the child component.
+- The **@State** variable of the parent component can be used to initialize the **@Prop**, **@Link** (through **$**), or regular variables of the child component, but cannot be used to initialize the **@Consume** variable.
-- The **@Link** decorated variables of the parent component can be used to initialize the **@Link** decorated or normal variables of the child component. However, initializing the **@State** decorated members of the child component can result in a syntax error. In addition, initializing the **@Prop** decorated variables is not recommended.
+- The **@Link** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
-- The **@Prop** decorated variables of the parent component can be used to initialize the normal variables or **@Prop** decorated variables of the child component, but not the **@State** or **@Link** decorated variables.
+- The **@Prop** variable of the parent component cannot be used to initialize the **@Consume** and **@ObjectLink** variables of the child component.
-- Passing **@StorageLink** and **@StorageProp** from the parent component to the child component is prohibited.
+- **@StorageLink**, **@StorageProp**, **@LocalStorageLink**, and **@LocalStorageProp** variables cannot be initialized from the parent component.
- In addition to the preceding rules, the TypeScript strong type rules need to be followed.
+
+Example:
+```ts
+@Entry
+@Component
+struct Parent {
+ message: string = "Hello World"
+ build() {
+ Column() {
+ Child({
+ stateMessage: this.message,
+ /* ArkTS:ERROR The regular property 'message' cannot be assigned
+ to the @Link property 'linkMessage'.*/
+ linkMessage: this.$message
+ })
+ }
+ .width('100%')
+ }
+}
+
+@Component
+struct Child {
+ @State stateMessage: string = "Hello World"
+ @Link linkMessage: string
+ build() {
+ Column() {
+ Text(this.stateMessage)
+ .fontSize(50)
+ .fontWeight(FontWeight.Bold)
+ }
+ .width('100%')
+ }
+}
+```
diff --git a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md
index 2eae06eca22030673ef35bcf756279444fcd9c60..dd2398a71811e6bbd9b20d0f18ce0659c3bd7acf 100644
--- a/en/application-dev/quick-start/arkts-state-mgmt-concepts.md
+++ b/en/application-dev/quick-start/arkts-state-mgmt-concepts.md
@@ -30,3 +30,5 @@ In the multi-dimensional state management mechanism for ArkUI, UI-related data c
- **@LocalStorageProp**: establishes one-way data binding between a component and the **LocalStorage**. Specifically, this is achieved by decorating the component's state variable with **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**.
- **PersistentStorage**: provides a set of static methods for managing persistent data of applications. Persistent data with specific tags can be linked to the **AppStorage**, and then the persistent data can be accessed through the **AppStorage** APIs. Alternatively, the **@StorageLink** decorator can be used to access the variable that matches the specific key.
- **Environment**: provides the **AppStorage** with an array of environment state attributes that are required by the application and describe the device environment where the application runs. It is a singleton object created by the framework when the application is started.
+
+For details about how to use state variables, see [Restrictions on Data Type Declarations of State Variables](arkts-restrictions-and-extensions.md).
diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md
index b1b7419a32599978dfb561452d56a139df835919..bb3eca101141cf2fcc13c880bc7edd69173d02d7 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -113,6 +113,7 @@
- [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md)
- [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md)
- [shellCmdResult](js-apis-inner-application-shellCmdResult.md)
+ - [WindowExtensionContext](js-apis-inner-application-windowExtensionContext.md)
- wantAgent
- [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md)
- [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md)
@@ -215,9 +216,13 @@
- data/rdb
- [resultSet](js-apis-data-resultset.md)
- File Management
- - [@ohos.environment (Environment)](js-apis-environment.md)
+ - [@ohos.file.environment (Directory Environment Capability)](js-apis-file-environment.md)
- [@ohos.file.fileAccess (User File Access and Management)](js-apis-fileAccess.md)
- [@ohos.file.fileExtensionInfo (User File Extension Information)](js-apis-fileExtensionInfo.md)
+ - [@ohos.file.fs (File Management)](js-apis-file-fs.md)
+ - [@ohos.file.hash (File Hash Processing)](js-apis-file-hash.md)
+ - [@ohos.file.securityLabel (Data Label)](js-apis-file-securityLabel.md)
+ - [@ohos.file.statvfs (File System Space Statistics)](js-apis-file-statvfs.md)
- [@ohos.filemanagement.userFileManager (User Data Management)](js-apis-userFileManager.md)
- [@ohos.multimedia.medialibrary (Media Library Management)](js-apis-medialibrary.md)
- [@ohos.storageStatistics (Application Storage Statistics)](js-apis-storage-statistics.md)
diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md
index da7ec7d145779eb5044427fdee758a34f6b33fdc..9ff98751e425eaca0d814a166f08bdb55cb2083a 100644
--- a/en/application-dev/reference/apis/js-apis-animator.md
+++ b/en/application-dev/reference/apis/js-apis-animator.md
@@ -1,6 +1,6 @@
-# @ohos.animator
+# @ohos.animator (Animator)
-The **animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order.
+The **Animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order.
> **NOTE**
>
@@ -72,7 +72,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
| ID | Error Message|
| --------- | ------- |
-| 100001 | If no page is found for pageId or fail to get object property list. |
+| 100001 | if no page is found for pageId or fail to get object property list. |
**Example**
@@ -283,7 +283,7 @@ export default {
easing: 'friction',
delay: 0,
fill: 'forwards',
- direction: 'normal',
+ direction: "normal",
iterations: 2,
begin: 200.0,
end: 400.0
@@ -296,10 +296,10 @@ export default {
easing: 'friction',
delay: 0,
fill: 'forwards',
- direction: "normal",
+ direction: 'normal',
iterations: 2,
begin: 0,
- end: 400.0,
+ end: 400.0
};
try {
this.animator.reset(options1);
@@ -519,7 +519,7 @@ let options = {
direction: 'normal',
iterations: 3,
begin: 200.0,
- end: 400.0,
+ end: 400.0
};
this.animator = animator.createAnimator(options);
```
diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md
index 0d2aef3e25aa21eb724c8f74f977d901ea12b290..7c2974d0c8fc4eef7a911523fdeb96c596304c94 100644
--- a/en/application-dev/reference/apis/js-apis-appAccount.md
+++ b/en/application-dev/reference/apis/js-apis-appAccount.md
@@ -1,4 +1,4 @@
-# @ohos.account.appAccount
+# @ohos.account.appAccount (App Account Management)
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
@@ -64,7 +64,6 @@ Creates an app account. This API uses an asynchronous callback to return the res
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.createAccount("WangWu", (err) => {
console.log("createAccount err: " + JSON.stringify(err));
@@ -102,7 +101,6 @@ Creates an app account with custom data. This API uses an asynchronous callback
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
customData: {
"age": "10"
@@ -155,7 +153,6 @@ Creates an app account with custom data. This API uses a promise to return the r
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
customData: {
"age": "10"
@@ -215,7 +212,6 @@ Creates an app account implicitly based on the specified account owner. This API
});
}
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.createAccountImplicitly("com.example.accountjsdemo", {
onResult: onResultCallback,
@@ -270,7 +266,6 @@ Creates an app account implicitly based on the specified account owner and optio
});
}
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
authType: "getSocialData",
requiredLabels: [ "student" ]
@@ -311,7 +306,6 @@ Removes an app account. This API uses an asynchronous callback to return the res
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.removeAccount("ZhaoLiu", (err) => {
if (err) {
@@ -356,7 +350,6 @@ Removes an app account. This API uses a promise to return the result.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.removeAccount("Lisi").then(() => {
console.log("removeAccount successfully");
@@ -397,7 +390,6 @@ Sets the access to the data of an account for an app. This API uses an asynchron
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => {
if (err) {
@@ -445,7 +437,6 @@ Sets the access to the data of an account for an app. This API uses a promise to
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => {
console.log("setAppAccess successfully");
@@ -485,7 +476,6 @@ Checks whether an app can access the data of an account. This API uses an asynch
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => {
if (err) {
@@ -532,7 +522,6 @@ Checks whether an app can access the data of an account. This API uses a promise
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => {
console.log("checkAppAccess successfully, isAccessible: " + isAccessible);
@@ -573,7 +562,6 @@ Sets data synchronization for an app account. This API uses an asynchronous call
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => {
console.log("setDataSyncEnabled err: " + JSON.stringify(err));
@@ -617,7 +605,6 @@ Sets data synchronization for an app account. This API uses a promise to return
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => {
console.log('setDataSyncEnabled Success');
@@ -657,7 +644,6 @@ Checks whether data synchronization is enabled for an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => {
if (err) {
@@ -704,7 +690,6 @@ Checks whether data synchronization is enabled for an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => {
console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled);
@@ -744,7 +729,6 @@ Sets a credential for an app account. This API uses an asynchronous callback to
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => {
if (err) {
@@ -791,7 +775,6 @@ Sets a credential for an app account. This API uses a promise to return the resu
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => {
console.log("setCredential successfully");
@@ -831,7 +814,6 @@ Obtains the credential of an app account. This API uses an asynchronous callback
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => {
if (err) {
@@ -878,7 +860,6 @@ Obtains the credential of an app account. This API uses a promise to return the
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => {
console.log("getCredential successfully, credential: " + credential);
@@ -919,7 +900,6 @@ Sets custom data for an app account. This API uses an asynchronous callback to r
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => {
if (err) {
@@ -967,7 +947,6 @@ Sets custom data for an app account. This API uses a promise to return the resul
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => {
console.log("setCustomData successfully");
@@ -1007,7 +986,6 @@ Obtains the custom data of an app account based on the specified key. This API u
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getCustomData("ZhangSan", "age", (err, data) => {
if (err) {
@@ -1054,7 +1032,6 @@ Obtains the custom data of an app account based on the specified key. This API u
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getCustomData("ZhangSan", "age").then((data) => {
console.log("getCustomData successfully, data: " + data);
@@ -1099,7 +1076,6 @@ Obtains the custom data of an app account based on the specified key. The API re
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
let value = appAccountManager.getCustomDataSync("ZhangSan", "age");
console.info("getCustomDataSync successfully, vaue:" + value);
@@ -1114,8 +1090,7 @@ getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void
Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
-
+**Required Permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
@@ -1133,7 +1108,6 @@ Obtains information about all accessible app accounts. This API uses an asynchro
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAllAccounts((err, data) => {
if (err) {
@@ -1153,8 +1127,7 @@ getAllAccounts(): Promise<Array<AppAccountInfo>>
Obtains information about all accessible app accounts. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
-
+**Required Permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
**System capability**: SystemCapability.Account.AppAccount
**Return value**
@@ -1172,7 +1145,6 @@ Obtains information about all accessible app accounts. This API uses a promise t
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAllAccounts().then((data) => {
console.debug("getAllAccounts successfully");
@@ -1190,8 +1162,7 @@ getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccount
Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
-
+**Required Permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
@@ -1212,7 +1183,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => {
if (err) {
@@ -1232,8 +1202,7 @@ getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>>
Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
-
+**Required Permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS
**System capability**: SystemCapability.Account.AppAccount
**Parameters**
@@ -1259,7 +1228,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => {
console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data));
@@ -1299,7 +1267,6 @@ Subscribes to account information changes of apps.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
function changeOnCallback(data){
console.log("receive change data:" + JSON.stringify(data));
}
@@ -1336,8 +1303,7 @@ Unsubscribes from account information changes.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
- function changeOnCallback(data){
+ function changeOnCallback(data) {
console.log("receive change data:" + JSON.stringify(data));
}
try{
@@ -1398,7 +1364,6 @@ Authenticates an app account. This API uses an asynchronous callback to return t
});
}
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", {
onResult: onResultCallback,
@@ -1458,7 +1423,6 @@ Authenticates an app account with customized options. This API uses an asynchron
let options = {
"password": "xxxx",
};
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, {
onResult: onResultCallback,
@@ -1498,7 +1462,6 @@ Obtains the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => {
if (err) {
@@ -1546,7 +1509,6 @@ Obtains the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => {
console.log("getAuthToken successfully, token: " + token);
@@ -1587,7 +1549,6 @@ Sets an authorization token of the specific authentication type for an app accou
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => {
if (err) {
@@ -1635,7 +1596,6 @@ Sets an authorization token of the specific authentication type for an app accou
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => {
console.log("setAuthToken successfully");
@@ -1677,7 +1637,6 @@ Deletes the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => {
if (err) {
@@ -1726,7 +1685,6 @@ Deletes the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => {
console.log("deleteAuthToken successfully");
@@ -1770,7 +1728,6 @@ Sets the visibility of an authorization token to an app. This API uses an asynch
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => {
if (err) {
@@ -1821,7 +1778,6 @@ Sets the visibility of an authorization token to an app. This API uses a promise
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => {
console.log("setAuthTokenVisibility successfully");
@@ -1863,7 +1819,6 @@ Checks the visibility of an authorization token of the specified authentication
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => {
if (err) {
@@ -1912,7 +1867,6 @@ Checks the visibility of an authorization token of the specified authentication
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => {
console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible);
@@ -1951,7 +1905,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => {
if (err) {
@@ -1997,7 +1950,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => {
console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr));
@@ -2037,7 +1989,6 @@ Obtains the authorization list of the specified authentication type for an app a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => {
if (err) {
@@ -2084,7 +2035,6 @@ Obtains the authorization list of the specified authentication type for an app a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => {
console.log("getAuthList successfully, authList: " + authList);
@@ -2123,7 +2073,6 @@ Obtains the authenticator callback for the authentication session. This API uses
```js
import featureAbility from '@ohos.ability.featureAbility';
- let appAccountManager = account_appAccount.createAppAccountManager();
featureAbility.getWant((err, want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
try {
@@ -2183,7 +2132,6 @@ Obtains the authenticator callback for the authentication session. This API uses
```js
import featureAbility from '@ohos.ability.featureAbility';
- let appAccountManager = account_appAccount.createAppAccountManager();
featureAbility.getWant().then((want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
try {
@@ -2236,7 +2184,6 @@ Obtains the authenticator information of an app. This API uses an asynchronous c
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => {
if (err) {
@@ -2281,7 +2228,6 @@ Obtains the authenticator information of an app. This API uses a promise to retu
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => {
console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info));
@@ -2324,7 +2270,6 @@ Checks whether an app account has specific labels. This API uses an asynchronous
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let labels = ["student"];
try {
appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => {
@@ -2375,7 +2320,6 @@ Checks whether an app account has specific labels. This API uses a promise to re
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let labels = ["student"];
try {
appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => {
@@ -2416,7 +2360,6 @@ Deletes the credential of the specified type from an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => {
if (err) {
@@ -2463,7 +2406,6 @@ Deletes the credential of the specified type from an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => {
console.log("deleteCredential successfully");
@@ -2502,7 +2444,6 @@ Selects the accounts that can be accessed by the invoker based on the options. T
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
allowedOwners: [ "com.example.accountjsdemo" ],
requiredLabels: [ "student" ]
@@ -2552,7 +2493,6 @@ Selects the accounts that can be accessed by the invoker based on the options. T
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
allowedOwners: ["com.example.accountjsdemo"]
};
@@ -2597,7 +2537,6 @@ Verifies the credential of an app account. This API uses an asynchronous callbac
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", {
onResult: (resultCode, result) => {
@@ -2644,7 +2583,6 @@ Verifies the user credential. This API uses an asynchronous callback to return t
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
credentialType: "pin",
credential: "123456"
@@ -2692,7 +2630,6 @@ Sets the authenticator attributes of an app. This API uses an asynchronous callb
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
try {
appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", {
onResult: (resultCode, result) => {
@@ -2737,7 +2674,6 @@ Set authenticator properties. This API uses an asynchronous callback to return t
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
let options = {
properties: {"prop1": "value1"}
};
@@ -2780,7 +2716,6 @@ Adds an app account. This API uses an asynchronous callback to return the result
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.addAccount("WangWu", (err) => {
console.log("addAccount err: " + JSON.stringify(err));
});
@@ -2809,7 +2744,6 @@ Adds an app account name and additional information. This API uses an asynchrono
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.addAccount("LiSi", "token101", (err) => {
console.log("addAccount err: " + JSON.stringify(err));
});
@@ -2843,7 +2777,6 @@ Adds an app account name and additional information. This API uses an asynchrono
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.addAccount("LiSi", "token101").then(()=> {
console.log('addAccount Success');
}).catch((err) => {
@@ -2889,7 +2822,6 @@ Adds an app account implicitly based on the specified owner. This API uses an as
});
}
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, {
onResult: onResultCallback,
onRequestRedirected: onRequestRedirectedCallback
@@ -2918,7 +2850,6 @@ Deletes an app account. This API uses an asynchronous callback to return the res
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteAccount("ZhaoLiu", (err) => {
console.log("deleteAccount err: " + JSON.stringify(err));
});
@@ -2951,7 +2882,6 @@ Deletes an app account. This API uses a promise to return the result.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteAccount("ZhaoLiu").then(() => {
console.log('deleteAccount Success');
}).catch((err) => {
@@ -2981,7 +2911,6 @@ Disables an app account from accessing an app. This API uses an asynchronous cal
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => {
console.log("disableAppAccess err: " + JSON.stringify(err));
});
@@ -3015,7 +2944,6 @@ Disables an app account from accessing an app. This API uses a promise to return
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => {
console.log('disableAppAccess Success');
}).catch((err) => {
@@ -3046,7 +2974,6 @@ Enables an app account to access an app. This API uses an asynchronous callback
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => {
console.log("enableAppAccess: " + JSON.stringify(err));
});
@@ -3080,7 +3007,6 @@ Enables an app account to access an app. This API uses a promise to return the r
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => {
console.log('enableAppAccess Success');
}).catch((err) => {
@@ -3112,7 +3038,6 @@ Checks whether data synchronization is enabled for an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => {
console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err));
console.log('checkAppAccountSyncEnable result: ' + result);
@@ -3148,7 +3073,6 @@ Checks whether data synchronization is enabled for an app account. This API uses
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => {
console.log('checkAppAccountSyncEnable, result: ' + data);
}).catch((err) => {
@@ -3180,7 +3104,6 @@ Set credentials for an app account. This API uses an asynchronous callback to re
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => {
console.log("setAccountCredential err: " + JSON.stringify(err));
});
@@ -3215,7 +3138,6 @@ Set credentials for an app account. This API uses a promise to return the result
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => {
console.log('setAccountCredential Success');
}).catch((err) => {
@@ -3247,7 +3169,6 @@ Sets additional information for an app account. This API uses an asynchronous ca
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => {
console.log("setAccountExtraInfo err: " + JSON.stringify(err));
});
@@ -3282,7 +3203,6 @@ Sets additional information for an app account. This API uses a promise to retur
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => {
console.log('setAccountExtraInfo Success');
}).catch((err) => {
@@ -3315,7 +3235,6 @@ Sets data synchronization for an app account. This API uses an asynchronous call
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => {
console.log("setAppAccountSyncEnable err: " + JSON.stringify(err));
});
@@ -3351,7 +3270,6 @@ Sets data synchronization for an app account. This API uses a promise to return
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => {
console.log('setAppAccountSyncEnable Success');
}).catch((err) => {
@@ -3384,7 +3302,6 @@ Sets data to be associated with an app account. This API uses an asynchronous ca
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => {
console.log("setAssociatedData err: " + JSON.stringify(err));
});
@@ -3420,7 +3337,6 @@ Sets data to be associated with an app account. This API uses a promise to retur
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => {
console.log('setAssociatedData Success');
}).catch((err) => {
@@ -3451,7 +3367,6 @@ Obtains information about all accessible app accounts. This API uses an asynchro
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAllAccessibleAccounts((err, data)=>{
console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err));
console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data));
@@ -3481,7 +3396,6 @@ Obtains information about all accessible app accounts. This API uses a promise t
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAllAccessibleAccounts().then((data) => {
console.log('getAllAccessibleAccounts: ' + data);
}).catch((err) => {
@@ -3513,7 +3427,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
const selfBundle = "com.example.actsgetallaaccounts";
appAccountManager.getAllAccounts(selfBundle, (err, data)=>{
console.debug("getAllAccounts err:" + JSON.stringify(err));
@@ -3550,7 +3463,6 @@ Obtains the app accounts that can be accessed by the invoker based on the app ac
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
const selfBundle = "com.example.actsgetallaaccounts";
appAccountManager.getAllAccounts(selfBundle).then((data) => {
console.log('getAllAccounts: ' + data);
@@ -3582,7 +3494,6 @@ Obtains the credential of an app account. This API uses an asynchronous callback
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => {
console.log("getAccountCredential err: " + JSON.stringify(err));
console.log('getAccountCredential result: ' + result);
@@ -3617,7 +3528,6 @@ Obtains the credential of an app account. This API uses a promise to return the
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => {
console.log('getAccountCredential, result: ' + data);
}).catch((err) => {
@@ -3647,7 +3557,6 @@ Obtains additional information of an app account. Additional information refers
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => {
console.log("getAccountExtraInfo err: " + JSON.stringify(err));
console.log('getAccountExtraInfo result: ' + result);
@@ -3681,7 +3590,6 @@ Obtains additional information of an app account. Additional information refers
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => {
console.log('getAccountExtraInfo, result: ' + data);
}).catch((err) => {
@@ -3712,7 +3620,6 @@ Obtains data associated with an app account. This API uses an asynchronous callb
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => {
console.log("getAssociatedData err: " + JSON.stringify(err));
console.log('getAssociatedData result: ' + result);
@@ -3747,7 +3654,6 @@ Obtains data associated with an app account. This API uses a promise to return t
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => {
console.log('getAssociatedData: ' + data);
}).catch((err) => {
@@ -3778,7 +3684,6 @@ Subscribes to account information changes of apps.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
function changeOnCallback(data){
console.debug("receive change data:" + JSON.stringify(data));
}
@@ -3812,7 +3717,6 @@ Unsubscribes from account information changes.
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
function changeOnCallback(data){
console.debug("receive change data:" + JSON.stringify(data));
appAccountManager.off('change', function(){
@@ -3866,7 +3770,6 @@ Authenticates an app account with customized options. This API uses an asynchron
});
}
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, {
onResult: onResultCallback,
onRequestRedirected: onRequestRedirectedCallback
@@ -3897,7 +3800,6 @@ Obtains the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => {
console.log('getOAuthToken err: ' + JSON.stringify(err));
console.log('getOAuthToken token: ' + data);
@@ -3933,7 +3835,6 @@ Obtains the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => {
console.log('getOAuthToken token: ' + data);
}).catch((err) => {
@@ -3965,7 +3866,6 @@ Sets an authorization token of the specific authentication type for an app accou
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => {
console.log('setOAuthToken err: ' + JSON.stringify(err));
});
@@ -4000,7 +3900,6 @@ Sets an authorization token of the specific authentication type for an app accou
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => {
console.log('setOAuthToken successfully');
}).catch((err) => {
@@ -4033,7 +3932,6 @@ Deletes the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => {
console.log('deleteOAuthToken err: ' + JSON.stringify(err));
});
@@ -4069,7 +3967,6 @@ Deletes the authorization token of the specified authentication type for an app
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => {
console.log('deleteOAuthToken successfully');
}).catch((err) => {
@@ -4102,7 +3999,6 @@ Sets the visibility of an authorization token to an app. This API uses an asynch
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => {
console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
});
@@ -4138,7 +4034,6 @@ Sets the visibility of an authorization token to an app. This API uses a promise
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => {
console.log('setOAuthTokenVisibility successfully');
}).catch((err) => {
@@ -4170,7 +4065,6 @@ Checks the visibility of an authorization token of the specified authentication
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => {
console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
console.log('checkOAuthTokenVisibility isVisible: ' + data);
@@ -4206,7 +4100,6 @@ Checks the visibility of an authorization token of the specified authentication
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => {
console.log('checkOAuthTokenVisibility isVisible: ' + data);
}).catch((err) => {
@@ -4237,7 +4130,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses an a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => {
console.log("getAllOAuthTokens err: " + JSON.stringify(err));
console.log('getAllOAuthTokens data: ' + JSON.stringify(data));
@@ -4272,7 +4164,6 @@ Obtains all tokens visible to the invoker for an app account. This API uses a pr
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => {
console.log('getAllOAuthTokens data: ' + JSON.stringify(data));
}).catch((err) => {
@@ -4303,7 +4194,6 @@ Obtains the authorization list of the specified authentication type for an app a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => {
console.log('getOAuthList err: ' + JSON.stringify(err));
console.log('getOAuthList data: ' + JSON.stringify(data));
@@ -4338,7 +4228,6 @@ Obtains the authorization list of the specified authentication type for an app a
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => {
console.log('getOAuthList data: ' + JSON.stringify(data));
}).catch((err) => {
@@ -4369,7 +4258,6 @@ Obtains the authenticator callback for an authentication session. This API uses
```js
import featureAbility from '@ohos.ability.featureAbility';
- let appAccountManager = account_appAccount.createAppAccountManager();
featureAbility.getWant((err, want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => {
@@ -4415,7 +4303,6 @@ Obtains the authenticator callback for an authentication session. This API uses
```js
import featureAbility from '@ohos.ability.featureAbility';
- let appAccountManager = account_appAccount.createAppAccountManager();
featureAbility.getWant().then((want) => {
var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
@@ -4454,7 +4341,6 @@ Obtains the authenticator information of an app. This API uses an asynchronous c
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => {
console.log("getAuthenticatorInfo err: " + JSON.stringify(err));
console.log('getAuthenticatorInfo data: ' + JSON.stringify(data));
@@ -4488,7 +4374,6 @@ Obtains the authenticator information of an app. This API uses a promise to retu
**Example**
```js
- let appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => {
console.log('getAuthenticatorInfo: ' + JSON.stringify(data));
}).catch((err) => {
@@ -4883,7 +4768,7 @@ Creates an app account implicitly based on the specified account owner. This API
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. |
| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.|
-### addAccountImplicitlydeprecated
+### addAccountImplicitly(deprecated)
addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
@@ -4922,7 +4807,7 @@ Authenticates an app account to obtain the authorization token. This API uses an
| options | {[key: string]: Object} | Yes | Options for the authentication. |
| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.|
-### authenticatedeprecated
+### authenticate(deprecated)
authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
similarity index 96%
rename from en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md
rename to en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
index 9ecffc326e125b6e7dbe0ecd3cf03bfc3d2fa7dd..2b868190b0b901638830d8051a2d973188c43d41 100644
--- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md
+++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
@@ -1,6 +1,6 @@
-# @ohos.application.DataShareExtensionAbility
+# @ohos.application.DataShareExtensionAbility (DataShare Extension Ability)
-The **DataShareExtensionAbility** module provides data share services based on the Extension ability.
+The **DataShareExtensionAbility** module provides data share services based on the ExtensionAbility.
>**NOTE**
>
@@ -22,12 +22,11 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
The URIs are in the following format:
**Scheme://authority/path**
-
- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module.
- *authority*: [userinfo@]host[:port]
- - *userinfo*: login information, which can be left unspecified.
- - *host*: server address. It is the target device ID for cross-device access and empty for local device access.
- - *port*: port number of the server, which can be left unspecified.
+ - *userinfo*: login information, which can be left unspecified.
+ - *host*: server address. It is the target device ID for cross-device access and empty for local device access.
+ - *port*: port number of the server, which can be left unspecified.
- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional.
Example:
@@ -76,7 +75,8 @@ let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want, callback) {
rdb.getRdbStore(this.context, {
- name: DB_NAME
+ name: DB_NAME,
+ securityLevel: rdb.SecurityLevel.S1
}, function (err, data) {
console.log('getRdbStore done, data : ' + data);
rdbStore = data;
diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
index 6080d2c9bc52e30b6fa987f9cb65ea9b42a28024..c05f331ad7f1fa1a9db31080bd1cc06ad9767054 100644
--- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
+++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md
@@ -187,7 +187,7 @@ let wantAgentInfo = {
wants: [
{
bundleName: "com.example.myapplication",
- abilityName: "EntryAbility"
+ abilityName: "com.example.myapplication.MainAbility"
}
],
operationType: wantAgent.OperationType.START_ABILITY,
@@ -207,7 +207,7 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.backgroundTaskManager';
-import wantAgent from '@ohos.wantAgent';
+import wantAgent from '@ohos.app.ability.wantAgent';
function callback(err, data) {
if (err) {
@@ -276,7 +276,7 @@ let wantAgentInfo = {
wants: [
{
bundleName: "com.example.myapplication",
- abilityName: "EntryAbility"
+ abilityName: "com.example.myapplication.MainAbility"
}
],
operationType: wantAgent.OperationType.START_ABILITY,
@@ -299,7 +299,7 @@ Stage model:
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.backgroundTaskManager';
-import wantAgent from '@ohos.wantAgent';
+import wantAgent from '@ohos.app.ability.wantAgent';
export default class EntryAbility extends UIAbility {
onCreate(want, launchParam) {
diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md
index 2bb3159fc3912a6a1fe272451ce31aa812052432..89cd4ab39ee2d9a7c7e0a4f9b03a4755b55b864f 100644
--- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md
+++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md
@@ -46,7 +46,7 @@ batteryStats.getBatteryStats()
console.info('battery statistics info: ' + data);
})
.catch(err => {
- console.error('get battery statisitics failed, err: ' + err);
+ console.error('get battery statistics failed, err: ' + err);
});
```
@@ -81,7 +81,7 @@ batteryStats.getBatteryStats((err, data) => {
if (typeof err === 'undefined') {
console.info('battery statistics info: ' + data);
} else {
- console.error('get battery statisitics failed, err: ' + err);
+ console.error('get battery statistics failed, err: ' + err);
}
});
```
@@ -123,7 +123,7 @@ try {
var value = batteryStats.getAppPowerValue(10021);
console.info('battery statistics value of app is: ' + value);
} catch(err) {
- console.error('get battery statisitics value of app failed, err: ' + err);
+ console.error('get battery statistics value of app failed, err: ' + err);
}
```
@@ -164,7 +164,7 @@ try {
var percent = batteryStats.getAppPowerPercent(10021);
console.info('battery statistics percent of app is: ' + percent);
} catch(err) {
- console.error('get battery statisitics percent of app failed, err: ' + err);
+ console.error('get battery statistics percent of app failed, err: ' + err);
}
```
@@ -205,7 +205,7 @@ try {
var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
- console.error('get battery statisitics percent of hardware failed, err: ' + err);
+ console.error('get battery statistics percent of hardware failed, err: ' + err);
}
```
@@ -246,7 +246,7 @@ try {
var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
- console.error('get battery statisitics percent of hardware failed, err: ' + err);
+ console.error('get battery statistics percent of hardware failed, err: ' + err);
}
```
diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md
index cb1311397a52d39e41466c33135bdc93164a0807..b30722bd2fddd6ef83914ffe6b8a3421831935ce 100644
--- a/en/application-dev/reference/apis/js-apis-camera.md
+++ b/en/application-dev/reference/apis/js-apis-camera.md
@@ -12,9 +12,9 @@ import camera from '@ohos.multimedia.camera';
## camera.getCameraManager
-getCameraManager(context: Context, callback: AsyncCallback): void
+getCameraManager(context: Context): CameraManager
-Obtains a **CameraManager** instance. This API uses an asynchronous callback to return the result.
+Obtains a **CameraManager** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -23,46 +23,17 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------- | ---- | ---------------------------- |
| context | [Context](js-apis-inner-app-context.md) | Yes | Application context. |
-| callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.|
-
-**Example**
-
-```js
-camera.getCameraManager(context, (err, cameraManager) => {
- if (err) {
- console.error(`Failed to get the CameraManager instance ${err.message}`);
- return;
- }
- console.log('Callback returned with the CameraManager instance');
-});
-```
-
-## camera.getCameraManager
-
-getCameraManager(context: Context): Promise
-
-Obtains a **CameraManager** instance. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------- | ------- | ---- | ------------ |
-| context | [Context](js-apis-inner-app-context.md) | Yes | Application context.|
**Return value**
-| Type | Description |
-| ----------------------------------------- | ----------------------------------- |
-| Promise<[CameraManager](#cameramanager)\> | Promise used to return the **CameraManager** instance.|
+| Type | Description |
+| ----------------------------------------------- | ---------------------------- |
+| [CameraManager](#cameramanager) | **CameraManager** instance obtained. |
**Example**
```js
-camera.getCameraManager(context).then((cameraManager) => {
- console.log('Promise returned with the CameraManager instance.');
-})
+let cameraManager = camera.getCameraManager(context);
```
## CameraStatus
@@ -71,12 +42,12 @@ Enumerates the camera statuses.
**System capability**: SystemCapability.Multimedia.Camera.Core
-| Name | Value | Description |
-| ------------------------- | ---- | ------------ |
+| Name | Value | Description |
+| ------------------------- | ---- | ------------ |
| CAMERA_STATUS_APPEAR | 0 | A camera appears. |
-| CAMERA_STATUS_DISAPPEAR | 1 | The camera disappears.|
-| CAMERA_STATUS_AVAILABLE | 2 | The camera is available. |
-| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable.|
+| CAMERA_STATUS_DISAPPEAR | 1 | The camera disappears. |
+| CAMERA_STATUS_AVAILABLE | 2 | The camera is available. |
+| CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable. |
## Profile
@@ -123,64 +94,54 @@ Defines the camera output capability.
| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording profiles. |
| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.|
-## CameraManager
-
-Implements camera management. Before calling any API in **CameraManager**, you must use **getCameraManager** to obtain a **CameraManager** instance.
-
-### getSupportedCameras
-
-getSupportedCameras(callback: AsyncCallback\>): void
+## CameraErrorCode
-Obtains supported cameras. This API uses an asynchronous callback to return the result.
+Enumerates the camera error codes, which are returned when an API call is incorrect or the **on()** API is used to listen for the error status.
**System capability**: SystemCapability.Multimedia.Camera.Core
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------- | ---- | ------------------------------- |
-| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.|
+| Name | Value | Description |
+| ------------------------- | ---- | ------------ |
+| INVALID_ARGUMENT | 7400101 | A parameter is missing or the parameter type is incorrect. |
+| OPERATION_NOT_ALLOWED | 7400102 | The operation is not allowed. |
+| SESSION_NOT_CONFIG | 7400103 | The session is not configured. |
+| SESSION_NOT_RUNNING | 7400104 | The session is not running. |
+| SESSION_CONFIG_LOCKED | 7400105 | The session configuration is locked. |
+| DEVICE_SETTING_LOCKED | 7400106 | The device setting is locked. |
+| CONFILICT_CAMERA | 7400107 | The device is already started. |
+| DEVICE_DISABLED | 7400108 | The camera is disabled for security reasons. |
+| SERVICE_FATAL_ERROR | 7400201 | An error occurs in the camera service. |
-**Example**
+## CameraManager
-```js
-cameraManager.getSupportedCameras((err, cameras) => {
- if (err) {
- console.error(`Failed to get the cameras. ${err.message}`);
- return;
- }
- console.log(`Callback returned with an array of supported cameras: ${cameras.length}`);
-})
-```
+Implements camera management. Before calling any API in **CameraManager**, you must use **getCameraManager** to obtain a **CameraManager** instance.
### getSupportedCameras
-getSupportedCameras(): Promise\>
+getSupportedCameras(): Array
-Obtains supported cameras. This API uses a promise to return the result.
+Obtains supported cameras. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ----------------------------------------------- | ------------------------- |
-| Promise\> | Promise used to return the array of supported cameras.|
-
+| Type | Description |
+| ----------------------------------------------- | ---------------------------- |
+| Array<[CameraDevice](#cameradevice)> | An array of supported cameras. |
**Example**
```js
-cameraManager.getSupportedCameras().then((cameras) => {
- console.log(`Promise returned with an array of supported cameras: ${cameras.length}`);
-})
+let cameras = cameraManager.getSupportedCameras();
+
```
### getSupportedOutputCapability
-getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void
+getSupportedOutputCapability(cameraDevice:CameraDevice): CameraOutputCapability
-Obtains the output capability supported by a camera. This API uses an asynchronous callback to return the result.
+Obtains the output capability supported by a camera. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -189,52 +150,19 @@ Obtains the output capability supported by a camera. This API uses an asynchrono
| Name | Type | Mandatory| Description |
| ------------ |--------------------------------------------------------------- | -- | -------------------------- |
| cameraDevice | [CameraDevice](#cameradevice) | Yes| Target camera, which is obtained through **getSupportedCameras**. |
-| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes| Callback used to return the output capability.|
-
-**Example**
-
-```js
-cameraManager.getSupportedCameras().then((cameras) => {
- let cameraDevice = cameras[0];
- cameraManager.getSupportedOutputCapability(cameraDevice, (err, CameraOutputCapability) => {
- if (err) {
- console.error(`Failed to get the outputCapability. ${err.message}`);
- return;
- }
- console.log('Callback returned with an array of supported outputCapability');
- })
-})
-```
-
-### getSupportedOutputCapability
-
-getSupportedOutputCapability(camera:CameraDevice): Promise
-
-Obtains the output capability supported by a camera. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------------- | ---- | ---------- |
-| cameradevice | [CameraDevice](#cameradevice) | Yes | Target camera, which is obtained through **getSupportedCameras**. |
**Return value**
-| Type | Description |
-| -------------------------------------------------------------- | ----------------------------- |
-| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.|
+| Type | Description |
+| ----------------------------------------------- | ---------------------------- |
+| [CameraOutputCapability](#cameraoutputcapability) | Camera output capability obtained. |
**Example**
```js
-cameraManager.getSupportedCameras().then((cameras) => {
- let cameraDevice = cameras[0];
- cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => {
- console.log('Promise returned with an array of supported outputCapability');
- })
-})
+let cameraDevice = cameras[0];
+let cameraOutputCapability = cameraManager.getSupportedOutputCapability(cameraDevice);
+
```
### isCameraMuted
@@ -306,9 +234,9 @@ cameraManager.muteCamera(mute);
### createCameraInput
-createCameraInput(camera: CameraDevice, callback: AsyncCallback): void
+createCameraInput(camera: CameraDevice): CameraInput
-Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses an asynchronous callback to return the result.
+Creates a **CameraInput** instance with the specified **CameraDevice** object. This API returns the result synchronously.
**Required permissions**: ohos.permission.CAMERA
@@ -318,58 +246,32 @@ Creates a **CameraInput** instance with the specified **CameraDevice** object. T
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | --------------------------------- |
-| cameraDevice | [CameraDevice](#cameradevice) | Yes | Target **CameraDevice** object, which is obtained through **getSupportedCameras**. |
-| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. |
-
-**Example**
-
-```js
-let cameraDevice = cameras[0];
-cameraManager.createCameraInput(cameraDevice, (err, cameraInput) => {
- if (err) {
- console.error(`Failed to create the CameraInput instance. ${err.message}`);
- return;
- }
- console.log('Callback returned with the CameraInput instance.');
-})
-```
-
-### createCameraInput
-
-createCameraInput(cameraDevice: CameraDevice): Promise
-
-Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.CAMERA
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------- | ---- | ---------- |
-| cameraDevice | [CameraDevice](#cameradevice) | Yes | Target **CameraDevice** object, which is obtained through **getSupportedCameras**.|
+| cameraDevice | [CameraDevice](#cameradevice) | Yes | Target **CameraDevice** object, which is obtained through **getSupportedCameras**. |
**Return value**
-| Type | Description |
-| ------------------------------------- | ------------------------------------ |
-| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraInput](#camerainput) | **CameraInput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
let cameraDevice = cameras[0];
-cameraManager.createCameraInput(cameraDevice).then((cameraInput) => {
- console.log('Promise returned with the CameraInput instance');
-})
+let cameraInput;
+try {
+ cameraInput = cameraManager.createCameraInput(cameraDevice);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createCameraInput
-createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void
+createCameraInput(position: CameraPosition, type: CameraType): CameraInput
-Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result.
+Creates a **CameraInput** instance with the specified camera position and type. This API returns the result synchronously.
**Required permissions**: ohos.permission.CAMERA
@@ -381,45 +283,12 @@ Creates a **CameraInput** instance with the specified camera position and type.
| -------- | ------------------------------------------- | ---- | --------------------------------- |
| position | [CameraPosition](#cameraposition) | Yes | Camera position, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera position information. |
| type | [CameraType](#cameratype) | Yes | Camera type, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera type information. |
-| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. |
-
-**Example**
-
-```js
-let cameraDevice = cameras[0];
-let position = cameraDevice.cameraPosition;
-let type = cameraDevice.cameraType;
-cameraManager.createCameraInput(position, type, (err, cameraInput) => {
- if (err) {
- console.error(`Failed to create the CameraInput instance. ${err.message}`);
- return;
- }
- console.log('Callback returned with the CameraInput instance');
-})
-```
-
-### createCameraInput
-
-createCameraInput(position: CameraPosition, type:CameraType ): Promise
-
-Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result.
-
-**Required permissions**: ohos.permission.CAMERA
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------- | ---- | ------------ |
-| position | [CameraPosition](#cameraposition) | Yes | Camera position, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera position information. |
-| type | [CameraType](#cameratype) | Yes | Camera type, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera type information. |
**Return value**
-| Type | Description |
-| ------------------------------------- | ------------------------------------ |
-| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraInput](#camerainput) | **CameraInput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
@@ -427,16 +296,20 @@ Creates a **CameraInput** instance with the specified camera position and type.
let cameraDevice = cameras[0];
let position = cameraDevice.cameraPosition;
let type = cameraDevice.cameraType;
-cameraManager.createCameraInput(position, type).then((cameraInput) => {
- console.log('Promise returned with the CameraInput instance');
-})
+let cameraInput;
+try {
+ cameraInput = cameraManager.createCameraInput(position, type);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createPreviewOutput
-createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void
+createPreviewOutput(profile: Profile, surfaceId: string): PreviewOutput
-Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result.
+Creates a **PreviewOutput** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -446,56 +319,31 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to
| -------- | ----------------------------------------------- | ---- | ------------------------------- |
| profile | [Profile](#profile) | Yes | Supported preview profiles, which are obtained through **getSupportedOutputCapability**.|
| surfaceId| string | Yes | Surface ID, which is obtained from [XComponent](../arkui-ts/ts-basic-components-xcomponent.md) or [ImageReceiver](js-apis-image.md#imagereceiver9).|
-| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.|
-
-**Example**
-
-```js
-let profile = cameraoutputcapability.previewProfiles[0];
-cameraManager.createPreviewOutput(profile, surfaceId, (err, previewOutput) => {
- if (err) {
- console.error(`Failed to gcreate previewOutput. ${err.message}`);
- return;
- }
- console.log('Callback returned with previewOutput created.');
-})
-```
-
-### createPreviewOutput
-
-createPreviewOutput(profile: Profile, surfaceId: string): Promise
-
-Creates a **PreviewOutput** instance. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------| ---- | ----------------- |
-| profile | [Profile](#profile) | Yes | Supported preview profiles, which are obtained through **getSupportedOutputCapability**.|
-| surfaceId| string | Yes | Surface ID, which is obtained from [XComponent](../arkui-ts/ts-basic-components-xcomponent.md) or [ImageReceiver](js-apis-image.md#imagereceiver9).|
**Return value**
-| Type | Description |
-| ---------------------------------------- | ---------------------------------------- |
-| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| [PreviewOutput](#previewoutput) | **PreviewOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-let profile = cameraoutputcapability.previewProfiles[0];
-cameraManager.createPreviewOutput(profile, surfaceId).then((previewOutput) => {
- console.log('Promise returned with previewOutput created.');
-})
+let profile = cameraOutputCapability.previewProfiles[0];
+let previewOutput;
+try {
+ previewOutput = cameraManager.createPreviewOutput(profile, surfaceId);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createPhotoOutput
-createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void
+createPhotoOutput(profile: Profile, surfaceId: string): PhotoOutput
-Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result.
+Creates a **PhotoOutput** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -505,56 +353,31 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re
| -------- | ------------------------------------------- | ---- | ----------------------------------- |
| profile | [Profile](#profile) | Yes | Supported shooting profiles, which are obtained through **getSupportedOutputCapability**.|
| surfaceId| string | Yes | Surface ID, which is obtained from [ImageReceiver](js-apis-image.md#imagereceiver9).|
-| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. |
-
-**Example**
-
-```js
-let profile = cameraoutputcapability.photoProfiles[0];
-cameraManager.createPhotoOutput(profile, surfaceId, (err, photoOutput) => {
- if (err) {
- console.error(`Failed to create photoOutput. ${err.message}`);
- return;
- }
- console.log('Callback returned with photoOutput created.');
-})
-```
-
-### createPhotoOutput
-
-createPhotoOutput(profile: Profile, surfaceId: string): Promise
-
-Creates a **PhotoOutput** instance. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------| ---- | ----------- |
-| profile | [Profile](#profile) | Yes | Supported shooting profiles, which are obtained through **getSupportedOutputCapability**.|
-| surfaceId| string | Yes | Surface ID, which is obtained from [ImageReceiver](js-apis-image.md#imagereceiver9).|
**Return value**
-| Type | Description |
-| ------------------------------------- | -------------------------------------- |
-| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| [PhotoOutput](#photooutput) | **PhotoOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-let profile = cameraoutputcapability.photoProfiles[0];
-cameraManager.createPhotoOutput(profile, surfaceId).then((photoOutput) => {
- console.log('Promise returned with photoOutput created.');
-})
+let profile = cameraOutputCapability.photoProfiles[0];
+let photoOutput;
+try {
+ photoOutput = cameraManager.createPhotoOutput(profile, surfaceId);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createVideoOutput
-createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void
+createVideoOutput(profile: VideoProfile, surfaceId: string): VideoOutput
-Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result.
+Creates a **VideoOutput** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -564,56 +387,31 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re
| -------- | ------------------------------------------- | ---- | ------------------------------ |
| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profiles, which are obtained through **getSupportedOutputCapability**.|
| surfaceId| string | Yes | Surface ID, which is obtained from [VideoRecorder](js-apis-media.md#videorecorder9).|
-| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.|
-
-**Example**
-
-```js
-let profile = cameraoutputcapability.videoProfiles[0];
-cameraManager.createVideoOutput(profile, surfaceId, (err, videoOutput) => {
- if (err) {
- console.error(`Failed to create videoOutput. ${err.message}`);
- return;
- }
- console.log('Callback returned with an array of supported outputCapability' );
-})
-```
-
-### createVideoOutput
-
-createVideoOutput(profile: VideoProfile, surfaceId: string): Promise
-
-Creates a **VideoOutput** instance. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------| ---- | ---------- |
-| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profiles, which are obtained through **getSupportedOutputCapability**.|
-| surfaceId| string | Yes | Surface ID, which is obtained from [VideoRecorder](js-apis-media.md#videorecorder9).|
**Return value**
-| Type | Description |
-| ------------------------------------- | -------------------------------------- |
-| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| [VideoOutput](#videooutput) | **VideoOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-let profile = cameraoutputcapability.videoProfiles[0];
-cameraManager.createVideoOutput(profile, surfaceId).then((videoOutput) => {
- console.log('Promise returned with videoOutput created.');
-})
+let profile = cameraOutputCapability.videoProfiles[0];
+let videoOutput;
+try {
+ videoOutput = cameraManager.createVideoOutput(profile, surfaceId);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createMetadataOutput
-createMetadataOutput(metadataObjectTypes:Array, callback: AsyncCallback): void
+createMetadataOutput(metadataObjectTypes:Array): MetadataOutput
-Creates a **MetadataOutput** instance. This API uses an asynchronous callback to return the result.
+Creates a **MetadataOutput** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -622,96 +420,50 @@ Creates a **MetadataOutput** instance. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------------- | --- | ---------------------------- |
| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**.|
-| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance. |
-
-**Example**
-
-```js
-let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
-cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataOutput) => {
- if (err) {
- console.error(`Failed to create metadataOutput. ${err.message}`);
- return;
- }
- console.log('Callback returned with metadataOutput created.');
-})
-```
-
-### createMetadataOutput
-
-createMetadataOutput(metadataObjectTypes:Array): Promise
-
-Creates a **MetadataOutput** instance. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------------------- | -------------------------------------------------- | --- | -------------------- |
-| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**. |
**Return value**
-| Type | Description |
-| ------------------------------------------ | ----------------------------------------- |
-| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.|
-
-**Example**
-
-```js
-let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes;
-cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataOutput) => {
- console.log('Promise returned with metadataOutput created.');
-})
-```
-
-### createCaptureSession
-
-createCaptureSession(callback: AsyncCallback): void
-
-Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------------------- | ----------------------------------------- | ----------- | ---------------------------- |
-| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [MetadataOutput](#metadataoutput) | **MetadataOutput** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-cameraManager.createCaptureSession((err, captureSession) => {
- if (err) {
- console.error(`Failed to create captureSession. ${err.message}`);
- return;
- }
- console.log('Callback returned with captureSession created.');
-})
+let metadataObjectTypes = cameraOutputCapability.supportedMetadataObjectTypes;
+let metadataOutput;
+try {
+ metadataOutput = cameraManager.createMetadataOutput(metadataObjectTypes);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### createCaptureSession
-createCaptureSession(): Promise
+createCaptureSession(): CaptureSession
-Creates a **CaptureSession** instance. This API uses a promise to return the result.
+Creates a **CaptureSession** instance. This API returns the result synchronously.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ------------------------------------------- | ---------------------------------------- |
-| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CaptureSession](#capturesession) | **CaptureSession** instance created. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-cameraManager.createCaptureSession().then((captureSession) => {
- console.log('Promise returned with captureSession created.');
-})
+let captureSession;
+try {
+ captureSession = cameraManager.createCaptureSession();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### on('cameraStatus')
@@ -726,17 +478,13 @@ Listens for camera status changes. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | --------- |
-| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**, indicating the camera status change event.|
+| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**. The callback function returns the camera information, including the device and device status (available or unavailable). The event can be listened for only when a **CameraManager** instance is obtained.|
| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. |
**Example**
```js
-cameraManager.on('cameraStatus', (err, cameraStatusInfo) => {
- if (err) {
- console.error(`Failed to get cameraStatus callback. ${err.message}`);
- return;
- }
+cameraManager.on('cameraStatus', (cameraStatusInfo) => {
console.log(`camera : ${cameraStatusInfo.camera.cameraId}`);
console.log(`status: ${cameraStatusInfo.status}`);
})
@@ -756,17 +504,14 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | --------------- | ---- | --------- |
-| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.|
+| type | string | Yes | Event type. The value is fixed at **'cameraMute'**. The callback function returns the mute status changes. The event can be listened for only when a **CameraManager** instance is obtained.|
| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. |
**Example**
```js
-cameraManager.on('cameraMute', (err, curMuetd) => {
- if (err) {
- console.error(`Failed to get cameraMute callback. ${err.message}`);
- return;
- }
+cameraManager.on('cameraMute', (curMuetd) => {
+ let isMuted = curMuetd;
})
```
@@ -801,7 +546,7 @@ Enumerates the camera types.
| Name | Value | Description |
| ----------------------- | ---- | -------------- |
-| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type. |
+| CAMERA_TYPE_DEFAULT | 0 | Unspecified camera type. |
| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. |
| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. |
| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. |
@@ -882,14 +627,14 @@ Opens this camera. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
cameraInput.open((err) => {
if (err) {
- console.error(`Failed to open the camera. ${err.message}`);
+ console.error(`Failed to open the camera. ${err.code}`);
return;
}
console.log('Callback returned with camera opened.');
@@ -908,14 +653,16 @@ Opens this camera. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
cameraInput.open().then(() => {
console.log('Promise returned with camera opened.');
-})
+}).catch((err) => {
+ console.error(`Failed to open the camera. ${err.code}`);
+});
```
### close
@@ -930,14 +677,14 @@ Closes this camera. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
cameraInput.close((err) => {
if (err) {
- console.error(`Failed to close the cameras. ${err.message}`);
+ console.error(`Failed to close the cameras. ${err.code}`);
return;
}
console.log('Callback returned with camera closed.');
@@ -963,111 +710,39 @@ Closes this camera. This API uses a promise to return the result.
```js
cameraInput.close().then(() => {
console.log('Promise returned with camera closed.');
-})
+}).catch((err) => {
+ console.error(`Failed to close the cameras. ${err.code}`);
+});
```
-### release
+### on('error')
-release\(callback: AsyncCallback\): void
+on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback): void
-Releases this camera. This API uses an asynchronous callback to return the result.
+Listens for **CameraInput** errors. This API uses a callback to return the result.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------------------- | --- | ------------------------------------------- |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code, for example, an error code indicating that the device is unavailable or a conflict occurs. The event can be listened for only when a **CameraInput** instance is obtained.|
+| cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.|
+| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
```js
-cameraInput.release((err) => {
- if (err) {
- console.error(`Failed to release the CameraInput instance ${err.message}`);
- return;
- }
- console.log('Callback invoked to indicate that the CameraInput instance is released successfully.');
-});
+let cameraDevice = cameras[0];
+cameraInput.on('error', cameraDevice, (error) => {
+ console.log(`Camera input error code: ${error.code}`);
+})
```
-### release
-
-release(): Promise
+## FlashMode
-Releases this camera. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
-
-**Example**
-
-```js
-cameraInput.release().then(() => {
- console.log('Promise returned to indicate that the CameraInput instance is released successfully.');
-})
-```
-
-### on('error')
-
-on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback): void
-
-Listens for **CameraInput** errors. This API uses a callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------- | --- | ------------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the camera input error event.|
-| cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.|
-| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. |
-
-**Example**
-
-```js
-let cameraDevice = cameras[0];
-cameraInput.on('error', cameraDevice, (cameraInputError) => {
- console.log(`Camera input error code: ${cameraInputError.code}`);
-})
-```
-
-## CameraInputErrorCode
-
-Enumerates the error codes used for camera input.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| ------------------------- | ---- | ---------- |
-| ERROR_UNKNOWN | -1 | Unknown error.|
-| ERROR_NO_PERMISSION | 0 | You do not have the required permission.|
-| ERROR_DEVICE_PREEMPTED | 1 | The camera is preempted.|
-| ERROR_DEVICE_DISCONNECTED | 2 | The camera is disconnected.|
-| ERROR_DEVICE_IN_USE | 3 | The camera is in use.|
-| ERROR_DRIVER_ERROR | 4 | Driver error. |
-
-## CameraInputError
-
-Defines an error object used for **[CameraInput](#camerainput)**.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory | Description |
-| ---- | --------------------------------------------- | ------------ |--------------------- |
-| code | [CameraInputErrorCode](#camerainputerrorcode) | Yes |**CameraInput** error code.|
-
-
-## FlashMode
-
-Enumerates the flash modes.
+Enumerates the flash modes.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1135,56 +810,32 @@ Implements a shooting session, which saves all **[CameraInput](#camerainput)** a
### beginConfig
-beginConfig\(callback: AsyncCallback\): void
-
-Starts configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-captureSession.beginConfig((err) => {
- if (err) {
- console.error(`Failed to start the configuration. ${err.message}`);
- return;
- }
- console.log('Callback invoked to indicate the begin config success.');
-});
-```
-
-### beginConfig
-
-beginConfig\(\): Promise
+beginConfig(): void
-Starts configuration for this **CaptureSession** instance. This API uses a promise to return the result.
+Starts configuration for the session.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
-
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.beginConfig().then(() => {
- console.log('Promise returned to indicate the begin config success.');
-})
+try {
+ captureSession.beginConfig();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### commitConfig
-commitConfig\(callback: AsyncCallback\): void
+commitConfig(callback: AsyncCallback): void
Commits the configuration for this **CaptureSession** instance. This API uses an asynchronous callback to return the result.
@@ -1194,14 +845,14 @@ Commits the configuration for this **CaptureSession** instance. This API uses an
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.commitConfig((err) => {
if (err) {
- console.error(`Failed to commit the configuration. ${err.message}`);
+ console.log('Failed to commitConfig '+ err.code);
return;
}
console.log('Callback invoked to indicate the commit config success.');
@@ -1210,7 +861,7 @@ captureSession.commitConfig((err) => {
### commitConfig
-commitConfig\(\): Promise
+commitConfig(): Promise
Commits the configuration for this **CaptureSession** instance. This API uses a promise to return the result.
@@ -1220,48 +871,24 @@ Commits the configuration for this **CaptureSession** instance. This API uses a
| Type | Description |
| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.commitConfig().then(() => {
console.log('Promise returned to indicate the commit config success.');
-})
-```
-
-### addInput
-
-addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void
-
-Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------------------- | ---- | ------------------------ |
-| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
-
-**Example**
-
-```js
-captureSession.addInput(cameraInput, (err) => {
- if (err) {
- console.error(`Failed to add the CameraInput instance. ${err.message}`);
- return;
- }
- console.log('Callback invoked to indicate that the CameraInput instance is added.');
+}).catch((err) => {
+ // If the operation fails, error.code is returned and processed.
+ console.log('Failed to commitConfig '+ err.code);
});
```
### addInput
-addInput\(cameraInput: CameraInput\): Promise
+addInput(cameraInput: CameraInput): void
-Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses a promise to return the result.
+Adds a [CameraInput](#camerainput) instance to the session.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1273,50 +900,26 @@ Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This
**Return value**
-| Type | Description |
-| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
-
-**Example**
-
-```js
-captureSession.addInput(cameraInput).then(() => {
- console.log('Promise used to indicate that the CameraInput instance is added.');
-})
-```
-
-### removeInput
-
-removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void
-
-Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | --------------------------- | ---- | ------------------------ |
-| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.removeInput(cameraInput, (err) => {
- if (err) {
- console.error(`Failed to remove the CameraInput instance. ${err.message}`);
- return;
- }
- console.log('Callback invoked to indicate that the cameraInput instance is removed.');
-});
+try {
+ captureSession.addInput(cameraInput);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### removeInput
-removeInput\(cameraInput: CameraInput\): Promise
+removeInput(cameraInput: CameraInput): void
-Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses a promise to return the result.
+Removes a [CameraInput](#camerainput) instance from the session.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1328,23 +931,26 @@ Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**.
**Return value**
-| Type | Description |
-| -------------- | ------------------------- |
-| Promise\ | Promise used to return the result.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.removeInput(cameraInput).then(() => {
- console.log('Promise returned to indicate that the cameraInput instance is removed.');
-})
+try {
+ captureSession.removeInput(cameraInput);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### addOutput
-addOutput\(previewOutput: CameraOutput, callback: AsyncCallback\): void
+addOutput(previewOutput: CameraOutput): void
-Adds a [CameraOutput](#cameraoutput) instance to this **CaptureSession**. This API uses an asynchronous callback to return the result.
+Adds a [CameraOutput](#cameraoutput) instance to the session.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1353,53 +959,29 @@ Adds a [CameraOutput](#cameraoutput) instance to this **CaptureSession**. This A
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
-
-**Example**
-
-```js
-captureSession.addOutput(previewOutput, (err) => {
- if (err) {
- console.error(`Failed to add output. ${err.message}`);
- return;
- }
- console.log('Callback returned with output added.');
-})
-```
-
-### addOutput
-
-addOutput\(previewOutput: CameraOutput\): Promise
-
-Adds a [CameraOutput](#cameraoutput) instance to this **CaptureSession**. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------------- | ------------------------------- | ---- | ------------------------- |
-| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.|
**Return value**
-| Type | Description |
-| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.addOutput(previewOutput).then(() => {
- console.log('Promise returned with cameraOutput added.');
-})
+try {
+ captureSession.addOutput(previewOutput);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### removeOutput
-removeOutput\(previewOutput: CameraOutput, callback: AsyncCallback\): void
+removeOutput(previewOutput: CameraOutput): void
-Removes a [CameraOutput](#cameraoutput) instance from this **CaptureSession**. This API uses an asynchronous callback to return the result.
+Removes a [CameraOutput](#cameraoutput) instance from the session.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1408,48 +990,22 @@ Removes a [CameraOutput](#cameraoutput) instance from this **CaptureSession**. T
| Name | Type | Mandatory| Description |
| ------------- | ------------------------------- | ---- | ------------------------ |
| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.|
-| callback | AsyncCallback | Yes | Callback used to return the result. |
-
-**Example**
-
-```js
-captureSession.removeOutput(previewOutput, (err) => {
- if (err) {
- console.error(`Failed to remove the CameraOutput instance. ${err.message}`);
- return;
- }
- console.log('Callback invoked to indicate that the CameraOutput instance is removed.');
-});
-```
-
-### removeOutput
-
-removeOutput(previewOutput: CameraOutput): Promise
-
-Removes a [CameraOutput](#cameraoutput) instance from this **CaptureSession**. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------------- | ------------------------------- | ---- | ------------------------- |
-| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.|
-
**Return value**
-| Type | Description |
-| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
-
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.removeOutput(previewOutput).then(() => {
- console.log('Promise returned to indicate that the CameraOutput instance is removed.');
-})
+try {
+ captureSession.removeOutput(previewOutput);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### start
@@ -1464,14 +1020,14 @@ Starts this **CaptureSession**. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.start((err) => {
if (err) {
- console.error(`Failed to start the session ${err.message}`);
+ console.error(`Failed to start the session ${err.code}`);
return;
}
console.log('Callback invoked to indicate the session start success.');
@@ -1497,7 +1053,9 @@ Starts this **CaptureSession**. This API uses a promise to return the result.
```js
captureSession.start().then(() => {
console.log('Promise returned to indicate the session start success.');
-})
+}).catch((err) => {
+ console.error(`Failed to start the session ${err.code}`);
+});
```
### stop
@@ -1512,14 +1070,14 @@ Stops this **CaptureSession**. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.stop((err) => {
if (err) {
- console.error(`Failed to stop the session ${err.message}`);
+ console.error(`Failed to stop the session ${err.code}`);
return;
}
console.log('Callback invoked to indicate the session stop success.');
@@ -1538,14 +1096,16 @@ Stops this **CaptureSession**. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.stop().then(() => {
console.log('Promise returned to indicate the session stop success.');
-})
+}).catch((err) => {
+ console.error(`Failed to stop the session ${err.code}`);
+});
```
### release
@@ -1560,14 +1120,14 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.release((err) => {
if (err) {
- console.error(`Failed to release the CaptureSession instance ${err.message}`);
+ console.error(`Failed to release the CaptureSession instance ${err.code}`);
return;
}
console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.');
@@ -1586,69 +1146,48 @@ Releases this **CaptureSession**. This API uses a promise to return the result.
| Type | Description |
| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
captureSession.release().then(() => {
console.log('Promise returned to indicate that the CaptureSession instance is released successfully.');
-})
+}).catch((err) => {
+ console.error(`Failed to release the CaptureSession instance ${err.code}`);
+});
```
### hasFlash
-hasFlash(callback: AsyncCallback): void
+hasFlash(): boolean
Checks whether the device has flash. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Multimedia.Camera.Core
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------- | ---- | -------------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the flash support status. The value **true** means that the device has flash.|
-
-**Example**
-
-```js
-captureSession.hasFlash((err, status) => {
- if (err) {
- console.error(`Failed to check whether the device has flash light. ${err.message}`);
- return;
- }
- console.log(`Callback returned with flash light support status: ${status}`);
-})
-```
-
-### hasFlash
-
-hasFlash(): Promise
-
-Checks whether the device has flash. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
**Return value**
-| Type | Description |
-| ----------------- | ----------------------------------------------- |
-| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| boolean | Returns **true** if the device has flash; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.hasFlash().then((status) => {
- console.log(`Promise returned with the flash light support status: ${status}`);
-})
+try {
+ let status = captureSession.hasFlash();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### isFlashModeSupported
-isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void
+isFlashModeSupported(flashMode: FlashMode): boolean
-Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result.
+Checks whether a flash mode is supported.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1657,53 +1196,29 @@ Checks whether a specified flash mode is supported. This API uses an asynchronou
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | --------------------------------- |
| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. |
-| callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.|
-
-**Example**
-
-```js
-captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => {
- if (err) {
- console.error(`Failed to check whether the flash mode is supported. ${err.message}`);
- return;
- }
- console.log(`Callback returned with the flash mode support status: ${status}`);
-})
-```
-
-### isFlashModeSupported
-
-isFlashModeSupported(flashMode: FlashMode): Promise
-
-Checks whether a specified flash mode is supported. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| --------- | ----------------------- | ---- | ------------- |
-| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.|
**Return value**
-| Type | Description |
-| ----------------- | ---------------------------------------------------- |
-| Promise | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| boolean | Returns **true** if the flash mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => {
- console.log(`Promise returned with flash mode support status.${status}`);
-})
+try {
+ let status = captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setFlashMode
-setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void
+setFlashMode(flashMode: FlashMode): void
-Sets the flash mode. This API uses an asynchronous callback to return the result.
+Sets a flash mode for the device.
Before the setting, do the following checks:
@@ -1716,134 +1231,55 @@ Before the setting, do the following checks:
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | --------------------- |
-| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. |
+
+**Return value**
+
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => {
- if (err) {
- console.error(`Failed to set the flash mode ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of setFlashMode.');
-})
+try {
+ captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
-### setFlashMode
+### getFlashMode
-setFlashMode(flashMode: FlashMode): Promise
+getFlashMode(): FlashMode
-Sets a flash mode. This API uses a promise to return the result.
-
-Before the setting, do the following checks:
-
-1. Use **[hasFlash](#hasflash)** to check whether the device has flash.
-2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| --------- | ----------------------- | ---- | ------------- |
-| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.|
-
-**Return value**
-
-| Type | Description |
-| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
-
-**Example**
-
-```js
-captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => {
- console.log('Promise returned with the successful execution of setFlashMode.');
-})
-```
-
-### getFlashMode
-
-getFlashMode(callback: AsyncCallback): void
-
-Obtains the flash mode in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------- | ---- | --------------------------------- |
-| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.|
-
-**Example**
-
-```js
-captureSession.getFlashMode((err, flashMode) => {
- if (err) {
- console.error(`Failed to get the flash mode ${err.message}`);
- return;
- }
- console.log(`Callback returned with current flash mode: ${flashMode}`);
-})
-```
-
-### getFlashMode
-
-getFlashMode(): Promise
-
-Obtains the flash mode in use. This API uses a promise to return the result.
+Obtains the flash mode in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| --------------------------------- | --------------------------------- |
-| Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.|
-
-**Example**
-
-```js
-captureSession.getFlashMode().then((flashMode) => {
- console.log(`Promise returned with current flash mode : ${flashMode}`);
-})
-```
-
-### isExposureModeSupported
-
-isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void;
-
-Checks whether a specified exposure mode is supported. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | -------------------------------| ---- | ----------------------------- |
-| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. |
-| callback | AsyncCallback | Yes | Callback used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [FlashMode](#flashmode) | Flash mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => {
- if (err) {
- console.log(`Failed to check exposure mode supported ${err.message}`);
- return ;
- }
- console.log('Callback returned with the successful execution of isExposureModeSupported');
-})
+try {
+ let flashMode = captureSession.getFlashMode();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### isExposureModeSupported
-isExposureModeSupported(aeMode: ExposureMode): Promise
+isExposureModeSupported(aeMode: ExposureMode): boolean;
-Checks whether a specified exposure mode is supported. This API uses a promise to return the result.
+Checks whether an exposure mode is supported.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1855,71 +1291,51 @@ Checks whether a specified exposure mode is supported. This API uses a promise t
**Return value**
-| Name | Description |
-| ----------------- |--------------------------------- |
-| Promise | Promise used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.|
-
-**Example**
-
-```js
-captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => {
- console.log(`Promise returned with exposure mode supported : ${isSupported}`);
-})
-```
-
-### getExposureMode
-
-getExposureMode(callback: AsyncCallback): void
-
-Obtains the exposure mode in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------| ---- | ---------------------------------------- |
-| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| boolean | Returns **true** if the exposure mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getExposureMode((err, exposureMode) => {
- if (err) {
- console.log(`Failed to get the exposure mode ${err.message}`);
- return ;
- }
- console.log(`Callback returned with current exposure mode: ${exposureMode}`);
-})
+try {
+ let isSupported = captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getExposureMode
-getExposureMode(): Promise
+getExposureMode(): ExposureMode
-Obtains the exposure mode in use. This API uses a promise to return the result.
+Obtains the exposure mode in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Name | Description |
-| --------------------------------------- |------------------------------- |
-| Promise<[ExposureMode](#exposuremode)\> | Promise used to return the exposure mode.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [ExposureMode](#exposuremode) | Exposure mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getExposureMode().then((exposureMode) => {
- console.log(`Promise returned with current exposure mode : ${exposureMode}`);
-})
+try {
+ let exposureMode = captureSession.getExposureMode();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setExposureMode
-setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void
+setExposureMode(aeMode: ExposureMode): void
-Sets an exposure mode. This API uses an asynchronous callback to return the result.
+Sets an exposure mode for the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -1928,124 +1344,54 @@ Sets an exposure mode. This API uses an asynchronous callback to return the resu
| Name | Type | Mandatory| Description |
| -------- | -------------------------------| ---- | ----------------------- |
| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED,(err) => {
- if (err) {
- console.log(`Failed to set the exposure mode ${err.message}`);
- return ;
- }
- console.log('Callback returned with the successful execution of setExposureMode');
-})
-```
-
-### setExposureMode
-
-setExposureMode(aeMode: ExposureMode): Promise
-
-Sets an exposure mode. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Name | Description |
-| ----------------- |---------------------------- |
-| Promise | Promise used to return the result.|
-
-**Example**
-
-```js
-captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => {
- console.log('Promise returned with the successful execution of setExposureMode.');
-})
-```
-
-### getMeteringPoint
-
-getMeteringPoint(callback: AsyncCallback): void
-
-Obtains the center of the metering area. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------| ---- | ------------------------ |
-| callback | AsyncCallback<[Point](#point)\>| Yes | Callback used to return the center of the metering area.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getMeteringPoint((err, exposurePoint) => {
- if (err) {
- console.log(`Failed to get the current exposure point ${err.message}`);
- return ;
- }
- console.log(`Callback returned with current exposure point: ${exposurePoint}`);
-})
+try {
+ captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getMeteringPoint
-getMeteringPoint(): Promise
+getMeteringPoint(): Point
-Obtains the center of the metering area. This API uses a promise to return the result.
+Obtains the metering point of the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Name | Description |
-| ------------------------- |----------------------------- |
-| Promise<[Point](#point)\> | Promise used to return the center of the metering area.|
-
-**Example**
-
-```js
-captureSession.getMeteringPoint().then((exposurePoint) => {
- console.log(`Promise returned with current exposure point : ${exposurePoint}`);
-})
-```
-
-### setMeteringPoint
-
-setMeteringPoint(point: Point, callback: AsyncCallback): void
-
-Sets the center of the metering area. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------------- | -------------------------------| ---- | ------------------- |
-| exposurePoint | [Point](#point) | Yes | Exposure point. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [Point](#point) | Metering point obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-const Point1 = {x: 1, y: 1};
-
-captureSession.setMeteringPoint(Point1,(err) => {
- if (err) {
- console.log(`Failed to set the exposure point ${err.message}`);
- return ;
- }
- console.log('Callback returned with the successful execution of setMeteringPoint');
-})
+try {
+ let exposurePoint = captureSession.getMeteringPoint();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setMeteringPoint
-setMeteringPoint(point: Point): Promise
+setMeteringPoint(point: Point): void
-Sets the center of the metering area. This API uses a promise to return the result.
+Sets the metering point for the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -2057,73 +1403,52 @@ Sets the center of the metering area. This API uses a promise to return the resu
**Return value**
-| Name | Description |
-| ----------------- |------------------------ |
-| Promise | Promise used to return the center of the metering area.|
-
-**Example**
-
-```js
-const Point2 = {x: 2, y: 2};
-
-captureSession.setMeteringPoint(Point2).then(() => {
- console.log('Promise returned with the successful execution of setMeteringPoint');
-})
-```
-
-### getExposureBiasRange
-
-getExposureBiasRange(callback: AsyncCallback\>): void
-
-Obtains the exposure compensation values. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------------| ---- | ----------------------------- |
-| callback | AsyncCallback\> | Yes | Callback used to return the array of compensation values.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getExposureBiasRange((err, biasRangeArray) => {
- if (err) {
- console.log(`Failed to get the array of compenstation range ${err.message}`);
- return ;
- }
- console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray));
-})
+const exposurePoint = {x: 1, y: 1};
+try {
+ captureSession.setMeteringPoint(exposurePoint);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getExposureBiasRange
-getExposureBiasRange(): Promise\>
+getExposureBiasRange(): Array
-Obtains the exposure compensation values. This API uses a promise to return the result.
+Obtains the exposure compensation values of the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Name | Description |
-| ----------------- |-------------------------------------- |
-| Promise\> | Promise used to return the array of compensation values.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| Array | An array of compensation values. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getExposureBiasRange().then((biasRangeArray) => {
- console.log('Promise returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray));
-})
+try {
+ let biasRangeArray = captureSession.getExposureBiasRange();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setExposureBias
-setExposureBias(exposureBias: number, callback: AsyncCallback): void
+setExposureBias(exposureBias: number): void
-Sets an exposure compensation value. This API uses an asynchronous callback to return the result.
+Sets an exposure compensation value for the device.
Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values.
@@ -2133,106 +1458,50 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure
| Name | Type | Mandatory| Description |
| -------- | -------------------------------| ---- | ------------------- |
-| exposureBias | number | Yes | Compensation value. You can use **getExposureBiasRange** to obtain the supported values.|
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-let exposureBias = biasRangeArray[0];
-captureSession.setExposureBias(exposureBias,(err) => {
- if (err) {
- console.log(`Failed to set the exposure bias ${err.message}`);
- return ;
- }
- console.log('Callback returned with the successful execution of setExposureBias');
-})
-```
-
-### setExposureBias
-
-setExposureBias(exposureBias: number): Promise
-
-Sets an exposure compensation value. This API uses a promise to return the result.
-
-Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------------- | --------- | ---- | --------- |
-| exposureBias | number | Yes | Compensation value. You can use **getExposureBiasRange** to obtain the supported values. |
-
-**Return value**
-
-| Name | Description |
-| ----------------- |------------------------- |
-| Promise | Promise used to return the result.|
+| exposureBias | number | Yes | Exposure bias to set, which must be within the range obtained by running **getExposureBiasRange** interface. If the API call fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
let exposureBias = biasRangeArray[0];
-captureSession.setExposureBias(exposureBias).then(() => {
- console.log('Promise returned with the successful execution of setExposureBias.');
-})
-```
-
-### getExposureValue
-
-getExposureValue(callback: AsyncCallback): void
-
-Obtains the exposure value in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------| ---- | --------------------- |
-| callback | AsyncCallback | Yes | Callback used to the exposure value.|
-
-**Example**
-
-```js
-captureSession.getExposureValue((err, exposureValue) => {
- if (err) {
- console.log(`Failed to get the exposure value ${err.message}`);
- return ;
- }
- console.log(`Callback returned with the exposure value: ${exposureValue}`);
-})
+try {
+ captureSession.setExposureBias(exposureBias);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getExposureValue
-getExposureValue(): Promise
+getExposureValue(): number
-Obtains the exposure value in use. This API uses a promise to return the result.
+Obtains the exposure value in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Name | Description |
-| ----------------- |-------------------------- |
-| Promise | Promise used to the exposure value.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| number | Exposure value obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getExposureValue().then((exposureValue) => {
- console.log(`Promise returned with exposure value: ${exposureValude}`);
-})
+try {
+ let exposureValue = captureSession.getExposureValue();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### isFocusModeSupported
-isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void
+isFocusModeSupported(afMode: FocusMode): boolean
-Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result.
+Checks whether a focus mode is supported.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -2241,53 +1510,29 @@ Checks whether a specified focus mode is supported. This API uses an asynchronou
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------- |
| afMode | [FocusMode](#focusmode) | Yes | Focus mode. |
-| callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.|
-
-**Example**
-
-```js
-captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => {
- if (err) {
- console.error(`Failed to check whether the focus mode is supported. ${err.message}`);
- return;
- }
- console.log(`Callback returned with the focus mode support status: ${status}`);
-})
-```
-
-### isFocusModeSupported
-
-isFocusModeSupported(afMode: FocusMode): Promise
-
-Checks whether a specified focus mode is supported. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------ | ----------------------- | ---- | ------------- |
-| afMode | [FocusMode](#focusmode) | Yes | Focus mode.|
**Return value**
-| Type | Description |
-| ----------------- | --------------------------------------------------- |
-| Promise | Promise used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| boolean | Returns **true** if the focus mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => {
- console.log(`Promise returned with focus mode support status ${status}.`);
-})
+try {
+ let status = captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setFocusMode
-setFocusMode(afMode: FocusMode, callback: AsyncCallback): void
+setFocusMode(afMode: FocusMode): void
-Sets a focus mode. This API uses an asynchronous callback to return the result.
+Sets a focus mode for the device.
Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported.
@@ -2298,132 +1543,54 @@ Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to che
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------- |
| afMode | [FocusMode](#focusmode) | Yes | Focus mode. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => {
- if (err) {
- console.error(`Failed to set the focus mode ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of setFocusMode.');
-})
-```
-
-### setFocusMode
-
-setFocusMode(afMode: FocusMode): Promise
-
-Sets a focus mode. This API uses a promise to return the result.
-
-Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ------ | ----------------------- | ---- | ------------- |
-| afMode | [FocusMode](#focusmode) | Yes | Focus mode.|
**Return value**
-| Type | Description |
-| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
-
-**Example**
-
-```js
-captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => {
- console.log('Promise returned with the successful execution of setFocusMode.');
-})
-```
-
-### getFocusMode
-
-getFocusMode(callback: AsyncCallback): void
-
-Obtains the focus mode in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------- | ---- | ------------------------------- |
-| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getFocusMode((err, afMode) => {
- if (err) {
- console.error(`Failed to get the focus mode ${err.message}`);
- return;
- }
- console.log(`Callback returned with current focus mode: ${afMode}`);
-})
+try {
+ captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getFocusMode
-getFocusMode(): Promise
+getFocusMode(): FocusMode
-Obtains the focus mode in use. This API uses a promise to return the result.
+Obtains the focus mode in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ------------------- | -------------------------------- |
-| Promise | Promise used to return the focus mode.|
-
-**Example**
-
-```js
-captureSession.getFocusMode().then((afMode) => {
- console.log(`Promise returned with current focus mode : ${afMode}`);
-})
-```
-
-### setFocusPoint
-
-setFocusPoint(point: Point, callback: AsyncCallback): void
-
-Sets a focus point. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------- | ---- | ------------------- |
-| point | [Point](#point) | Yes | Focal point. |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [FocusMode](#focusmode) | Focus mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-const Point1 = {x: 1, y: 1};
-
-captureSession.setFocusPoint(Point1, (err) => {
- if (err) {
- console.error(`Failed to set the focus point ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of setFocusPoint.');
-})
+try {
+ let afMode = captureSession.getFocusMode();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setFocusPoint
-setFocusPoint(point: Point): Promise
+setFocusPoint(point: Point): void
-Sets a focal point. This API uses a promise to return the result.
+Sets a focal point for the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -2431,173 +1598,106 @@ Sets a focal point. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------- |
-| point | [Point](#point) | Yes | Focal point. |
+| Point1 | [Point](#point) | Yes | Focal point. |
**Return value**
-| Type | Description |
-| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
-
-**Example**
-
-```js
-const Point2 = {x: 2, y: 2};
-
-captureSession.setFocusPoint(Point2).then(() => {
- console.log('Promise returned with the successful execution of setFocusPoint.');
-})
-```
-
-### getFocusPoint
-
-getFocusPoint(callback: AsyncCallback): void
-
-Obtains the focal point. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------------- | ---- | ----------------------- |
-| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the focal point.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getFocusPoint((err, point) => {
- if (err) {
- console.error(`Failed to get the current focus point ${err.message}`);
- return;
- }
- console.log('Callback returned with the current focus point: ' + JSON.stringify(point));
-})
+const Point1 = {x: 1, y: 1};
+try {
+ captureSession.setFocusPoint(Point1);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getFocusPoint
-getFocusPoint(): Promise
+getFocusPoint(): Point
-Obtains the focal point. This API uses a promise to return the result.
+Obtains the focal point of the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| --------------- | --------------------------- |
-| Promise | Promise used to return the focal point.|
-
-**Example**
-
-```js
-captureSession.getFocusPoint().then((point) => {
- console.log('Promise returned with the current focus point: ' + JSON.stringify(point));
-})
-```
-
-### getFocalLength
-
-getFocalLength(callback: AsyncCallback): void
-
-Obtains the focal length. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------- | ---- | ----------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the focal length.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [Point](#point) | Focal point obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getFocalLength((err, focalLength) => {
- if (err) {
- console.error(`Failed to get the current focal length ${err.message}`);
- return;
- }
- console.log(`Callback returned with the current focal length: ${focalLength}`);
-})
+try {
+ let point = captureSession.getFocusPoint();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getFocalLength
-getFocalLength(): Promise
+getFocalLength(): number
-Obtains the focal length. This API uses a promise to return the result.
+Obtains the focal length of the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ---------------- | ----------------------- |
-| Promise | Promise used to return the focal length.|
-
-**Example**
-
-```js
-captureSession.getFocalLength().then((focalLength) => {
- console.log(`Promise returned with the current focal length: ${focalLength}`);
-})
-```
-
-### getZoomRatioRange
-
-getZoomRatioRange\(callback: AsyncCallback\>\): void
-
-Obtains the zoom ratio range. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------ | ---- | ------------------- |
-| callback | AsyncCallback\> | Yes | Callback used to return an array containing the minimum and maximum zoom ratios.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| number | Focal length obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getZoomRatioRange((err, zoomRatioRange) => {
- if (err) {
- console.error(`Failed to get the zoom ratio range. ${err.message}`);
- return;
- }
- console.log(`Callback returned with zoom ratio range: ${zoomRatioRange.length}`);
-})
+try {
+ let focalLength = captureSession.getFocalLength();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getZoomRatioRange
-getZoomRatioRange\(\): Promise\>
+getZoomRatioRange(): Array
-Obtains the zoom ratio range. This API uses a promise to return the result.
+Obtains the supported zoom ratio range.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ------------------------ | --------------------------- |
-| Promise\> | Promise used to return an array containing the minimum and maximum zoom ratios.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| Array | 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.|
**Example**
```js
-captureSession.getZoomRatioRange().then((zoomRatioRange) => {
- console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`);
-})
+try {
+ let zoomRatioRange = captureSession.getZoomRatioRange();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setZoomRatio
-setZoomRatio(zoomRatio: number, callback: AsyncCallback): void
+setZoomRatio(zoomRatio: number): void
-Sets a zoom ratio. This API uses an asynchronous callback to return the result.
+Sets a zoom ratio for the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -2606,227 +1706,111 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| --------- | -------------------- | ---- | ------------------- |
| zoomRatio | number | Yes | Zoom ratio. You can use **getZoomRatioRange** to obtain the supported values.|
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-let zoomRatio = zoomRatioRange[0];
-captureSession.setZoomRatio(zoomRatio, (err) => {
- if (err) {
- console.error(`Failed to set the zoom ratio value ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of setZoomRatio.');
-})
-```
-
-### setZoomRatio
-
-setZoomRatio(zoomRatio: number): Promise
-
-Sets a zoom ratio. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| --------- | ------ | ---- | --------- |
-| zoomRatio | number | Yes | Zoom ratio. You can use **getZoomRatioRange** to obtain the supported values.|
**Return value**
-| Type | Description |
-| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
let zoomRatio = zoomRatioRange[0];
-captureSession.setZoomRatio(zoomRatio).then(() => {
- console.log('Promise returned with the successful execution of setZoomRatio.');
-})
-```
-
-### getZoomRatio
-
-getZoomRatio(callback: AsyncCallback): void
-
-Obtains the zoom ratio in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-captureSession.getZoomRatio((err, zoomRatio) => {
- if (err) {
- console.error(`Failed to get the zoom ratio ${err.message}`);
- return;
- }
- console.log(`Callback returned with current zoom ratio: ${zoomRatio}`);
-})
+try {
+ captureSession.setZoomRatio(zoomRatio);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### getZoomRatio
-getZoomRatio(): Promise
+getZoomRatio(): number
-Obtains the zoom ratio in use. This API uses a promise to return the result.
+Obtains the zoom ratio in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
**Return value**
-| Type | Description |
-| ---------------- | ----------------------- |
-| Promise | Promise used to return the zoom ratio.|
-
-**Example**
-
-```js
-captureSession.getZoomRatio().then((zoomRatio) => {
- console.log(`Promise returned with current zoom ratio : ${zoomRatio}`);
-})
-```
-
-### isVideoStabilizationModeSupported
-
-isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void
-
-Checks whether the specified video stabilization mode is supported. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------- | ---- | ------------------------------ |
-| vsMode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. |
-| callback | AsyncCallback | Yes | Callback used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite. |
-
-**Example**
-
-```js
-captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => {
- if (err) {
- console.error(`Failed to check whether video stabilization mode supported. ${err.message}`);
- return;
- }
- console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported`);
-})
-```
-
-### isVideoStabilizationModeSupported
-
-isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): Promise
-
-Checks whether the specified video stabilization mode is supported. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| ----------------- | --------------------------------------------- |
-| Promise | Promise used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.|
-
-**Example**
-
-```js
-captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => {
- console.log(`Promise returned with video stabilization mode supported: ${isSupported}`);
-})
-```
-
-### getActiveVideoStabilizationMode
-
-getActiveVideoStabilizationMode(callback: AsyncCallback): void
-
-Obtains the video stabilization mode in use. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------- | ---- | ------------------------------ |
-| callback | AsyncCallback | Yes | Callback used to return the video stabilization mode. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| number | Zoom ratio obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getActiveVideoStabilizationMode((err, vsMode) => {
- if (err) {
- console.error(`Failed to get active video stabilization mode ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.');
-})
+try {
+ let zoomRatio = captureSession.getZoomRatio();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
-### getActiveVideoStabilizationMode
+### isVideoStabilizationModeSupported
-getActiveVideoStabilizationMode(): Promise
+isVideoStabilizationModeSupported(vsMode: VideoStabilizationMode): boolean
-Obtains the video stabilization mode in use. This API uses a promise to return the result.
+Checks whether the specified video stabilization mode is supported.
**System capability**: SystemCapability.Multimedia.Camera.Core
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------------------- | ---- | ------------------------------ |
+| vsMode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. |
+
**Return value**
-| Type | Description |
-| -------------------------------- | ------------------------------------------------- |
-| Promise | Promise used to return the video stabilization mode. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| boolean | Returns **true** if the video stabilization mode is supported; returns **false** otherwise. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.getActiveVideoStabilizationMode().then((vsMode) => {
- console.log(`Promise returned with the current video stabilization mode: ${vsMode}`);
-})
+try {
+ let isSupported = captureSession.isVideoStabilizationModeSupported(camera.VideoStabilizationMode.OFF);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
-### setVideoStabilizationMode
+### getActiveVideoStabilizationMode
-setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void
+getActiveVideoStabilizationMode(): VideoStabilizationMode
-Sets a video stabilization mode. This API uses an asynchronous callback to return the result.
+Obtains the video stabilization mode in use.
**System capability**: SystemCapability.Multimedia.Camera.Core
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------- | ---- | --------------------- |
-| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| VideoStabilizationMode | Video stabilization mode obtained. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => {
- if (err) {
- console.error(`Failed to set the video stabilization mode ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of setVideoStabilizationMode.');
-})
+try {
+ let vsMode = captureSession.getActiveVideoStabilizationMode();
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### setVideoStabilizationMode
-setVideoStabilizationMode(mode: VideoStabilizationMode): Promise
+setVideoStabilizationMode(mode: VideoStabilizationMode): void
-Sets a video stabilization mode. This API uses a promise to return the result.
+Sets a video stabilization mode for the device.
**System capability**: SystemCapability.Multimedia.Camera.Core
@@ -2838,16 +1822,19 @@ Sets a video stabilization mode. This API uses a promise to return the result.
**Return value**
-| Type | Description |
-| -------------- | ------------------------------------------------- |
-| Promise| Promise used to return the result. |
+| Type | Description |
+| ---------- | ----------------------------- |
+| [CameraErrorCode](#cameraerrorcode) | If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => {
- console.log('Promise returned with the successful execution of setVideoStabilizationMode.');
-})
+try {
+ captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF);
+} catch (error) {
+ // If the operation fails, error.code is returned and processed.
+ console.log(error.code);
+}
```
### on('focusStateChange')
@@ -2862,7 +1849,7 @@ Listens for focus state changes. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**, indicating the focus state change event.|
+| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**. The callback function returns the focus state change. The event can be listened for only when the session is created.|
| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. |
**Example**
@@ -2875,7 +1862,7 @@ captureSession.on('focusStateChange', (focusState) => {
### on('error')
-on(type: 'error', callback: ErrorCallback): void
+on(type: 'error', callback: ErrorCallback): void
Listens for **CaptureSession** errors. This API uses a callback to return the errors.
@@ -2885,39 +1872,17 @@ Listens for **CaptureSession** errors. This API uses a callback to return the er
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the capture session error event.|
-| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **CaptureSession** API, for example, **beginConfig()**, **commitConfig()**, or **addInput()**.|
+| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
```js
-captureSession.on('error', (captureSessionError) => {
- console.log(`Capture session error code: ${captureSessionError.code}`);
+captureSession.on('error', (error) => {
+ console.log(`Capture session error code: ${error.code}`);
})
```
-## CaptureSessionErrorCode
-
-Enumerates the error codes used in a **CaptureSession**.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| ----------------------------- | ---- | -------- |
-| ERROR_UNKNOWN | -1 | Unknown error.|
-| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.|
-| ERROR_TIMEOUT | 1 | Timeout.|
-
-## CaptureSessionError
-
-Defines a **CaptureSession** error.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory | Description |
-| ---- | ------------------------------------------- | -------------------------- |-------------------------- |
-| code | [CaptureSessionError](#capturesessionerror) | Yes |**CaptureSession** error code.|
-
## CameraOutput
Implements output information used in a **[CaptureSession](#capturesession)**. It is the base class of **output**.
@@ -2938,14 +1903,14 @@ Starts to output preview streams. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
previewOutput.start((err) => {
if (err) {
- console.error(`Failed to start the previewOutput. ${err.message}`);
+ console.error(`Failed to start the previewOutput. ${err.code}`);
return;
}
console.log('Callback returned with previewOutput started.');
@@ -2964,14 +1929,16 @@ Starts to output preview streams. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
previewOutput.start().then(() => {
console.log('Promise returned with previewOutput started.');
-})
+}).catch((err) => {
+ console.log('Failed to previewOutput start '+ err.code);
+});
```
### stop
@@ -2993,7 +1960,7 @@ Stops outputting preview streams. This API uses an asynchronous callback to retu
```js
previewOutput.stop((err) => {
if (err) {
- console.error(`Failed to stop the previewOutput. ${err.message}`);
+ console.error(`Failed to stop the previewOutput. ${err.code}`);
return;
}
console.log('Callback returned with previewOutput stopped.');
@@ -3019,7 +1986,9 @@ Stops outputting preview streams. This API uses a promise to return the result.
```js
previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stopped.');
-})
+}).catch((err) => {
+ console.log('Failed to previewOutput stop '+ err.code);
+});
```
### release
@@ -3034,14 +2003,14 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
previewOutput.release((err) => {
if (err) {
- console.error(`Failed to release the PreviewOutput instance ${err.message}`);
+ console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
@@ -3060,14 +2029,16 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
previewOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
-})
+}).catch((err) => {
+ console.log('Failed to previewOutput release '+ err.code);
+});
```
### on('frameStart')
@@ -3082,7 +2053,7 @@ Listens for preview frame start events. This API uses an asynchronous callback t
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | --------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'frameStart'**, indicating the preview frame start event.|
+| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the preview on the first frame starts. This event can be listened for only when a **previewOutput** instance is created.|
| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
@@ -3105,7 +2076,7 @@ Listens for preview frame end events. This API uses an asynchronous callback to
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the preview frame end event.|
+| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the preview on the last frame ends. This event can be listened for only when a **previewOutput** instance is created.|
| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
@@ -3118,7 +2089,7 @@ previewOutput.on('frameEnd', () => {
### on('error')
-on(type: 'error', callback: ErrorCallback): void
+on(type: 'error', callback: ErrorCallback): void
Listens for **PreviewOutput** errors. This API uses a callback to return the errors.
@@ -3128,8 +2099,8 @@ Listens for **PreviewOutput** errors. This API uses a callback to return the err
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------------- | ---- | ------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the preview output error event.|
-| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **PreviewOutput** API, for example, **start()** or **release()**.|
+| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -3139,26 +2110,6 @@ previewOutput.on('error', (previewOutputError) => {
})
```
-## PreviewOutputErrorCode
-
-Enumerates the error codes used for preview output.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| ------------- | ---- | -------- |
-| ERROR_UNKNOWN | -1 | Unknown error.|
-
-## PreviewOutputError
-
-Defines the preview output error.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory | Description |
-| ---- | ------------------------------------------------- | ---------------- |---------------------- |
-| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Yes |**PreviewOutput** error code.|
-
## ImageRotation
Enumerates the image rotation angles.
@@ -3226,14 +2177,14 @@ Captures a photo with the default shooting parameters. This API uses an asynchro
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
photoOutput.capture((err) => {
if (err) {
- console.error(`Failed to capture the photo ${err.message}`);
+ console.error(`Failed to capture the photo ${err.code}`);
return;
}
console.log('Callback invoked to indicate the photo capture request success.');
@@ -3242,6 +2193,30 @@ photoOutput.capture((err) => {
### capture
+capture(): Promise
+
+Captures a photo with the default shooting parameters. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Multimedia.Camera.Core
+
+**Return value**
+
+| Type | Description |
+| -------------- | ------------------------ |
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
+
+**Example**
+
+```js
+photoOutput.capture().then(() => {
+ console.log('Promise returned to indicate that photo capture request success.');
+}).catch((err) => {
+ console.log('Failed to photoOutput capture '+ err.code);
+});
+```
+
+### capture
+
capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void
Captures a photo with the specified shooting parameters. This API uses an asynchronous callback to return the result.
@@ -3253,7 +2228,7 @@ Captures a photo with the specified shooting parameters. This API uses an asynch
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------- | ---- | -------------------- |
| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. |
-| callback | AsyncCallback | Yes | Callback used to return the result. |
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned. |
**Example**
@@ -3271,7 +2246,7 @@ let settings = {
}
photoOutput.capture(settings, (err) => {
if (err) {
- console.error(`Failed to capture the photo ${err.message}`);
+ console.error(`Failed to capture the photo ${err.code}`);
return;
}
console.log('Callback invoked to indicate the photo capture request success.');
@@ -3296,41 +2271,37 @@ Captures a photo with the specified shooting parameters. This API uses a promise
| Type | Description |
| -------------- | ------------------------ |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
-photoOutput.capture().then(() => {
+photoOutput.capture(settings).then(() => {
console.log('Promise returned to indicate that photo capture request success.');
-})
+}).catch((err) => {
+ console.log('Failed to photoOutput capture '+ err.code);
+});
```
### isMirrorSupported
-isMirrorSupported(callback: AsyncCallback): void
+isMirrorSupported(): boolean
-Checks whether mirroring is supported. This API uses an asynchronous callback to return the result.
+Checks whether mirroring is supported.
**System capability**: SystemCapability.Multimedia.Camera.Core
-**Parameters**
+**Return value**
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------------------------------- | ---- | -------------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. |
+| Type | Description |
+| -------------- | ----------------------- |
+| boolean | Returns **true** if mirroring is supported; returns **false** otherwise.|
**Example**
```js
-photoOutput.isMirrorSupported((err, isSupported) => {
- if (err) {
- console.error(`Failed to check mirror is supported ${err.message}`);
- return;
- }
- console.log('Callback returned with the successful execution of isMirrorSupported.');
-})
+let isSupported = photoOutput.isMirrorSupported();
```
### release
@@ -3345,14 +2316,14 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
photoOutput.release((err) => {
if (err) {
- console.error(`Failed to release the PreviewOutput instance ${err.message}`);
+ console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
@@ -3371,36 +2342,16 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
photoOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
-})
-```
-
-### isMirrorSupported
-
-isMirrorSupported(): Promise
-
-Checks whether mirroring is supported. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| ----------------- | ------------------------------------------- |
-| Promise | Promise used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. |
-
-**Example**
-
-```js
-photoOutput.isMirrorSupported().then((isSupported) => {
- console.log(`Promise returned with mirror supported: ${isSupported}`);
-})
+}).catch((err) => {
+ console.log('Failed to photoOutput release '+ err.code);
+});
```
### on('captureStart')
@@ -3415,13 +2366,13 @@ Listens for shooting start events. This API uses an asynchronous callback to ret
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'captureStart'**, indicating the shooting start event.|
+| type | string | Yes | Event type. The value is fixed at **'captureStart'**. The callback function returns the shooting start event.|
| callback | AsyncCallback | Yes | Callback used to return the capture ID. |
**Example**
```js
-photoOutput.on('captureStart', (err, captureId) => {
+photoOutput.on('captureStart', (captureId) => {
console.log(`photo capture stated, captureId : ${captureId}`);
})
```
@@ -3438,13 +2389,13 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | --- | ------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'frameShutter'**, indicating the frame shutter event.|
+| type | string | Yes | Event type. The value is fixed at **'frameShutter'**. The callback function returns the captured frame information (captureId and time).|
| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. |
**Example**
```js
-photoOutput.on('frameShutter', (err, frameShutterInfo) => {
+photoOutput.on('frameShutter', (frameShutterInfo) => {
console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`);
console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`);
})
@@ -3462,13 +2413,13 @@ Listens for shooting end events. This API uses an asynchronous callback to retur
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------- | ---- | ---------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'captureEnd'**, indicating the shooting end event.|
+| type | string | Yes | Event type. The value is fixed at **'captureEnd'**. The callback function returns the shooting end event.|
| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. |
**Example**
```js
-photoOutput.on('captureEnd', (err, captureEndInfo) => {
+photoOutput.on('captureEnd', (captureEndInfo) => {
console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`);
console.log(`frameCount : ${captureEndInfo.frameCount}`);
})
@@ -3476,7 +2427,7 @@ photoOutput.on('captureEnd', (err, captureEndInfo) => {
### on('error')
-on(type: 'error', callback: ErrorCallback): void
+on(type: 'error', callback: ErrorCallback): void
Listens for **PhotoOutput** errors. This API uses a callback to return the errors.
@@ -3486,14 +2437,14 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | ----------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the photo output error event.|
-| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns an error code when an API call fails.|
+| callback | ErrorCallback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
```js
-photoOutput.on('error', (err, photoOutputError) => {
- console.log(`Photo output error code: ${photoOutputError.code}`);
+photoOutput.on('error', (error) => {
+ console.log(`Photo output error code: ${error.code}`);
})
```
@@ -3519,29 +2470,6 @@ Defines the capture end information.
| captureId | number | Yes | ID of this capture action.|
| frameCount | number | Yes | Number of frames captured. |
-## PhotoOutputErrorCode
-
-Enumerates the error codes used for photo output.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| ----------------------------- | ---- | --------------- |
-| ERROR_UNKNOWN | -1 | Unknown error. |
-| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.|
-| ERROR_INSUFFICIENT_RESOURCES | 1 | Insufficient resources. |
-| ERROR_TIMEOUT | 2 | Timeout. |
-
-## PhotoOutputError
-
-Defines a photo output error.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory |Description |
-| ---- | ------------------------------------- | --------- | ----------------------- |
-| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Yes | **PhotoOutput** error code.|
-
## VideoOutput
Implements output information used in a video recording session. This class inherits from [CameraOutput](#cameraoutput).
@@ -3558,14 +2486,14 @@ Starts video recording. This API uses an asynchronous callback to return the res
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | -------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
videoOutput.start((err) => {
if (err) {
- console.error(`Failed to start the video output ${err.message}`);
+ console.error(`Failed to start the video output ${err.code}`);
return;
}
console.log('Callback invoked to indicate the video output start success.');
@@ -3584,7 +2512,7 @@ Starts video recording. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
@@ -3592,7 +2520,9 @@ Starts video recording. This API uses a promise to return the result.
```js
videoOutput.start().then(() => {
console.log('Promise returned to indicate that start method execution success.');
-})
+}).catch((err) => {
+ console.log('Failed to videoOutput start '+ err.code);
+});
```
### stop
@@ -3614,7 +2544,7 @@ Stops video recording. This API uses an asynchronous callback to return the resu
```js
videoOutput.stop((err) => {
if (err) {
- console.error(`Failed to stop the video output ${err.message}`);
+ console.error(`Failed to stop the video output ${err.code}`);
return;
}
console.log('Callback invoked to indicate the video output stop success.');
@@ -3640,8 +2570,10 @@ Stops video recording. This API uses a promise to return the result.
```js
videoOutput.stop().then(() => {
console.log('Promise returned to indicate that stop method execution success.');
-})
-```
+}).catch((err) => {
+ console.log('Failed to videoOutput stop '+ err.code);
+});
+```
### release
@@ -3655,14 +2587,14 @@ Releases output resources. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
videoOutput.release((err) => {
if (err) {
- console.error(`Failed to release the PreviewOutput instance ${err.message}`);
+ console.error(`Failed to release the PreviewOutput instance ${err.code}`);
return;
}
console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.');
@@ -3681,14 +2613,16 @@ Releases output resources. This API uses a promise to return the result.
| Type | Description |
| -------------- | ----------------------- |
-| Promise| Promise used to return the result.|
+| Promise| Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
videoOutput.release().then(() => {
console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.');
-})
+}).catch((err) => {
+ console.log('Failed to videoOutput release '+ err.code);
+});
```
### on('frameStart')
@@ -3703,7 +2637,7 @@ Listens for video recording start events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ----------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **`frameStart`**, indicating the video recording start event.|
+| type | string | Yes | Event type. The value is fixed at **'frameStart'**. The callback is invoked when the recording on the first frame of an image starts.|
| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
@@ -3726,7 +2660,7 @@ Listens for video recording stop events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the video recording stop event.|
+| type | string | Yes | Event type. The value is fixed at **'frameEnd'**. The callback is invoked when the recording on the last frame of an image stops.|
| callback | AsyncCallback | Yes | Callback used to return the result. |
**Example**
@@ -3739,7 +2673,7 @@ videoOutput.on('frameEnd', () => {
### on('error')
-on(type: 'error', callback: ErrorCallback): void
+on(type: 'error', callback: ErrorCallback): void
Listens for errors that occur during video recording. This API uses a callback to return the result.
@@ -3749,38 +2683,17 @@ Listens for errors that occur during video recording. This API uses a callback t
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | -------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the video output error event.|
-| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **VideoOutput** API, for example, **start()** or **release()**.|
+| callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
```js
-videoOutput.on('error', (VideoOutputError) => {
- console.log(`Video output error code: ${VideoOutputError.code}`);
+videoOutput.on('error', (error) => {
+ console.log(`Video output error code: ${error.code}`);
})
```
-## VideoOutputErrorCode
-
-Enumerates the error codes used for video recording.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| --------------------- | ---- | ------------ |
-| ERROR_UNKNOWN | -1 | Unknown error. |
-| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.|
-
-## VideoOutputError
-
-Defines a video output error.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory | Description |
-| ---- | ------------------------------------- | ----------------- | ----------------------- |
-| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Yes | **VideoOutput** error code.|
-
## MetadataOutput
Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**.
@@ -3796,15 +2709,15 @@ Starts to output metadata. This API uses an asynchronous callback to return the
**Parameters**
| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------------- | ---- | ------------------- |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
+| -------- | -------------------------- | ---- | ------------------- |
+| callback | AsyncCallback | Yes | Callback used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
metadataOutput.start((err) => {
if (err) {
- console.error(`Failed to start metadataOutput. ${err.message}`);
+ console.error(`Failed to start metadataOutput. ${err.code}`);
return;
}
console.log('Callback returned with metadataOutput started.');
@@ -3823,14 +2736,16 @@ Starts to output metadata. This API uses a promise to return the result.
| Type | Description |
| ---------------------- | ------------------------ |
-| Promise | Promise used to return the result.|
+| Promise | Promise used to return the result. If the operation fails, an error code defined in [CameraErrorCode](#cameraerrorcode) is returned.|
**Example**
```js
metadataOutput.start().then(() => {
console.log('Callback returned with metadataOutput started.');
-})
+}).catch((err) => {
+ console.log('Failed to metadataOutput start '+ err.code);
+});
```
### stop
@@ -3852,7 +2767,7 @@ Stops outputting metadata. This API uses an asynchronous callback to return the
```js
metadataOutput.stop((err) => {
if (err) {
- console.error(`Failed to stop the metadataOutput. ${err.message}`);
+ console.error(`Failed to stop the metadataOutput. ${err.code}`);
return;
}
console.log('Callback returned with metadataOutput stopped.');
@@ -3878,7 +2793,9 @@ Stops outputting metadata. This API uses a promise to return the result.
```js
metadataOutput.stop().then(() => {
console.log('Callback returned with metadataOutput stopped.');
-})
+}).catch((err) => {
+ console.log('Failed to metadataOutput stop '+ err.code);
+});
```
### on('metadataObjectsAvailable')
@@ -3893,8 +2810,8 @@ Listens for metadata objects. This API uses an asynchronous callback to return t
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------ |
-| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.|
-| callback | Callback\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**. The callback function returns the valid metadata. This event can be listened for only when a **MetadataOutput** instance is created.|
+| callback | Callback\> | Yes | Callback used to return the metadata.|
**Example**
@@ -3906,7 +2823,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => {
### on('error')
-on(type: 'error', callback: ErrorCallback): void
+on(type: 'error', callback: ErrorCallback): void
Listens for metadata errors. This API uses an asynchronous callback to return the result.
@@ -3916,8 +2833,8 @@ Listens for metadata errors. This API uses an asynchronous callback to return th
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | --------------------------------------- |
-| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.|
-| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. |
+| type | string | Yes | Event type. The value is fixed at **'error'**. The callback function returns the error code corresponding to an error that occurs during the call of a **MetadataOutput** instance API, for example, **start()** or **release()**.|
+| callback | Callback | Yes | Callback used to return an error code defined in [CameraErrorCode](#cameraerrorcode). |
**Example**
@@ -3927,36 +2844,15 @@ metadataOutput.on('error', (metadataOutputError) => {
})
```
-## MetadataOutputErrorCode
-
-Enumerates the codes used for metadata output errors.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name | Value | Description |
-| ------------------------------- | ---- | -------- |
-| ERROR_UNKNOWN | -1 | Unknown error.|
-| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.|
-
-## MetadataOutputError
-
-Defines a metadata output error.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-| Name| Type | Mandatory | Description |
-| ---- | ------------------------------------- | ----------------- | ----------------------- |
-| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | Yes | **MetadataOutput** error code.|
-
## MetadataObjectType
-Enumerates metadata streams.
+Enumerates the metadata object types.
**System capability**: SystemCapability.Multimedia.Camera.Core
| Name | Value | Description |
| ------------------------- | ---- | ----------------- |
-| FACE_DETECTION | 0 | Metadata object type.|
+| FACE_DETECTION | 0 | Face detection.|
## Rect
@@ -3975,156 +2871,8 @@ Defines a rectangle.
Implements camera metadata, which is the data source of [CameraInput](#camerainput). The metadata is obtained through metadataOutput.on('metadataObjectsAvailable').
-### getType
-
-getType(callback: AsyncCallback): void
-
-Obtains the metadata object type. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------------------------------------- | --- | -------------------- |
-| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getType((err, metadataObjectType) => {
- if (err) {
- console.error(`Failed to get type. ${err.message}`);
- return;
- }
- console.log('Callback returned with an array of metadataObjectType.');
-})
-```
-
-### getType
-
-getType(): Promise
-
-Obtains the metadata object type. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| --------------------------------------------------- | --------------------------- |
-| Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getType().then((metadataObjectType) => {
- console.log('Callback returned with an array of metadataObjectType.');
-})
-```
-
-### getTimestamp
-
-getTimestamp(callback: AsyncCallback): void
-
-Obtains the metadata timestamp. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------------- | ---- | ------------------------ |
-| callback | AsyncCallback | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getTimestamp((err,timestamp) => {
- if (err) {
- console.error(`Failed to get timestamp. ${err.message}`);
- return;
- }
- console.log('Callback returned with timestamp getted timestamp : ${timestamp}');
-})
-```
-
-### getTimestamp
-
-getTimestamp(): Promise
-
-Obtains the metadata timestamp. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| ---------------- | --------------------------- |
-| Promise | Promise used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getTimestamp().then((timestamp) => {
- console.log('Callback returned with timestamp getted timestamp : ${timestamp}');
-})
-```
-
-### getBoundingBox
-
-getBoundingBox(callback: AsyncCallback): void
-
-Obtains the bounding box of metadata. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ----------------------------------------------------------- | ---- | ------------------------ |
-| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getBoundingBox((err, rect) => {
- if (err) {
- console.error(`Failed to get boundingBox. ${err.message}`);
- return;
- }
- console.log('Callback returned with boundingBox getted.');
-})
-```
-
-### getBoundingBox
-
-getBoundingBox(): Promise
-
-Obtains the bounding box of metadata. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Multimedia.Camera.Core
-
-**Return value**
-
-| Type | Description |
-| ---------------------- | --------------------------- |
-| Promise<[Rect](#rect)\> | Promise used to return the result.|
-
-**Example**
-
-```js
-let metadataObject = metadataObjectArr[0];
-metadataObject.getBoundingBox().then((rect) => {
- console.log('Callback returned with boundingBox getted.');
-})
-```
-
-## MetadataFaceObject
-
-Implements the face object of metadata. It inherits [MetadataObject](#metadataobject).
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | -----------------|
+| type | [MetadataObjectType](#metadataobjecttype) | No | Metadata data type. Only face recognition is supported.|
+| timestamp | number | No | Current timestamp, in milliseconds.|
+| boundingBox | [Rect](#rect) | No | Metadata rectangle.|
diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md
index 08df60a00e536dbc715b2017f8301203cbbf9ffc..cf334f6fd36fd654c2c9558865b0c9f06b68d9ef 100644
--- a/en/application-dev/reference/apis/js-apis-cert.md
+++ b/en/application-dev/reference/apis/js-apis-cert.md
@@ -102,7 +102,7 @@ Creates an **X509Cert** instance. This API uses an asynchronous callback to retu
| Name | Type | Mandatory| Description |
| -------- | ----------------------------- | ---- | -------------------------- |
| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cert** instance created.|
**Example**
@@ -115,7 +115,7 @@ let encodingData = null;
let encodingBlob = {
data: encodingData,
// Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
- encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
};
cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
if (error != null) {
@@ -144,7 +144,7 @@ Creates an **X509Cert** instance. This API uses a promise to return the result.
| Type | Description |
| ------- | ---------------- |
-| Promise\ | **X509Cer** instance created.|
+| Promise\ | **X509Cert** instance created.|
**Example**
@@ -189,7 +189,6 @@ Verifies the certificate signature. This API uses an asynchronous callback to re
```js
import cryptoCert from '@ohos.security.cert';
-import cryptoFramework from "@ohos.security.cryptoFramework"
// Certificate binary data, which must be set based on the service.
let encodingData = null;
@@ -250,7 +249,7 @@ let encodingBlob = {
};
cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
console.log("createX509Cert success");
- // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance.
+ // The service can call getPublicKey() of the upper-level X509Cert object to obtain the public key.
let pubKey = null;
x509Cert.verify(pubKey).then(result => {
console.log("verify success");
@@ -1217,7 +1216,7 @@ cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void
-Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result.
+Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result. The RSA algorithm is supported.
**System capability**: SystemCapability.Security.Cert
@@ -1225,7 +1224,7 @@ Verifies the signature of the X.509 CRL. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------------------------------------------ |
-| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. |
+| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.|
@@ -1264,7 +1263,7 @@ cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
verify(key : cryptoFramework.PubKey) : Promise\
-Verifies the signature of the X.509 CRL. This API uses a promise to return the result.
+Verifies the signature of the X.509 CRL. This API uses a promise to return the result. The RSA algorithm is supported.
**System capability**: SystemCapability.Security.Cert
@@ -2061,7 +2060,7 @@ Obtains the issuer of this revoked certificate. This API uses an asynchronous ca
**Return value**
| Type | Description |
-| --------------------- | ---------------------- - |
+| --------------------- | ----------------------- |
| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md
index 05f490c454f7e7133bfc5977d1bdc2d180462a7c..5ffc47acf97498d254f58b5b4ea8d540631083d2 100644
--- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md
+++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md
@@ -155,8 +155,6 @@ registerContinuation(callback: AsyncCallback\): void;
Registers the continuation management service and obtains a token. This API does not involve any filter parameters and uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
-
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
@@ -198,8 +196,6 @@ registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\<
Registers the continuation management service and obtains a token. This API uses an asynchronous callback to return the result.
-**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
-
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
@@ -245,8 +241,6 @@ registerContinuation(options?: ContinuationExtraParams): Promise\;
Registers the continuation management service and obtains a token. This API uses a promise to return the result.
-**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
-
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
@@ -298,7 +292,7 @@ on(type: "deviceConnect", callback: Callback\): void;
Subscribes to device connection events. This API uses an asynchronous callback to return the result.
-> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceselected9) instead.
+> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
@@ -337,7 +331,7 @@ on(type: "deviceDisconnect", callback: Callback\): void;
Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
-> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceunselected9) instead.
+> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
@@ -374,7 +368,7 @@ off(type: "deviceConnect", callback?: Callback\): void;
Unsubscribes from device connection events. This API uses an asynchronous callback to return the result.
-> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceselected9) instead.
+> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
@@ -413,7 +407,7 @@ off(type: "deviceDisconnect", callback?: Callback\): void;
Unsubscribes from device disconnection events. This API uses an asynchronous callback to return the result.
-> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceunselected9) instead.
+> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
@@ -444,21 +438,19 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
});
```
-## continuationManager.on("deviceSelected")