提交 4514d3eb 编写于 作者: L longwei 提交者: Gitee

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

Signed-off-by: Nlongwei <longwei27@huawei.com>
......@@ -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
......
......@@ -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)了解版本详情。
......
......@@ -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.
<img src="figures/stage-want1.png" alt="stage-want1" style="zoom:80%;" />
![stage-want1](figures/stage-want1.png)
......@@ -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.
<img src="figures/context-inheritance.png" alt="context-inheritance" style="zoom: 50%;" />
![context-inheritance](figures/context-inheritance.png)
- The figure below illustrates the holding relationship of contexts.
<img src="figures/context-holding.png" alt="context-holding" style="zoom:50%;" />
![context-holding](figures/context-holding.png)
- 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
<img src="figures/context-dir.png" alt="context-dir" style="zoom: 50%;" />
![context-dir](figures/context-dir.png)
- 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';
......
......@@ -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:
<img src="figures/stage-want2.png" alt="stage-want2" style="zoom:50%;" />
![stage-want2](figures/stage-want2.png)
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.
......
......@@ -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
<img src="figures/want-action.png" alt="want-action" style="zoom:80%;" />
![want-action](figures/want-action.png)
### 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
<img src="figures/want-entities.png" alt="want-entities" style="zoom:80%;" />
Figure 2 Matching rule of entities in the want parameter
![want-entities](figures/want-entities.png)
### 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
<img src="figures/want-uri-type1.png" alt="want-uri-type1" style="zoom: 80%;" />
![want-uri-type1](figures/want-uri-type1.png)
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
<img src="figures/want-uri-type2.png" alt="want-uri-type2" style="zoom:80%;" />
![want-uri-type2](figures/want-uri-type2.png)
### Matching Rules of uri
......
......@@ -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
<img src="figures/hop-structure.png" alt="hop-structure" style="zoom:80%;" />
**Figure 1** Continuation architecture
![hop-structure](figures/hop-structure.png)
- 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.)
......
......@@ -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
<img src="figures/globalThis1.png" alt="globalThis1" style="zoom:67%;" />
![globalThis1](figures/globalThis1.png)
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
![globalThis2](figures/globalThis2.png)
- 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.
......
......@@ -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.
<img src="figures/uiability-intra-device-interaction.png" alt="uiability-intra-device-interaction" style="zoom:50%;" />
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
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
<img src="figures/call.png" alt="call" style="zoom:67%;" />
![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
......
......@@ -19,7 +19,7 @@ Each time [startAbility()](../reference/apis/js-apis-inner-application-uiAbility
**Figure 1** Demonstration effect in singleton mode
<img src="figures/uiability-launch-type1.png" alt="uiability-launch-type1" width="40%;" />
![uiability-launch-type1](figures/uiability-launch-type1.png)
> **NOTE**
>
......@@ -49,7 +49,7 @@ In standard mode, each time [startAbility()](../reference/apis/js-apis-inner-app
**Figure 2** Demonstration effect in standard mode
<img src="figures/standard-mode.png" alt="standard-mode" width="40%;" />
![standard-mode](figures/standard-mode.png)
To use the standard mode, set **launchType** in the [module.json5 configuration file](../quick-start/module-configuration-file.md) to **standard**.
......@@ -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
<img src="figures/uiability-launch-type2.png" alt="uiability-launch-type2" style="zoom:50%;" />
![uiability-launch-type2](figures/uiability-launch-type2.png)
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.
......
......@@ -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
<img src="figures/Ability-Life-Cycle.png" alt="Ability-Life-Cycle" style="zoom:50%;" />
**Figure 1** UIAbility lifecycle states
![Ability-Life-Cycle](figures/Ability-Life-Cycle.png)
## 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
<img src="figures/Ability-Life-Cycle-WindowStage.png" alt="Ability-Life-Cycle-WindowStage" style="zoom:50%;" />
**Figure 2** WindowStageCreate and WindowStageDestory
![Ability-Life-Cycle-WindowStage](figures/Ability-Life-Cycle-WindowStage.png)
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.
......
......@@ -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
<img src="figures/usage-of-want.png" alt="usage-of-want" style="zoom:80%;" />
**Figure 1** Want usage
![usage-of-want](figures/usage-of-want.png)
## Types of Want
......
......@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): 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);
});
......
......@@ -14,12 +14,12 @@ For details about the APIs, see [Distributed KV Store](../reference/apis/js-apis
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KvManager** object for database management. |
| getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Creates and obtains a KV store.|
| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array\|string\|number\|boolean): Promise&lt;void> | Inserts and updates data. |
| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. |
| get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Obtains data. |
| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string,number]&gt;&gt;): 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');
......
......@@ -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
```
此差异已折叠。
此差异已折叠。
......@@ -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.
![camera_framework process](figures/camera_framework_process.jpg)
![camera_framework process](figures/camera_framework_process.png)
......@@ -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.
......
......@@ -263,11 +263,11 @@ struct MyComponent {
>
> - **LazyForEach** must be used in the container component. Currently, only the **\<List>**, **\<Grid>**, and **\<Swiper>** 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**.
>
......
......@@ -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%')
}
}
```
```
![datePicker](../../application-dev/reference/arkui-ts/figures/datePicker.gif)
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%')
}
}
```
![hello](figures/hello.PNG)
![hello](figures/hello.PNG)
## 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%')
}
}
```
......@@ -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).
......@@ -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)
......
# @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);
```
# @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;
......
......@@ -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) {
......
......@@ -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);
}
```
......
......@@ -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\<X509Cert> | Yes | Callback invoked to return the result. **X509Cer** instance created.|
| callback | AsyncCallback\<X509Cert> | 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\<X509Cert> | **X509Cer** instance created.|
| Promise\<X509Cert> | **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>) : 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\<void> | 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\<void>
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**
......
......@@ -155,8 +155,6 @@ registerContinuation(callback: AsyncCallback\<number>): 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\<number>;
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\<ContinuationResult>): 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\<string>): 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\<ContinuationResult>): 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\<string>): 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")<sup>9+</sup>
## continuationManager.on("deviceConnect")<sup>9+</sup>
on(type: "deviceSelected", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
Subscribes to device connection events. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceSelected**.|
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | Callback\<Array\<[ContinuationResult](js-apis-continuation-continuationResult.md)>> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
......@@ -477,12 +469,12 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
```ts
let token = 1;
try {
continuationManager.on("deviceSelected", token, (data) => {
console.info('onDeviceSelected len: ' + data.length);
continuationManager.on("deviceConnect", token, (data) => {
console.info('onDeviceConnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceSelected deviceId: ' + JSON.stringify(data[i].id));
console.info('onDeviceSelected deviceType: ' + JSON.stringify(data[i].type));
console.info('onDeviceSelected deviceName: ' + JSON.stringify(data[i].name));
console.info('onDeviceConnect deviceId: ' + JSON.stringify(data[i].id));
console.info('onDeviceConnect deviceType: ' + JSON.stringify(data[i].type));
console.info('onDeviceConnect deviceName: ' + JSON.stringify(data[i].name));
}
});
} catch (err) {
......@@ -490,23 +482,21 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
}
```
## continuationManager.on("deviceUnselected")<sup>9+</sup>
## continuationManager.on("deviceDisconnect")<sup>9+</sup>
on(type: "deviceUnselected", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
on(type: "deviceDisconnect", token: number, callback: Callback\<Array\<string>>): void;
Subscribes to device disconnection events. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceUnselected**.|
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
| callback | Callback\<Array\<[ContinuationResult](js-apis-continuation-continuationResult.md)>> | Yes| Callback invoked when a device is unselected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
| callback | Callback\<Array\<string>> | Yes| Callback invoked when a device is unselected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
**Error codes**
......@@ -523,35 +513,31 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
```ts
let token = 1;
try {
continuationManager.on("deviceUnselected", token, (data) => {
console.info('onDeviceUnselected len: ' + data.length);
continuationManager.on("deviceDisconnect", token, (data) => {
console.info('onDeviceDisconnect len: ' + data.length);
for (let i = 0; i < data.length; i++) {
console.info('onDeviceUnselected deviceId: ' + JSON.stringify(data[i].id));
console.info('onDeviceUnselected deviceType: ' + JSON.stringify(data[i].type));
console.info('onDeviceUnselected deviceName: ' + JSON.stringify(data[i].name));
console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data[i]));
}
console.info('onDeviceUnselected finished.');
console.info('onDeviceDisconnect finished.');
});
} catch (err) {
console.error('on failed, cause: ' + JSON.stringify(err));
}
```
## continuationManager.off("deviceSelected")<sup>9+</sup>
## continuationManager.off("deviceConnect")<sup>9+</sup>
off(type: "deviceSelected", token: number): void;
off(type: "deviceConnect", token: number): void;
Unsubscribes from device connection events.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceSelected**.|
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
**Error codes**
......@@ -569,27 +555,25 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
```ts
let token = 1;
try {
continuationManager.off("deviceSelected", token);
continuationManager.off("deviceConnect", token);
} catch (err) {
console.error('off failed, cause: ' + JSON.stringify(err));
}
```
## continuationManager.off("deviceUnselected")<sup>9+</sup>
## continuationManager.off("deviceDisconnect")<sup>9+</sup>
off(type: "deviceUnselected", token: number): void;
off(type: "deviceDisconnect", token: number): void;
Unsubscribes from device disconnection events.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceUnselected**.|
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| token | number | Yes| Token obtained after the registration of the continuation management service.|
**Error codes**
......@@ -607,7 +591,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
```ts
let token = 1;
try {
continuationManager.off("deviceUnselected", token);
continuationManager.off("deviceDisconnect", token);
} catch (err) {
console.error('off failed, cause: ' + JSON.stringify(err));
}
......@@ -761,8 +745,6 @@ startContinuationDeviceManager(token: number, callback: AsyncCallback\<void>): v
Starts the device selection module to show the list of available devices on the network. 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**
......@@ -804,8 +786,6 @@ startContinuationDeviceManager(token: number, options: ContinuationExtraParams,
Starts the device selection module to show the list of available devices on the network. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......@@ -851,8 +831,6 @@ startContinuationDeviceManager(token: number, options?: ContinuationExtraParams)
Starts the device selection module to show the list of available devices on the network. This API uses a promise to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......@@ -1000,8 +978,6 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt
Instructs the device selection module to update the device connection state. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......@@ -1046,8 +1022,6 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt
Instructs the device selection module to update the device connection state. This API uses a promise to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......@@ -1183,8 +1157,6 @@ unregisterContinuation(token: number, callback: AsyncCallback\<void>): void;
Deregisters the continuation management service. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......@@ -1226,8 +1198,6 @@ unregisterContinuation(token: number): Promise\<void>;
Deregisters the continuation management service. This API uses a promise to return the result.
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
......
# @ohos.curves
# @ohos.curves (Interpolation Calculation)
The **Curves** module provides APIs for interpolation calculation to create step, cubic Bezier, and spring curves.
......@@ -309,7 +309,6 @@ Creates a spring curve. This API is deprecated since API version 9. You are advi
```ts
// xxx.ets
import Curves from '@ohos.curves'
@Entry
@Component
struct ImageComponent {
......@@ -319,16 +318,16 @@ struct ImageComponent {
build() {
Column() {
Text()
.margin({ top: 100 })
.margin({top:100})
.width(this.widthSize)
.height(this.heightSize)
.backgroundColor(Color.Red)
.onClick(() => {
.onClick(()=> {
let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0);
this.widthSize = curve.interpolate(0.5) * this.widthSize;
this.heightSize = curve.interpolate(0.5) * this.heightSize;
})
.animation({ duration: 2000, curve: Curves.stepsCurve(9, true) })
.animation({ duration: 2000 , curve: Curves.stepsCurve(9, true) })
}.width("100%").height("100%")
}
}
......
# @ohos.data.dataShare (DataShare)
# @ohos.data.dataShare (Data Sharing)
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
......@@ -37,18 +37,12 @@ Example:
**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path.
## dataShare.createDataShareHelper
createDataShareHelper(context: Context, uri: string, callback: AsyncCallback&lt;DataShareHelper&gt;): void
Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
......@@ -70,7 +64,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let dataShareHelper;
......@@ -94,11 +88,6 @@ createDataShareHelper(context: Context, uri: string): Promise&lt;DataShareHelper
Creates a **DataShareHelper** instance. This API uses a promise to return the result.
Observe the following when using this API:
- If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
- If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md).
**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer
**Parameters**
......@@ -125,7 +114,7 @@ For details about the error codes, see [DataShare Error Codes](../errorcodes/err
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let dataShareHelper;
......@@ -164,8 +153,7 @@ Subscribes to changes of the specified data. After an observer is registered, th
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
function onCallback() {
console.info("**** Observer on callback ****");
}
......@@ -192,8 +180,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
function offCallback() {
console.info("**** Observer off callback ****");
}
......@@ -220,8 +207,7 @@ Inserts a single data record into the database. This API uses an asynchronous ca
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
const valueBucket = {
"name": "rose",
......@@ -265,8 +251,7 @@ Inserts a single data record into the database. This API uses a promise to retur
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
const valueBucket = {
"name": "rose1",
......@@ -303,8 +288,8 @@ Deletes one or more data records from the database. This API uses an asynchronou
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
......@@ -346,8 +331,8 @@ Deletes one or more data records from the database. This API uses a promise to r
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
......@@ -383,8 +368,8 @@ Queries data in the database. This API uses an asynchronous callback to return t
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"];
......@@ -428,8 +413,8 @@ Queries data in the database. This API uses a promise to return the result.
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let columns = ["*"];
......@@ -466,8 +451,8 @@ Updates data in the database. This API uses an asynchronous callback to return t
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
......@@ -516,8 +501,8 @@ Updates data in the database. This API uses a promise to return the result.
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
import UIAbility from '@ohos.app.ability.UIAbility'
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let da = new dataSharePredicates.DataSharePredicates();
......@@ -558,8 +543,7 @@ Batch inserts data into the database. This API uses an asynchronous callback to
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
{"name": "roe12", "age": 21, "salary": 20.5,},
......@@ -601,8 +585,7 @@ Batch inserts data into the database. This API uses a promise to return the resu
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,},
{"name": "roe12", "age": 21, "salary": 20.5,},
......@@ -636,8 +619,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.normalizeUri(uri, (err, data) => {
if (err != undefined) {
......@@ -671,8 +653,7 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.normalizeUri(uri).then((data) => {
console.log("normalizeUri = " + data);
......@@ -699,8 +680,7 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result.
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.denormalizeUri(uri, (err, data) => {
if (err != undefined) {
......@@ -734,8 +714,7 @@ Denormalizes a URI. This API uses a promise to return the result.
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.denormalizeUri(uri).then((data) => {
console.log("denormalizeUri = " + data);
......@@ -762,8 +741,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri, () => {
console.log("***** notifyChange *****");
......@@ -793,8 +771,7 @@ Notifies the registered observer of data changes. This API uses a promise to ret
**Example**
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import UIAbility from '@ohos.app.ability.UIAbility'
let uri = ("datashare:///com.samples.datasharetest.DataShare");
dataShareHelper.notifyChange(uri);
```
# Environment
# @ohos.file.environment (Directory Environment Capability)
The **Environment** module provides APIs for obtaining the root directories of the storage and public files.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import environment from '@ohos.environment';
import environment from '@ohos.file.environment';
```
## environment.getStorageDataDir
......@@ -30,10 +31,10 @@ Obtains the root directory of the storage. This API uses a promise to return the
**Example**
```js
environment.getStorageDataDir().then(function(path){
console.info("getStorageDataDir successfully:"+ path);
}).catch(function(error){
console.info("getStorageDataDir failed with error:"+ error);
environment.getStorageDataDir().then((path) => {
console.info("getStorageDataDir successfully, Path: " + path);
}).catch((err) => {
console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
});
```
......@@ -54,8 +55,12 @@ Obtains the root directory of the storage. This API uses an asynchronous callbac
**Example**
```js
environment.getStorageDataDir(function(error, path){
// do something
environment.getStorageDataDir((err, path) => {
if (err) {
console.info("getStorageDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getStorageDataDir successfully, Path: " + path);
}
});
```
......@@ -76,10 +81,10 @@ Obtains the root directory of public files. This API uses a promise to return th
**Example**
```js
environment.getUserDataDir().then(function(path){
console.info("getUserDataDir successfully:"+ path);
}).catch(function(error){
console.info("getUserDataDir failed with error:"+ error);
environment.getUserDataDir().then((path) => {
console.info("getUserDataDir successfully, Path: " + path);
}).catch((err) => {
console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
});
```
......@@ -100,7 +105,11 @@ Obtains the root directory of public files. This API uses an asynchronous callba
**Example**
```js
environment.getUserDataDir(function(error, path){
// do something
environment.getUserDataDir((err, path) => {
if (err) {
console.info("getUserDataDir failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("getUserDataDir successfully, Path: " + path);
}
});
```
此差异已折叠。
# @ohos.file.hash (File Hash Processing)
The **fileHash** module implements hash processing on files.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module support processing of error codes. For details, see [File Management Error Codes](../errorcodes/errorcode-filemanagement.md).
## Modules to Import
```js
import Hash from '@ohos.file.hash';
```
## Guidelines
Before using the APIs provided by this module to perform operations on a file or directory, obtain the path of the file or directory in the application sandbox as follows:
**Stage Model**
```js
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
let context = this.context;
let pathDir = context.filesDir;
}
}
```
**FA Model**
```js
import featureAbility from '@ohos.ability.featureAbility';
let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
let pathDir = data;
})
```
For details about how to obtain the FA model context, see [Context](js-apis-inner-app-context.md#context).
## Hash.hash
hash(path: string, algorithm: string): Promise&lt;string&gt;
Calculates a hash value for a file. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
**Return value**
| Type | Description |
| --------------------- | -------------------------- |
| Promise&lt;string&gt; | Promise used to return the hash value. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
let filePath = pathDir + "/test.txt";
Hash.hash(filePath, "sha256").then((str) => {
console.info("calculate file hash succeed:" + str);
}).catch((err) => {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
});
```
## Hash.hash
hash(path: string, algorithm: string, callback: AsyncCallback&lt;string&gt;): void
Calculates a hash value for a file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.File.FileIO
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | --------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the file in the application sandbox. |
| algorithm | string | Yes | Algorithm used to calculate the hash value. The value can be **md5**, **sha1**, or **sha256**. **sha256** is recommended for security purposes.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the hash value obtained. The hash value is a hexadecimal string consisting of digits and uppercase letters.|
**Example**
```js
Hash.hash(filePath, "sha256", (err, str) => {
if (err) {
console.info("calculate file hash failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("calculate file hash succeed:" + str);
}
});
```
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册