提交 b78d34d2 编写于 作者: F FangJinliang 提交者: Gitee

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

Signed-off-by: NFangJinliang <fangjinliang1@huawei.com>
...@@ -85,6 +85,7 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin ...@@ -85,6 +85,7 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin
zh-cn/device-dev/subsystems/subsys-security-huks-guide.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23
zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23
...@@ -348,4 +349,7 @@ zh-cn/application-dev/napi/napi-guidelines.md @RayShih ...@@ -348,4 +349,7 @@ zh-cn/application-dev/napi/napi-guidelines.md @RayShih
zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang
zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen
zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease
\ No newline at end of file zh-cn/application-dev/website.md @zengyawen
zh-cn/application-dev/faqs/ @zengyawen
zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
#!/bin/bash
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
docker build -t openharmony-docker:1.0.0 .
...@@ -590,7 +590,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -590,7 +590,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
testIntTransaction(data: number, callback: testIntTransactionCallback): void testIntTransaction(data: number, callback: testIntTransactionCallback): void
{ {
let _option = new rpc.MessageOption(rpc.MessageOption.TF_SYNC); let _option = new rpc.MessageOption();
let _data = new rpc.MessageParcel(); let _data = new rpc.MessageParcel();
let _reply = new rpc.MessageParcel(); let _reply = new rpc.MessageParcel();
_data.writeInt(data); _data.writeInt(data);
...@@ -612,7 +612,7 @@ export default class IdlTestServiceProxy implements IIdlTestService { ...@@ -612,7 +612,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
testStringTransaction(data: string, callback: testStringTransactionCallback): void testStringTransaction(data: string, callback: testStringTransactionCallback): void
{ {
let _option = new rpc.MessageOption(rpc.MessageOption.TF_SYNC); let _option = new rpc.MessageOption();
let _data = new rpc.MessageParcel(); let _data = new rpc.MessageParcel();
let _reply = new rpc.MessageParcel(); let _reply = new rpc.MessageParcel();
_data.writeString(data); _data.writeString(data);
......
...@@ -19,7 +19,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r ...@@ -19,7 +19,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise\<Caller>|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| |startAbilityByCall(want: Want): Promise\<Caller>|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.|
|on(method: string, callback: CaleeCallBack): void|Callback invoked when the callee registers a method.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.|
|off(method: string): void|Callback invoked when the callee deregisters a method.| |off(method: string): void|Callback invoked when the callee deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.|
...@@ -28,7 +28,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r ...@@ -28,7 +28,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r
## How to Develop ## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. For details about the complete project code, see [Samples](#samples). > The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently.
### Creating a Callee ### Creating a Callee
For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener.
1. Configure the ability startup mode. 1. Configure the ability startup mode.
......
...@@ -39,33 +39,36 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -39,33 +39,36 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
``` ```
2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined and override the lifecycle callbacks of the base class. The code sample is as follows: 2. Customize a class that inherits from **ServiceExtensionAbility** in the .ts file in the directory where the Service Extension ability is defined (**entry\src\main\ets\ServiceExtAbility\ServiceExtAbility.ts** by default) and override the lifecycle callbacks of the base class. The code sample is as follows:
```js ```js
import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'
import rpc from '@ohos.rpc' import rpc from '@ohos.rpc'
class StubTest extends rpc.RemoteObject { class StubTest extends rpc.RemoteObject {
constructor(des) { constructor(des) {
super(des); super(des);
} }
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
} }
} }
class ServiceExt extends ServiceExtensionAbility { class ServiceExtAbility extends ServiceExtensionAbility {
console.log('onCreate, want:' + want.abilityName); onCreate(want) {
} console.log('onCreate, want:' + want.abilityName);
onRequest(want, startId) { }
console.log('onRequest, want:' + want.abilityName); onRequest(want, startId) {
} console.log('onRequest, want:' + want.abilityName);
onConnect(want) { }
console.log('onConnect , want:' + want.abilityName); onConnect(want) {
return new StubTest("test"); console.log('onConnect , want:' + want.abilityName);
} return new StubTest("test");
onDisconnect(want) { }
console.log('onDisconnect, want:' + want.abilityName); onDisconnect(want) {
} console.log('onDisconnect, want:' + want.abilityName);
onDestroy() { }
console.log('onDestroy'); onDestroy() {
} console.log('onDestroy');
}
} }
``` ```
\ No newline at end of file
...@@ -17,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -17,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance **Table 1** API for creating a distributed data object instance
| Package| API| Description| | Package| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.| | ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
### Generating a Session ID ### Generating a Session ID
...@@ -35,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s ...@@ -35,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s
**Table 3** API for setting a session ID **Table 3** API for setting a session ID
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br> **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| | DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes ### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes. Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object **Table 4** APIs for observing data changes of a distributed data object
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.| | DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| | DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
### Observing Online or Offline Status ### Observing Online or Offline Status
...@@ -85,7 +85,11 @@ The following example shows how to implement a distributed data object synchroni ...@@ -85,7 +85,11 @@ The following example shows how to implement a distributed data object synchroni
```js ```js
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
2. Request the permission. <br>Add the required permission in the **config.json** file. The sample code is as follows:
2. Request the permission.
Add the required permission in the **config.json** file. The sample code is as follows:
``` ```
{ {
"module": { "module": {
...@@ -97,10 +101,11 @@ The following example shows how to implement a distributed data object synchroni ...@@ -97,10 +101,11 @@ The following example shows how to implement a distributed data object synchroni
} }
} }
``` ```
This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows: This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows:
```js
```
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
...@@ -108,11 +113,13 @@ The following example shows how to implement a distributed data object synchroni ...@@ -108,11 +113,13 @@ The following example shows how to implement a distributed data object synchroni
console.info(`result.requestCode=${result.requestCode}`) console.info(`result.requestCode=${result.requestCode}`)
}) })
console.info('end grantPermission'); console.info('end grantPermission');
} }
grantPermission(); grantPermission();
``` ```
3. Obtain a distributed data object instance. 3. Obtain a distributed data object instance.
The sample code is as follows: The sample code is as follows:
...@@ -130,7 +137,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -130,7 +137,7 @@ The following example shows how to implement a distributed data object synchroni
```js ```js
// Local object // Local object
var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true,
parent:{mother:"jack mom",father:"jack Dad"},list:[{mother:"jack mom"}, {father:"jack Dad"}]}); parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]});
local_object.setSessionId(sessionId); local_object.setSessionId(sessionId);
// Remote object // Remote object
...@@ -140,8 +147,10 @@ The following example shows how to implement a distributed data object synchroni ...@@ -140,8 +147,10 @@ The following example shows how to implement a distributed data object synchroni
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
``` ```
5. Observe the data changes of the distributed data object. <br>You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. 5. Observe the data changes of the distributed data object.
You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -152,26 +161,32 @@ The following example shows how to implement a distributed data object synchroni ...@@ -152,26 +161,32 @@ The following example shows how to implement a distributed data object synchroni
changeData.forEach(element => { changeData.forEach(element => {
console.info("changed !" + element + " " + local_object[element]); console.info("changed !" + element + " " + local_object[element]);
}); });
} }
} }
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback. // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this)); local_object.on("change", this.changeCallback.bind(this));
``` ```
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). 6. Modify object attributes.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows: The sample code is as follows:
```js ```js
local_object.name = "jack"; local_object.name = "jack";
local_object.age = 19; local_object.age = 19;
local_object.isVis = false; local_object.isVis = false;
local_object.parent = {mother:"jack mom",father:"jack Dad"}; local_object.parent = {mother:"jack mom", father:"jack Dad"};
local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}]; local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}];
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example: >
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified.
Example:
```js ```js
// Supported modification. // Supported modification.
local_object.parent = {mother:"mom", father:"dad"}; local_object.parent = {mother:"mom", father:"dad"};
...@@ -179,13 +194,18 @@ The following example shows how to implement a distributed data object synchroni ...@@ -179,13 +194,18 @@ The following example shows how to implement a distributed data object synchroni
local_object.parent.mother = "mom"; local_object.parent.mother = "mom";
``` ```
7. Access the distributed data object. <br>Obtain the distributed data object attribute, which is the latest data on the network. 7. Access the distributed data object.
Obtain the distributed data object attribute, which is the latest data on the network.
The sample code is as follows: The sample code is as follows:
```js ```js
console.info("name " + local_object["name"]); console.info("name " + local_object["name"]);
``` ```
8. Unsubscribe from data changes. <br>You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
8. Unsubscribe from data changes.
You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -194,6 +214,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -194,6 +214,7 @@ The following example shows how to implement a distributed data object synchroni
// Unregister all data change callbacks. // Unregister all data change callbacks.
local_object.off("change"); local_object.off("change");
``` ```
9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -207,58 +228,62 @@ The following example shows how to implement a distributed data object synchroni ...@@ -207,58 +228,62 @@ The following example shows how to implement a distributed data object synchroni
10. Save a distributed data object and revoke the data saving operation. 10. Save a distributed data object and revoke the data saving operation.
- Callback - Callback
```js ```
// Save a distributed data object. ​```js
local_object.save("local", (result, data)=>{ // Save a distributed data object.
console.log("save callback"); local_object.save("local", (result, data) => {
console.info("save sessionId " + data.sessionId); console.log("save callback");
console.info("save version " + data.version); console.info("save sessionId " + data.sessionId);
console.info("save deviceId " + data.deviceId); console.info("save version " + data.version);
}); console.info("save deviceId " + data.deviceId);
// Revoke the data saving operation. });
local_object.revokeSave((result, data) =>{ // Revoke the data saving operation.
console.log("revokeSave callback"); local_object.revokeSave((result, data) => {
console.info("revokeSave sessionId " + data.sessionId); console.log("revokeSave callback");
}); console.info("revokeSave sessionId " + data.sessionId);
``` });
- Promise ​```
```js ```
// Save a distributed data object.
g_object.save("local").then((result)=>{ - Promise
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version); ```
console.info("save deviceId " + result.deviceId); ​```js
}, (result)=>{ // Save a distributed data object.
console.info("save local failed."); g_object.save("local").then((result) => {
}); console.info("save sessionId " + result.sessionId);
// Revoke the data saving operation. console.info("save version " + result.version);
g_object.revokeSave().then((result)=>{ console.info("save deviceId " + result.deviceId);
console.info("revokeSave success."); }, (result)=>{
}, (result)=>{ console.info("save local failed.");
console.info("revokeSave failed."); });
}); // Revoke the data saving operation.
``` g_object.revokeSave().then((result) => {
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
​```
```
11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
The sample code is as follows: The sample code is as follows:
```js ```js
// Unregister the specified status change callback. // Unregister the specified status change callback.
local_object.off("status", this.statusCallback); local_object.off("status", this.statusCallback);
// Unregister all status change callbacks. // Unregister all status change callbacks.
local_object.off("status"); local_object.off("status");
``` ```
12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. 12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object.
The sample code is as follows: The sample code is as follows:
```js ```js
local_object.setSessionId(""); local_object.setSessionId("");
``` ```
## Development Example
The following example is provided for you to better understand the development of distributed data objects:
- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad)
When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network.
...@@ -6,22 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,22 +6,20 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| Category | API | Description | | API | Description |
| ------------ | ------------- | ------------- | | ------------------------------------------------------------ | ----------------------------------------------- |
| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.| | createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed 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; | Obtains the KV store with the specified **Options** and **storeId**.| | 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; | Obtains a KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed 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.| | 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. |
| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. | | delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br>delete(key:string):Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store| 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> | Queries data. |
| Subscribing to changes in the distributed 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.| | 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. |
| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | | sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. |
...@@ -36,11 +34,14 @@ The following uses a single KV store as an example to describe the development p ...@@ -36,11 +34,14 @@ The following uses a single KV store as an example to describe the development p
``` ```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
(1) Create a **KvManagerConfig** object based on the application context. (1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
(2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js
```
let kvManager; let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
...@@ -62,9 +63,12 @@ The following uses a single KV store as an example to describe the development p ...@@ -62,9 +63,12 @@ The following uses a single KV store as an example to describe the development p
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
} }
``` ```
3. Create and obtain a single KV store. 3. Create and obtain a single KV store.
(1) Declare the ID of the single KV store to create. (1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows: The sample code is as follows:
...@@ -92,8 +96,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -92,8 +96,9 @@ The following uses a single KV store as an example to describe the development p
} }
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. >
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/> 4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store: The following is the sample code for subscribing to the data changes of a single KV store:
...@@ -104,7 +109,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -104,7 +109,9 @@ The following uses a single KV store as an example to describe the development p
``` ```
5. Write data to the single KV store. 5. Write data to the single KV store.
(1) Construct the key and value to be written into the single KV store. (1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store. (2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store: The following is the sample code for writing key-value pairs of the string type into the single KV store:
...@@ -126,7 +133,9 @@ The following uses a single KV store as an example to describe the development p ...@@ -126,7 +133,9 @@ The following uses a single KV store as an example to describe the development p
``` ```
6. Query data in the single KV store. 6. Query data in the single KV store.
(1) Construct the key to be queried from the single KV store. (1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store. (2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store: The following is the sample code for querying data of the string type from the single KV store:
...@@ -152,7 +161,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -152,7 +161,11 @@ The following uses a single KV store as an example to describe the development p
7. Synchronize data to other devices.<br/> 7. Synchronize data to other devices.<br/>
Select the devices in the same network and the synchronization mode to synchronize data. Select the devices in the same network and the synchronization mode to synchronize data.
The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms. > **NOTE**
>
> The APIs of the `deviceManager` module are system interfaces.
The following is the sample code for synchronizing data in a single KV store:
```js ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
...@@ -161,7 +174,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -161,7 +174,7 @@ The following uses a single KV store as an example to describe the development p
deviceManager.createDeviceManager("bundleName", (err, value) => { deviceManager.createDeviceManager("bundleName", (err, value) => {
if (!err) { if (!err) {
devManager = value; devManager = value;
// Obtain deviceIds. // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync().
let deviceIds = []; let deviceIds = [];
if (devManager != null) { if (devManager != null) {
var devices = devManager.getTrustedDeviceListSync(); var devices = devManager.getTrustedDeviceListSync();
...@@ -170,6 +183,7 @@ The following uses a single KV store as an example to describe the development p ...@@ -170,6 +183,7 @@ The following uses a single KV store as an example to describe the development p
} }
} }
try{ try{
// 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
}catch (e) { }catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error:" + e);
...@@ -177,7 +191,3 @@ The following uses a single KV store as an example to describe the development p ...@@ -177,7 +191,3 @@ The following uses a single KV store as an example to describe the development p
} }
}); });
``` ```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
...@@ -65,9 +65,9 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -65,9 +65,9 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error) => { vibrator.vibrate(1000).then((error) => {
if (error) { // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
} else { // The call is successful, and the device starts to vibrate. } else { // The call is successful, and the device starts to vibrate.
Console.log("Promise returned to indicate a successful vibration.") console.log("Promise returned to indicate a successful vibration.")
} }
}) })
``` ```
...@@ -78,9 +78,9 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -78,9 +78,9 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => { vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
if (error) { // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
} else { // The call is successful, and the device stops vibrating. } else { // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop."); console.log("Promise returned to indicate successful.");
} }
}) })
``` ```
...@@ -39,28 +39,28 @@ function printfDescription(obj) { ...@@ -39,28 +39,28 @@ function printfDescription(obj) {
// Set the player callbacks. // Set the player callbacks.
function setCallBack(audioPlayer) { function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the `play` event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the `pause` event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the `stop` event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success'); console.info('audio stop success');
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the `reset` event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the `timeUpdate` event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
...@@ -68,7 +68,7 @@ function setCallBack(audioPlayer) { ...@@ -68,7 +68,7 @@ function setCallBack(audioPlayer) {
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the `volumeChange` event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
...@@ -107,7 +107,7 @@ async function audioPlayerDemo() { ...@@ -107,7 +107,7 @@ async function audioPlayerDemo() {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
``` ```
...@@ -119,11 +119,11 @@ import fileIO from '@ohos.fileio' ...@@ -119,11 +119,11 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the `play` event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
...@@ -147,7 +147,7 @@ export class AudioDemo { ...@@ -147,7 +147,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -161,15 +161,15 @@ export class AudioDemo { ...@@ -161,15 +161,15 @@ export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
private isNextMusic = false; private isNextMusic = false;
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the `play` event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('reset', () => { // Set the `reset` event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play success'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented.
...@@ -223,7 +223,7 @@ import fileIO from '@ohos.fileio' ...@@ -223,7 +223,7 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute. audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
...@@ -247,7 +247,7 @@ export class AudioDemo { ...@@ -247,7 +247,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -267,7 +267,7 @@ imageSourceApi.getImageInfo(imageInfo => { ...@@ -267,7 +267,7 @@ imageSourceApi.getImageInfo(imageInfo => {
}) })
// Update incremental data. // Update incremental data.
imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {}) imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error, data)=> {})
``` ```
......
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
- Getting Started - Getting Started
- [Preparations](start-overview.md) - [Preparations](start-overview.md)
- [Getting Started with eTS in the Traditional Coding Approach](start-with-ets.md) - [Getting Started with eTS in Stage Model](start-with-ets-stage.md)
- [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md) - [Getting Started with eTS in FA Model](start-with-ets-fa.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md) - [Getting Started with JavaScript in FA Model](start-with-js-fa.md)
- [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md)
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md) - [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
......
因为 它太大了无法显示 image diff 。你可以改为 查看blob
# Preparations # Preparations
This document is intended for novices at developing OpenHarmony applications. It will introduce you to the OpenHarmony project directory structure and application development process, by walking you through a stripped-down, real-world example – building two pages and implementing redirection between pages. The following figure shows how the pages look on the DevEco Studio Previewer. This document is intended for novices at developing OpenHarmony applications. It will introduce you to the OpenHarmony project directory structure and application development process, by walking you through a stripped-down, real-world example – building two pages and implementing redirection between them. The following figure shows how the pages look on the DevEco Studio Previewer.
![en-us_image_0000001261809595](figures/en-us_image_0000001261809595.png) ![en-us_image_0000001364254729](figures/en-us_image_0000001364254729.png)
Before you begin, there are some basic concepts that will help you better understand OpenHarmony: UI framework and ability. Before you begin, there are two basic concepts that will help you better understand OpenHarmony: UI framework and ability.
## Basic Concepts ## Basic Concepts
...@@ -14,37 +14,39 @@ Before you begin, there are some basic concepts that will help you better unders ...@@ -14,37 +14,39 @@ Before you begin, there are some basic concepts that will help you better unders
### UI Framework ### UI Framework
OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides capabilities you may need for application UI development, including a wide array of components, layout calculation, animation, UI interaction, and drawing capabilities. OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides a full range of capabilities you may need for application UI development, ranging from components to layout calculation, animation, UI interaction, and drawing capabilities.
ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice. ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
| **Development Paradigm** | **Language** | **UI Update Mode** | **Applicable To** | **Intended Audience** | | **Development Paradigm**| **Programming Language**| **UI Update Mode**| **Applicable To**| **Intended Audience**|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| Web-like development paradigm | JavaScript | Data-driven | Applications and service widgets with simple UIs | Frontend web developers | | Declarative development paradigm| Extended TypeScript (eTS)| Data-driven| Applications involving technological sophistication and teamwork| Mobile application and system application developers|
| Declarative development paradigm | Extended TypeScript (eTS) | Data-driven | Applications involving technological sophistication and teamwork | Mobile application and system application developers | | Web-like development paradigm| JavaScript| Data-driven| Applications and service widgets with simple UIs| Frontend web developers|
For DevEco Studio V2.2 Beta1 and later versions, both the traditional coding mode and the low-code mode are supported when the JS language is used for development. For more details, see [UI Development](../ui/arkui-overview.md).
For eTS language development, DevEco Studio V3.0 Beta3 and later versions support low-code development in addition to the traditional code development mode.
On the OpenHarmony low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features. ### Ability
An ability is the abstraction of a functionality that an application can provide. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other.
### Ability The ability framework model has two forms:
- **FA model**: applies to application development using API version 8 and earlier versions. For details, see [FA Model Overview](../ability/fa-brief.md).
An ability is an abstraction of a capability that an application can provide. The **Ability** class is an essential component to OpenHarmony applications. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other. - **Stage model**: introduced since API version 9. For details, see [Stage Model Overview](../ability/stage-brief.md).
Abilities are classified into two types: [Feature Ability (FA)](../../glossary.md#f) and [Particle Ability (PA)](../../glossary.md#p). Each type has their respective templates for different capabilities. FAs support only the Page template (also called the [Page ability](../ability/fa-pageability.md)), which is used to provide the capability of interacting with users. A Page ability consists of one or more pages. The figure below shows the relationship between a Page ability and pages. The project directory structure of the FA model is different from that of the stage model. The stage model only works with the eTS programming language.
![en-us_image_0000001215206886](figures/en-us_image_0000001215206886.png) For details about the differences between the FA model and stage model, see [Ability Framework Overview](../ability/ability-brief.md).
This document provides a Page ability instance with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md). This document provides an ability with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md).
## Tool Preparation ## Tool Preparation
1. Install the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony). 1. Download the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta).
2. Install DevEco Studio and configure the development environment. For details, see [Configuring the OpenHarmony SDK](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443). 2. Install DevEco Studio and configure the development environment. For details, see [Setting Up the Development Environment](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443).
When you are done, follow the instructions in [Getting Started with eTS in the Traditional Coding Approach](start-with-ets.md), [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md), [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md), and [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md). When you are done, follow the instructions in [Getting Started with eTS in Stage Model](start-with-ets-stage.md), [Getting Started with eTS in FA Model](start-with-ets-fa.md), and [Getting Started with JavaScript in FA Model](../quick-start/start-with-js-fa.md).
# Getting Started with eTS in FA Model
> **NOTE**
>
> To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
>
> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
## Creating an eTS Project
1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
![01](figures/01.png)
2. In the project configuration page, set **Compile SDK** to **8** or **9** (in the latter case, you also need to set **Model** to **FA**) and **Language** to **eTS** and retain the default values for other parameters.
![02](figures/02.png)
> **NOTE**
>
> If you are using DevEco Studio V3.0 Beta3 or later, you can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach.
>
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
>
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## eTS Project Directory Structure
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **src > main > ets**: a collection of eTS source code.
- **src > main > ets > MainAbility**: entry to your application/service.
- **src > main > ets > MainAbility > pages**: pages contained in **MainAbility**.
- **src > main > ets > MainAbility > pages > index.ets**: the first page in the **pages** list, also referred to as the entry to the application.
- **src > main > ets > MainAbility > app.ets**: ability lifecycle file.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource File Categories](../ui/ui-ts-basic-resource-file-categories.md).
- **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.js**: application-level compilation and build task script.
## Building the First Page
1. Use the **\<Text>** component.
After the project synchronization is complete, choose **entry** > **src** > **main** > **ets** > **MainAbility** > **pages** in the **Project** window and open the **index.ets** file. You can see that the file contains a **\<Text>** component. The sample code in the **index.ets** file is shown below:
```ts
// index.ets
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
2. Add a **\<Button>** component.
On the default page, add a **\<Button>** component to respond to user clicks and implement redirection to another page. The sample code in the **index.ets** file is shown below:
```ts
// index.ets
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Add a button to respond to user clicks.
Button() {
Text('Next')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
}
.width('100%')
}
.height('100%')
}
}
```
3. On the toolbar in the upper right corner of the editing window, click **Previewer**. Below is how the first page looks in the Previewer.
![en-us_image_0000001364254741](figures/en-us_image_0000001364254741.png)
## Building the Second Page
1. Create the second page.
- Create the second page file: In the **Project** window, choose **entry** > **src** > **main** > **ets** > **MainAbility**. Right-click the **pages** folder, choose **New** > **eTS File**, name the page **second**, and click **Finish**. Below is the structure of the **second** folder.
![en-us_image_0000001311334932](figures/en-us_image_0000001311334932.png)
> **NOTE**
>
> You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes.
- Configure the route for the second page, by setting **pages/second** under **module - js - pages** in the **config.json** The sample code is as follows: The sample code is as follows:
```json
{
"module": {
"js": [
{
"pages": [
"pages/index",
"pages/second"
],
}
]
}
}
```
2. Add **\<Text>** and **\<Button>** components.
Add **\<Text>** and **\<Button>** components and set their styles, as you do for the first page. The sample code in the **second.ets** file is shown below:
```ts
// second.ets
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Back')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
}
.width('100%')
}
.height('100%')
}
}
```
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **index.ets** file is shown below:
```ts
// index.ets
import router from '@ohos.router';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Add a button to respond to user clicks.
Button() {
Text('Next')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
// Bind the onClick event to the Next button so that clicking the button redirects the user to the second page.
.onClick(() => {
router.push({ url: 'pages/second' })
})
}
.width('100%')
}
.height('100%')
}
}
```
2. Implement redirection from the second page to the first page.
In the **second.ets** file of the second page, bind the **onClick** event to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.ets** file is shown below:
```ts
// second.ets
import router from '@ohos.router';
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Back')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
// Bind the onClick event to the Back button so that clicking the button redirects the user back to the first page.
.onClick(() => {
router.back()
})
}
.width('100%')
}
.height('100%')
}
}
```
3. Open the **index.ets** file and click ![en-us_image_0000001311175120](figures/en-us_image_0000001311175120.png) in the Previewer to refresh the file. The display effect is shown in the figure below.
![en-us_image_0000001364173989](figures/en-us_image_0000001364173989.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001311494580](figures/en-us_image_0000001311494580.png). The display effect is shown in the figure below.
![en-us_image_0000001363934577](figures/en-us_image_0000001363934577.png)
Congratulations! You have finished developing your OpenHarmony application in eTS in the FA model. To learn more about OpenHarmony application development, see [Application Development Overview](../application-dev-guide.md).
# Getting Started with eTS in the Low-Code Approach
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>This feature is supported in DevEco Studio V3.0 Beta3 and later versions.
>
> The component lineup that supports low-code development in eTS is now at its preliminary stage and will be expanding in coming versions.
>
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development.
On the OpenHarmony low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
You can develop applications or services in the low-code approach using either of the following methods:
- Create a project that supports low-code development. This method is used as an example in this topic.
- In an existing project, create a .visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page).
## Creating a Project That Supports Low-Code Development
1. In DevEco Studio, if no project is open, click **Create Project**; if a project is already open, choose **File** &gt; **New** &gt; **Create Project**. Then, select **Empty Ability** and click **Next**.
![en-us_image_0000001233528152](figures/en-us_image_0000001233528152.png)
2. Go to the project configuration page, select **Enable Super Visual**, set **UI Syntax** to **eTS**, and retain the default values for other parameters.
![en-us_image_0000001277728569](figures/en-us_image_0000001277728569.png)
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## Low-code Project Files
After the project synchronization is complete, a low-code directory structure is automatically generated in the project, as shown below.
![en-us_image_0000001277809333](figures/en-us_image_0000001277809333.png)
- **entry &gt; src &gt; main &gt; ets &gt; MainAbility &gt; pages &gt; index.ets**: defines logical relationships, such as data and events, used on low-code pages. For details, see [About Syntactic Sugar](../ui/ts-syntactic-sugar.md). If multiple low-code development pages are created, a page folder and the corresponding **.ets** file will be created for each of these pages.
- **entry &gt; src &gt; main &gt; supervisual &gt; MainAbility &gt; pages &gt; index.visual**: stores the data model of the low-code development page. You can double-click the file to open the low-code development page. If multiple low-code development pages are created, a page folder and the corresponding **.visual** file will be created for each of these pages.
## Building the First Page
After the project synchronization is complete, the default first page contains the **Column** and **Text** (**Hello World**) components. To better understand low-code development, we'll delete these template components from the canvas and set the page from scratch.
Add **Column**, **Text**, and **Button** components to the first page. A column is a container component whose child components are vertically arranged. For details, see [Column](../reference/arkui-ts/ts-container-column.md).
1. Delete the existing template components from the canvas.<a name="delete_origin_content"></a>
Open the **index.visual** file, right-click the existing template components on the canvas, and choose **Delete** from the shortcut menu to delete them. Below is an illustration of the operations.
![en-us_image_0000001233208980](figures/en-us_image_0000001233208980.gif)
2. Add a **Column** component and set its styles and attributes.<a name="add_container"></a>
Drag the **Column** component from the **UI Control** area to the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001233048996](figures/en-us_image_0000001233048996.png)**General** and set **Height** to **100%** so that the component fills the entire screen. Click ![en-us_image_0000001233368860](figures/en-us_image_0000001233368860.png)**Feature** and set **AlignItems** to **center** so that the child components of the **Column** component are centered along the horizontal axis. Below is an illustration of the operations.
![en-us_image_0000001277488977](figures/en-us_image_0000001277488977.gif)
3. Add a **Text** component.
Drag the **Text** component from the **UI Control** area to the canvas and then to the center area of the **Column** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001277608813](figures/en-us_image_0000001277608813.png)**Feature**, set **Content** of the **Text** component to **this.message** (that is, **Hello World**), set **FontSize** to **30fp**, and set **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001235731706](figures/en-us_image_0000001235731706.gif)
4. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to the canvas and then to a position under the **Text** component. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001277728577](figures/en-us_image_0000001277728577.png)**General** and set **Height** of the **Button** component to **40vp**. Click ![en-us_image_0000001277809337](figures/en-us_image_0000001277809337.png)**Feature** and set **Label** to **Next** and **FontSize** to **25fp**. Below is an illustration of the operations.
![en-us_image_0000001235732402](figures/en-us_image_0000001235732402.gif)
5. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer.
Below is how the first page looks in the Previewer.
![en-us_image_0000001235892798](figures/en-us_image_0000001235892798.png)
## Building the Second Page
1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **ets** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Visual**, name the page **second**, and click **Finish**. Below, you can see the structure of the **pages** folder.
![en-us_image_0000001233368868](figures/en-us_image_0000001233368868.png)
2. [Delete the existing template components from the canvas.](#delete_origin_content)
3. [Add a **Column** component and set its styles and attributes.](#add_container)
4. Add a **Text** component.
- In the **second.ets** file, set the message text content to **Hi there**. The sample code is as follows:
```ts
// second.ets
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
/**
* In low-code mode, do not add anything to the build function, as it will be
* overwritten by the content generated by the .visual file in the build phase.
*/
build() {
}
}
```
- Drag the **Text** component to the canvas and then to the center area of the **Column** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001277488985](figures/en-us_image_0000001277488985.png)**Feature**, set **Content** of the **Text** component to **this.message** (that is, **Hi there**), set **FontSize** to **30fp**, and set **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001280255513](figures/en-us_image_0000001280255513.gif)
5. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to the canvas and then to a position under the **Text** component. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001233528160](figures/en-us_image_0000001233528160.png)**General** and set **Height** of the **Button** component to **40vp**. Click ![en-us_image_0000001277728597](figures/en-us_image_0000001277728597.png)**Feature** and set **Value** to **Back** and **FontSize** to **25fp**. Below is an illustration of the operations.
![en-us_image_0000001280383937](figures/en-us_image_0000001280383937.gif)
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the files of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. This operation needs to be completed in both .ets and .visual files.
- In the **index.ets** file:
```ts
// index.ets
import router from '@ohos.router';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
/**
* In low-code mode, do not add anything to the build function, as it will be
* overwritten by the content generated by the .visual file in the build phase.
*/
onclick() {
router.push({
url: 'pages/second', // Specify the page to be redirected to.
})
}
build() {
}
}
```
- In the **index.visual** file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001233209020](figures/en-us_image_0000001233209020.png)**Events** and set **OnClick** to **this.onclick**.
![en-us_image_0000001235745716](figures/en-us_image_0000001235745716.png)
2. Implement redirection from the second page to the first page.
In the files of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. This operation needs to be completed in both .ets and .visual files.
- In the **second.ets** file:
```ts
// second.ets
import router from '@ohos.router';
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
/**
* In low-code mode, do not add anything to the build function, as it will be
* overwritten by the content generated by the .visual file in the build phase.
*/
back() {
router.back()
}
build() {
}
}
```
- In the **second.visual** file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001233368900](figures/en-us_image_0000001233368900.png)**Events** and set **OnClick** to **this.back**.
![en-us_image_0000001280385809](figures/en-us_image_0000001280385809.png)
3. Open the **index.visual** or **index.ets** file and click ![en-us_image_0000001277608849](figures/en-us_image_0000001277608849.png) in the Previewer to refresh the file. The figure below shows the effect.
![en-us_image_0000001233528192](figures/en-us_image_0000001233528192.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below.
![en-us_image_0000001277728613](figures/en-us_image_0000001277728613.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001277809373](figures/en-us_image_0000001277809373.png). The display effect is shown in the figure below.
![en-us_image_0000001233209024](figures/en-us_image_0000001233209024.png)
Congratulations! You have finished developing your OpenHarmony application in eTS in the low-code approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md).
# Getting Started with eTS in the Traditional Coding Approach # Getting Started with eTS in Stage Model
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
> **NOTE**
>
> To use eTS, your DevEco Studio must be V3.0.0.900 Beta3 or later.
> >
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development. > For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
## Creating an eTS Project ## Creating an eTS Project
1. In DevEco Studio, if no project is open, click **Create Project**; if a project is already open, choose **File** &gt; **New** &gt; **Create Project**. Then, select **Empty Ability** and click **Next**. 1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
![en-us_image_0000001223556342](figures/en-us_image_0000001223556342.png) ![01](figures/01.png)
2. On the project configuration page, set **UI Syntax** to **eTS** and retain the default values for other parameters. 2. On the project configuration page, set **Compile SDK** to **9**, **Model** to **Stage**, **Language** to **eTS** and retain the default values for other parameters.
![en-us_image_0000001223716826](figures/en-us_image_0000001223716826.png) ![07](figures/07.png)
> **NOTE**
>
> You can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach.
>
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
>
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. 3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## eTS Project Files ## eTS Project Directory Structure
- **entry**: OpenHarmony project module, which can be built into an ability package ([HAP](../../glossary.md#hap)). ![en-us_image_0000001364054489](figures/en-us_image_0000001364054489.png)
- **src &gt; main &gt; ets**: a collection of eTS source code.
- **src &gt; main &gt; ets &gt; MainAbility**: entry to your application/service. - **AppScope > app.json5**: application-level configuration information.
- **src &gt; main &gt; ets &gt; MainAbility &gt; pages**: pages contained in **MainAbility**.
- **src &gt; main &gt; ets &gt; MainAbility &gt; pages &gt; index.ets**: the first page in the pages list, that is, the home page of your application. - **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **src &gt; main &gt; ets &gt; MainAbility &gt; app.ets**: ability lifecycle file. - **src > main > ets**: a collection of eTS source code.
- **src &gt; main &gt; resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. - **src > main > ets > Application > AbilityStage.ts**: implementation of AbilityStage APIs.
- **src &gt; main &gt; config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. - **src > main > ets > MainAbility**: entry to your application/service.
- **src > main > ets > MainAbility > MainAbility.ets**: ability lifecycle file.
- **src > main > ets > pages**: pages contained in **MainAbility**.
- **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource File Categories](../ui/ui-ts-basic-resource-file-categories.md).
- **src > main > module.json5**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (Stage Model)](stage-structure.md).
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation. - **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration. - **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.js**: application-level compilation and build task script. - **hvigorfile.js**: application-level compilation and build task script.
## Building the First Page ## Building the First Page
1. Use the **Text** component. 1. Use the **\<Text>** component.
After the project synchronization is complete, choose **entry** &gt; **src** &gt; **main** &gt; **ets** &gt; **MainAbility** &gt; **pages** in the **Project** window and open the **index.ets** file. You can see that the file contains a **&lt;Text&gt;** component. The sample code in the **index.ets** file is shown below:
After the project synchronization is complete, choose **entry** > **src** > **main** > **ets** > **MainAbility** > **pages** in the **Project** window and open the **index.ets** file. You can see that the file contains a **\<Text>** component. The sample code in the **index.ets** file is shown below:
```ts ```ts
// index.ets // index.ets
@Entry @Entry
...@@ -62,11 +79,11 @@ ...@@ -62,11 +79,11 @@
} }
``` ```
2. Add a **&lt;Button&gt;** component. 2. Add a **\<Button>** component.
On the default page, add a **&lt;Button&gt;** component to respond to user clicks and implement redirection to another page. The sample code in the **index.ets** file is shown below:
On the default page, add a **\<Button>** component to respond to user clicks and implement redirection to another page. The sample code in the **index.ets** file is shown below:
```ts ```ts
// index.ets // index.ets
@Entry @Entry
...@@ -101,26 +118,38 @@ ...@@ -101,26 +118,38 @@
} }
``` ```
3. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. 3. On the toolbar in the upper right corner of the editing window, click **Previewer**. Below is how the first page looks in the Previewer.
Below is how the first page looks on the Previewer. ![en-us_image_0000001311334976](figures/en-us_image_0000001311334976.png)
![en-us_image_0000001216239356](figures/en-us_image_0000001216239356.png)
## Building the Second Page ## Building the Second Page
1. Create the second page. 1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **ets** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Page**, name the page **second**, and click **Finish**. Below, you can see the structure of the **pages** folder.
![en-us_image_0000001223397122](figures/en-us_image_0000001223397122.png) - Create the second page file: In the **Project** window, choose **entry** > **src** > **main** > **ets**. Right-click the **pages** folder, choose **New** > **eTS File**, name the page **second**, and click **Finish**. Below is the structure of the **second** folder.
![09](figures/09.png)
2. Add **&lt;Text&gt;** and **&lt;Button&gt;** components. > **NOTE**
>
> You can also right-click the **pages** folder and choose **New** > **Page** from the shortcut menu. In this scenario, you do not need to manually configure page routes.
- Configure the route for the second page: In the **Project** window, choose **entry** > **src** > **main** > **resources** > **base** > **profile**. In the **main_pages.json** file, set **pages/second** under **src**. The sample code is as follows:
```json
{
"src": [
"pages/index",
"pages/second"
]
}
```
Add **&lt;Text&gt;** and **&lt;Button&gt;** components and set their styles, as you do for the first page. The sample code in the **second.ets** file is shown below: 2. Add **\<Text>** and **\<Button>** components.
Add **\<Text>** and **\<Button>** components and set their styles, as you do for the first page. The sample code in the **second.ets** file is shown below:
```ts ```ts
// second.ets // second.ets
@Entry @Entry
...@@ -160,10 +189,10 @@ ...@@ -160,10 +189,10 @@
You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page. 1. Implement redirection from the first page to the second page.
In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **index.ets** file is shown below:
In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **index.ets** file is shown below:
```ts ```ts
// index.ets // index.ets
import router from '@ohos.router'; import router from '@ohos.router';
...@@ -208,7 +237,7 @@ You can implement page redirection through the page router, which finds the targ ...@@ -208,7 +237,7 @@ You can implement page redirection through the page router, which finds the targ
In the **second.ets** file of the second page, bind the **onClick** event to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.ets** file is shown below: In the **second.ets** file of the second page, bind the **onClick** event to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.ets** file is shown below:
```ts ```ts
// second.ets // second.ets
import router from '@ohos.router'; import router from '@ohos.router';
...@@ -248,21 +277,21 @@ You can implement page redirection through the page router, which finds the targ ...@@ -248,21 +277,21 @@ You can implement page redirection through the page router, which finds the targ
} }
``` ```
3. Open the **index.ets** file and click ![en-us_image_0000001262219043](figures/en-us_image_0000001262219043.png) in the Previewer to refresh the file. The figure below shows the effect. 3. Open the **index.ets** file and click ![en-us_image_0000001311015192](figures/en-us_image_0000001311015192.png) in the Previewer to refresh the file. The display effect is shown in the figure below.
![en-us_image_0000001260684127](figures/en-us_image_0000001260684127.png) ![en-us_image_0000001364254773](figures/en-us_image_0000001364254773.png)
## Running the Application on a Real Device ## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below. 2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![en-us_image_0000001268077317](figures/en-us_image_0000001268077317.png) ![06](figures/06.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001262206247](figures/en-us_image_0000001262206247.png). The display effect is shown in the figure below. 3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001364054485](figures/en-us_image_0000001364054485.png). The display effect is shown in the figure below.
![en-us_image_0000001217526428](figures/en-us_image_0000001217526428.png) ![en-us_image_0000001311334972](figures/en-us_image_0000001311334972.png)
Congratulations! You have finished developing your OpenHarmony application in eTS in the traditional coding approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md) Congratulations! You have finished developing your OpenHarmony application in eTS in the stage model. To learn more about OpenHarmony application development, see [Application Development Overview](../application-dev-guide.md).
# Getting Started with JavaScript in the Traditional Coding Approach # Getting Started with JavaScript in FA Model
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development.
> **NOTE**
> >
> For best possible results, use [DevEco Studio V3.0.0.991 Beta4](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
## Creating a JavaScript Project ## Creating a JavaScript Project
1. In DevEco Studio, if no project is open, click **Create Project**; if a project is already open, choose **File** &gt; **New** &gt; **Create Project**. Then, select **Empty Ability** and click **Next**. 1. If you are opening DevEco Studio for the first time, click **Create Project**. If a project is already open, choose **File** > **New** > **Create Project** from the menu bar. On the **OpenHarmony** tab of the **Choose Your Ability Template** page, select **Empty Ability** and click **Next**.
![01](figures/01.png)
![en-us_image_0000001223558814](figures/en-us_image_0000001223558814.png) 2. In the project configuration page, set **Compile SDK** to **8** or **9** (in the latter case, you also need to set **Model** to **FA**) and **Language** to **JS** and retain the default values for other parameters.
2. On the project configuration page, set **UI Syntax** to **JS** and retain the default values for other parameters. ![04](figures/04.png)
![en-us_image_0000001223877162](figures/en-us_image_0000001223877162.png) > **NOTE**
>
> If you are using DevEco Studio V2.2 Beta1 or later, you can use the [low-code development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652) mode apart from the traditional coding approach.
>
> On the low-code development pages, you can design your application UI in an efficient, intuitive manner, with a wide array of UI editing features.
>
> To use the low-code development mode, turn on **Enable Super Visual** on the page shown above.
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. 3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## JavaScript Project Files ## JavaScript Project Directory Structure
- **entry**: OpenHarmony project module, which can be built into an OpenHarmony Ability Package ([HAP](../../glossary.md#hap)).
- **src > main > js**: a collection of JavaScript source code.
- **src > main > js > MainAbility**: entry to your application/service.
- **src > main > js > MainAbility > i18n**: resources in different languages, for example, UI strings and image paths.
- **src > main > js > MainAbility > pages**: pages contained in **MainAbility**.
- **src > main > js > MainAbility > app.js**: ability lifecycle file.
- **entry**: OpenHarmony project module, which can be built into an ability package ([HAP](../../glossary.md#hap)). - **src > main > resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files. For details about resource files, see [Resource Limitations and Access](../ui/js-framework-resource-restriction.md).
- **src &gt; main &gt; js**: a collection of JS source code. - **src > main > config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file. For details about the configuration file, see [Application Package Structure Configuration File (FA Model)](package-structure.md).
- **src &gt; main &gt; js &gt; MainAbility**: entry to your application/service.
- **src &gt; main &gt; js &gt; MainAbility &gt; i18n**: resources in different languages, for example, UI strings and image paths.
- **src &gt; main &gt; js &gt; MainAbility &gt; pages**: pages contained in **MainAbility**.
- **src &gt; main &gt; js &gt; MainAbility &gt; app.js**: ability lifecycle file.
- **src &gt; main &gt; resources**: a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files.
- **src &gt; main &gt; config.json**: module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file.
- **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**. - **build-profile.json5**: current module information and build configuration options, including **buildOption** and **targets**.
- **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation. - **hvigorfile.js**: module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5**: application-level configuration information, including the signature and product configuration. - **build-profile.json5**: application-level configuration information, including the signature and product configuration.
- **hvigorfile.js**: application-level compilation and build task script. - **hvigorfile.js**: application-level compilation and build task script.
## Building the First Page ## Building the First Page
1. Use the **Text** component. 1. Use the **\<Text>** component.
After the project synchronization is complete, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility** &gt; **pages** &gt; **index** in the **Project** window and open the **index.hml** file. You can see that the file contains a **&lt;Text&gt;** component. The sample code in the **index.hml** file is shown below:
After the project synchronization is complete, choose **entry** > **src** > **main** > **js** > **MainAbility** > **pages** > **index** in the **Project** window and open the **index.hml** file. You can see that the file contains a **<Text>** component. The sample code in the **index.hml** file is shown below:
```html ```html
<!--index.hml--> <!-- index.hml -->
<div class="container"> <div class="container">
<text class="title"> <text class="title">
Hello World Hello World
...@@ -51,11 +64,11 @@ ...@@ -51,11 +64,11 @@
2. Add a button and bind the **onclick** method to this button. 2. Add a button and bind the **onclick** method to this button.
On the default page, add an **&lt;input&gt;** component of the button type to respond to user clicks and implement redirection to another page. The sample code in the **index.hml** file is shown below: On the default page, add a **\<Button>** component to respond to user clicks and implement redirection to another page. The sample code in the **index.hml** file is shown below:
```html ```html
<!--index.hml--> <!-- index.hml -->
<div class="container"> <div class="container">
<text class="title"> <text class="title">
Hello World Hello World
...@@ -68,10 +81,11 @@ ...@@ -68,10 +81,11 @@
3. Set the page style in the **index.css** file. 3. Set the page style in the **index.css** file.
From the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility** &gt; **pages** &gt; **index**, open the **index.css** file, and set the page styles, such as the width, height, font size, and spacing. The sample code in the **index.css** file is shown below: From the **Project** window, choose **entry** > **src** > **main** > **js** > **MainAbility** > **pages** > **index**, open the **index.css** file, and set the page styles, such as the width, height, font size, and spacing. The sample code in the **index.css** file is shown below:
```css ```css
/* index.css */
.container { .container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -101,28 +115,26 @@ ...@@ -101,28 +115,26 @@
} }
``` ```
4. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. 4. On the toolbar in the upper right corner of the editing window, click **Previewer**. Below is how the first page looks in the Previewer.
Below is how the first page looks on the Previewer. ![en-us_image_0000001311494592](figures/en-us_image_0000001311494592.png)
![en-us_image_0000001216084724](figures/en-us_image_0000001216084724.png)
## Building the Second Page ## Building the Second Page
1. Create the second page. 1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Page**, name the page **second**, and click **Finish**. Below, you can see the structure of the **second** folder.
![en-us_image_0000001223877210](figures/en-us_image_0000001223877210.png) In the **Project** window, choose **entry** > **src** > **main** > **js** > **MainAbility**, right-click the **pages** folder, choose **New** > **Page**, name the page **second**, and click **Finish**. Below is the structure of the **second** folder.
2. Add **&lt;Text&gt;** and **&lt;Button&gt;** components. ![en-us_image_0000001311334944](figures/en-us_image_0000001311334944.png)
Add **&lt;Text&gt;** and **&lt;Button&gt;** components and set their styles, as you do for the first page. The sample code in the **second.hml** file is shown below: 2. Add **\<Text>** and **\<Button>** components.
Add **\<Text>** and **\<Button>** components and set their styles, as you do for the first page. The sample code in the **second.hml** file is shown below:
```html ```html
<!--second.hml--> <!-- second.hml -->
<div class="container"> <div class="container">
<text class="title"> <text class="title">
Hi there Hi there
...@@ -133,9 +145,10 @@ ...@@ -133,9 +145,10 @@
</div> </div>
``` ```
3. Set the page style in the **second.css** file. The sample code in the **second.css** file is shown below: 3. Set the page style. The sample code in the **second.css** file is shown below:
```css ```css
/* second.css */
.container { .container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
...@@ -171,10 +184,10 @@ ...@@ -171,10 +184,10 @@
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page. 1. Implement redirection from the first page to the second page.
In the **index.js** file of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. The sample code in the **index.js** file is shown below:
In the **index.js** file of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. The sample code in the **index.js** file is shown below:
```js ```js
// index.js // index.js
import router from '@ohos.router'; import router from '@ohos.router';
...@@ -192,7 +205,7 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin ...@@ -192,7 +205,7 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin
In the **second.ets** file of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.js** file is shown below: In the **second.ets** file of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.js** file is shown below:
```js ```js
// second.js // second.js
import router from '@ohos.router'; import router from '@ohos.router';
...@@ -204,21 +217,21 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin ...@@ -204,21 +217,21 @@ You can implement page redirection through the [page router](../ui/ui-js-buildin
} }
``` ```
3. Open any file in the **index** folder and click ![en-us_image_0000001262339067](figures/en-us_image_0000001262339067.png) in the Previewer to refresh the file. The figure below shows the effect. 3. Open any file in the **index** folder and click ![en-us_image_0000001364174013](figures/en-us_image_0000001364174013.png) in the Previewer to refresh the file. The display effect is shown in the figure below.
![en-us_image_0000001216269940](figures/en-us_image_0000001216269940.png) ![en-us_image_0000001311175132](figures/en-us_image_0000001311175132.png)
## Running the Application on a Real Device ## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below. 2. Choose **File** > **Project Structure...** > **Project** > **Signing Configs**, and select **Automatically generate signing**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![en-us_image_0000001223557290](figures/en-us_image_0000001223557290.png) ![06](figures/06.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001217047316](figures/en-us_image_0000001217047316.png). The display effect is shown in the figure below. 3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001311494604](figures/en-us_image_0000001311494604.png). The display effect is shown in the figure below.
![en-us_image_0000001217527892](figures/en-us_image_0000001217527892.png) ![en-us_image_0000001363934589](figures/en-us_image_0000001363934589.png)
Congratulations! You have finished developing your OpenHarmony application in JavaScript in the traditional coding approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md) Congratulations! You have finished developing your OpenHarmony application in JavaScript in the FA model. To learn more about OpenHarmony application development, see [Application Development Overview](../application-dev-guide.md).
# Getting Started with JavaScript in the Low-Code Approach
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>This feature will be available in DevEco Studio V2.2 Beta1 and later versions.
>
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) for your development.
On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features.
You can develop applications or services in the low-code approach using either of the following methods:
- Create a project that supports low-code development. This method is used as an example in this topic.
- In an existing project, create a Visual file for development. For details, see [Creating a .visual File That Supports Low-Code Development](#building-the-second-page).
## Creating a Project That Supports Low-Code Development
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>This feature is available in DevEco Studio 3.0 Beta2 and later versions and works with compileSdkVersion 7 or later.
>
1. In DevEco Studio, if no project is open, click **Create Project**; if a project is already open, choose **File** &gt; **New** &gt; **Create Project**. Then, select **Empty Ability** and click **Next**.
![en-us_image_0000001268198893](figures/en-us_image_0000001268198893.png)
2. Go to the project configuration page, select **Enable Super Visual**, set **UI Syntax** to **JS**, and retain the default values for other parameters.
![en-us_image_0000001223717294](figures/en-us_image_0000001223717294.png)
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## Low-code Project Files
After the project synchronization is complete, a low-code directory structure is automatically generated in the project, as shown below.
![en-us_image_0000001223558810](figures/en-us_image_0000001223558810.png)
- **entry &gt; src &gt; main &gt; js &gt; MainAbility &gt; pages &gt; index &gt; index.js**: defines logical relationships, such as data and events, used on low-code pages. For details, see [JavaScript](../ui/js-framework-syntax-js.md). If multiple low-code development pages are created, a page folder and the corresponding **.js** file will be created for each of these pages.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>To avoid build errors when using the low-code development page, make sure the directory where the corresponding **.js** file is located does not contain **.hml** or **.css** files. For example, in the preceding example, no **.hml** or **.css** file is allowed in **js** &gt; **MainAbility** &gt; **pages** &gt; **index**.
>
- **entry &gt; src &gt; main &gt; supervisual &gt; MainAbility &gt; pages &gt; index &gt; index.visual**: stores the data model of the low-code development page. You can double-click the file to open the low-code development page. If multiple low-code development pages are created, a page folder and the corresponding **.visual** file will be created for each of these pages.
## Building the First Page
After the project synchronization is complete, the default first page contains the **Div** and **Text** (**Hello World**) components. To better understand low-code development, we'll delete these template components from the canvas and set the page from scratch.
Add **Div**, **Text**, and **Button** components to the first page.
1. Delete the existing template components from the canvas.<a name= delete_origin_content></a>
Open the index.visual file, right-click the existing template components on the canvas, and choose **Delete** from the shortcut menu to delete them. Below is an illustration of the operations.
![en-us_image_0000001216600980](figures/en-us_image_0000001216600980.gif)
2. Add a **Div** component and set its styles and attributes.<a name = add_container></a>
Drag the **Div** component from the **UI Control** area to the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001260226691](figures/en-us_image_0000001260226691.png)**General** and set **Height** to **100%** so that the component fills the entire screen. Click ![en-us_image_0000001215226858](figures/en-us_image_0000001215226858.png)**Flex**, set **FlexDirection** to **column** so that the main axis of the component is vertical, and set both **JustifyContent** and **AlignItems** to **center** so that the child components of the **Div** component are centered along the main axis and cross axis. Below is an illustration of the operations.
![en-us_image_0000001216448880](figures/en-us_image_0000001216448880.gif)
3. Add a **Text** component.
Drag the **Text** component from the **UI Control** area to the center area of the **Div** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215066868](figures/en-us_image_0000001215066868.png)**Properties** and set **Content** of the **Text** component to **Hello World**. Click ![en-us_image_0000001215386842](figures/en-us_image_0000001215386842.png)**Feature**, and set **FontSize** to **60px** and **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001216446670](figures/en-us_image_0000001216446670.gif)
4. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to a position under the **Text** component on the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001260106745](figures/en-us_image_0000001260106745.png)**Properties** and set **Value** of the **Button** component to **Next**. Click ![en-us_image_0000001259866741](figures/en-us_image_0000001259866741.png)**Feature** and set **FontSize** to **40px**. Then, select the **Button** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001260928361](figures/en-us_image_0000001260928361.gif)
5. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer.
Below is how the first page looks on the Previewer.
![en-us_image_0000001216288558](figures/en-us_image_0000001216288558.png)
## Building the Second Page
1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **JS Visual**, as shown below, name the page **second**, and click **Finish**.
<img src="figures/en-us_image_202206250937.png" alt="create-newVisual" style="zoom: 67%;" />
Below, you can see the structure of the **pages** folder.
![en-us_image_0000001223882030](figures/en-us_image_0000001223882030.png)
2. [Delete the existing template components from the canvas.](#delete_origin_content)
3. [Add a Div component and set its styles and attributes.](#add_container)
4. Add a **Text** component.
Drag the **Text** component from the **UI Control** area to the center area of the **Div** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001260227453](figures/en-us_image_0000001260227453.png)**Properties** and set **Content** of the **Text** component to **Hi there**. Click ![en-us_image_0000001260107497](figures/en-us_image_0000001260107497.png)**Feature**, and set **FontSize** to **60px** and **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001216614132](figures/en-us_image_0000001216614132.gif)
5. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to a position under the **Text** component on the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001215227618](figures/en-us_image_0000001215227618.png)**Properties** and set **Value** of the **Button** component to **Back**. Click ![en-us_image_0000001259987441](figures/en-us_image_0000001259987441.png)**Feature** and set **FontSize** to **40px**. Then, select the **Button** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001261017331](figures/en-us_image_0000001261017331.gif)
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the files of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. This operation needs to be completed in both .js and .visual files.
- In the **index.js** file:
```js
import router from '@ohos.router';
export default {
onclick() {
router.push({
url:'pages/second/second', // Specify the page to be redirected to.
})
}
}
```
- In the index.visual file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215388136](figures/en-us_image_0000001215388136.png)**Events** and set **Click** to **onclick**.
![en-us_image_0000001223722586](figures/en-us_image_0000001223722586.png)
2. Implement redirection from the second page to the first page.
In the files of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page.
This operation needs to be completed in both .js and .visual files.
- In the **second.js** file:
```js
import router from '@ohos.router';
export default {
back() {
router.back()
}
}
```
- In the **second.visual** file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215388262](figures/en-us_image_0000001215388262.png)**Events** and set **Click** to **back**.
![en-us_image_0000001268082945](figures/en-us_image_0000001268082945.png)
3. Open the **index.visual** or **index.js** file and click ![en-us_image_0000001261979271](figures/en-us_image_0000001261979271.png) in the Previewer to refresh the file. The figure below shows the effect.
![en-us_image_0000001261142799](figures/en-us_image_0000001261142799.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below.
![en-us_image_0000001268283201](figures/en-us_image_0000001268283201.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001262207811](figures/en-us_image_0000001262207811.png). The display effect is shown in the figure below.
![en-us_image_0000001262127855](figures/en-us_image_0000001262127855.png)
Congratulations! You have finished developing your OpenHarmony app in JavaScript in the low-code approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md)
...@@ -4,17 +4,15 @@ ...@@ -4,17 +4,15 @@
### System Capabilities and APIs ### System Capabilities and APIs
SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association. SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association.
![image-20220326064841782](figures/image-20220326064841782.png) ![image-20220326064841782](figures/image-20220326064841782.png)
### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set ### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed.
The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development. The associated SysCap set covers the system capabilities of associated APIs that DevEco Studio offers during application development.
![image-20220326064913834](figures/image-20220326064913834.png) ![image-20220326064913834](figures/image-20220326064913834.png)
...@@ -31,7 +29,7 @@ The SDK classifies devices into general devices and custom devices. The general ...@@ -31,7 +29,7 @@ The SDK classifies devices into general devices and custom devices. The general
### Mapping Between Devices and SDK Capabilities ### Mapping Between Devices and SDK Capabilities
The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input). The SDK provides a full set of APIs for DevEco Studio. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
![image-20220326065043006](figures/image-20220326065043006.png) ![image-20220326065043006](figures/image-20220326065043006.png)
...@@ -39,6 +37,12 @@ The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the su ...@@ -39,6 +37,12 @@ The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the su
## How to Develop ## How to Develop
### Obtaining the PCID
The Product Compatibility ID (PCID) contains the SysCap information supported by the current device. For the moment, you can obtain the PCID of a device from the device vendor. In the future, you'll be able to obtain the PCIDs of all devices from the authentication center, which is in development.
### Importing the PCID ### Importing the PCID
DevEco Studio allows Product Compatibility ID (PCID) imports for projects. After the imported PCID file is decoded, the SysCap is output and written into the **syscap.json** file. DevEco Studio allows Product Compatibility ID (PCID) imports for projects. After the imported PCID file is decoded, the SysCap is output and written into the **syscap.json** file.
...@@ -55,34 +59,30 @@ DevEco Studio automatically configures the associated SysCap set and required Sy ...@@ -55,34 +59,30 @@ DevEco Studio automatically configures the associated SysCap set and required Sy
You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them.
Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device.
``` ```json
/* syscap.json */ /* syscap.json */
{ {
devices: { "devices": {
general: [ /* General devices. Each general device supports a SysCap set. Multiple general devices can be configured. */ "general": [ /* General devices. Each general device supports a SysCap set. Multiple general devices can be configured. */
"default", "default",
"car, "car"
...
], ],
custom: [ /* Custom devices. */ "custom": [ /* Custom devices. */
{ {
"Custom device": [ "Custom device": [
"SystemCapability.Communication.SoftBus.Core", "SystemCapability.Communication.SoftBus.Core"
...
] ]
}, }
...
] ]
}, },
development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ "development": { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */
addedSysCaps: [ "addedSysCaps": [
"SystemCapability.Location.Location.Lite", "SystemCapability.Location.Location.Lite"
...
] ]
}, },
production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ "production": { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */
addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. "addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set.
removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. "removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device.
} }
} }
``` ```
...@@ -113,7 +113,7 @@ Use **canIUse** if you want to check whether a project supports a specific SysCa ...@@ -113,7 +113,7 @@ Use **canIUse** if you want to check whether a project supports a specific SysCa
if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) { if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) {
console.log("This application supports SystemCapability.ArkUI.ArkUI.Full."); console.log("This application supports SystemCapability.ArkUI.ArkUI.Full.");
} else { } else {
Console.log("This application does not support SystemCapability.ArkUI.ArkUI.Full".); console.log("This application does not support SystemCapability.ArkUI.ArkUI.Full".);
} }
``` ```
...@@ -127,7 +127,7 @@ if (geolocation) { ...@@ -127,7 +127,7 @@ if (geolocation) {
console.log(location.latitude, location.longitude); console.log(location.latitude, location.longitude);
}); });
} else { } else {
Console.log('This device does not support location information.'); console.log('This device does not support location information.');
} }
``` ```
...@@ -144,7 +144,7 @@ const authenticator = userAuth.getAuthenticator(); ...@@ -144,7 +144,7 @@ const authenticator = userAuth.getAuthenticator();
const result = authenticator.checkAbility('FACE_ONLY', 'S1'); const result = authenticator.checkAbility('FACE_ONLY', 'S1');
if (result == authenticator.CheckAvailabilityResult.AUTH_NOT_SUPPORT) { if (result == authenticator.CheckAvailabilityResult.AUTH_NOT_SUPPORT) {
Console.log('This device does not support facial recognition.'); console.log('This device does not support facial recognition.');
} }
// If an unsupported API is forcibly called, an error message is returned, but no syntax error occurs. // If an unsupported API is forcibly called, an error message is returned, but no syntax error occurs.
authenticator.execute('FACE_ONLY', 'S1', (err, result) => { authenticator.execute('FACE_ONLY', 'S1', (err, result) => {
......
# Development References # Development References
- [Component Reference(TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [Component Reference(JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [APIs](apis/Readme-EN.md) - [JS and TS APIs](apis/Readme-EN.md)
- Native APIs
- [JS (eTS Included) APIs](apis/Readme-EN.md) - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md)
- Native APIs
- [Standard Library](native-lib/third_party_libc/musl.md)
- [Node_API](native-lib/third_party_napi/napi.md)
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
- [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md)
- [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md)
- [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md)
- [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md)
- application/[AbilityContext](js-apis-ability-context.md) - application/[AbilityContext](js-apis-ability-context.md)
- application/[ApplicationContext](js-apis-application-applicationContext.md) - application/[ApplicationContext](js-apis-application-applicationContext.md)
- application/[AbilityStageContext](js-apis-abilitystagecontext.md) - application/[AbilityStageContext](js-apis-abilitystagecontext.md)
...@@ -33,10 +34,13 @@ ...@@ -33,10 +34,13 @@
- [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md)
- [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md)
- [@ohos.application.abilityManager](js-apis-application-abilityManager.md) - [@ohos.application.abilityManager](js-apis-application-abilityManager.md)
- [@ohos.application.AccessibilityExtensionAbility](js-apis-accessibility-extension-context.md)
- [@ohos.application.AccessibilityExtensionAbility](js-apis-application-AccessibilityExtensionAbility.md)
- [@ohos.application.appManager](js-apis-appmanager.md) - [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md) - [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
- [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md) - [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md)
- [@ohos.application.errorManager](js-apis-errorManager.md)
- [@ohos.application.formBindingData](js-apis-formbindingdata.md) - [@ohos.application.formBindingData](js-apis-formbindingdata.md)
- [@ohos.application.formError](js-apis-formerror.md) - [@ohos.application.formError](js-apis-formerror.md)
- [@ohos.application.formHost](js-apis-formhost.md) - [@ohos.application.formHost](js-apis-formhost.md)
...@@ -68,18 +72,25 @@ ...@@ -68,18 +72,25 @@
- [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md)
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md)
- [@ohos.zlib](js-apis-zlib.md) - [@ohos.zlib](js-apis-zlib.md)
- bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md)
- bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)
- bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md)
- bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md)
- bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md)
- bundle/[DispatchInfo](js-apis-dispatchInfo.md)
- bundle/[ElementName](js-apis-bundle-ElementName.md) - bundle/[ElementName](js-apis-bundle-ElementName.md)
- bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) - bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)
- bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)
- bundle/[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)
- bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[Metadata](js-apis-bundle-Metadata.md)
- bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md)
- bundle/[PermissionDef](js-apis-bundle-PermissionDef.md)
- bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)
- bundle/[ShortcutInfo](js-apis-bundle-ShortcutInfo.md)
- UI Page - UI Page
- [@ohos.animator](js-apis-animator.md) - [@ohos.animator](js-apis-animator.md)
...@@ -90,6 +101,7 @@ ...@@ -90,6 +101,7 @@
- Graphics - Graphics
- [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md)
- [@ohos.display ](js-apis-display.md) - [@ohos.display ](js-apis-display.md)
- [@ohos.effectKit](js-apis-effectKit.md) - [@ohos.effectKit](js-apis-effectKit.md)
- [@ohos.screen](js-apis-screen.md) - [@ohos.screen](js-apis-screen.md)
...@@ -115,6 +127,7 @@ ...@@ -115,6 +127,7 @@
- Resource Scheduling - Resource Scheduling
- [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md)
- [@ohos.distributedMissionManager](js-apis-distributedMissionManager.md)
- [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.workScheduler ](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
......
# innerBundleManager
The **innerBundleManager** module manages internal bundles.
> **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.
## Modules to Import
```
import innerBundleManager from '@ohos.bundle.innerBundleManager';
```
## System Capability
SystemCapability.BundleManager.BundleFramework
## Required Permissions
| Permission | Permission Level | Description |
| ------------------------------------------ | ------------ | ---------------------------- |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications. |
| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant | Permission to listen for application changes.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
## innerBundleManager.getLauncherAbilityInfos
getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback&lt;Array&lt;LauncherAbilityInfo&gt;&gt;) : void;
Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| bundleName | string | Yes | Bundle name of an application. |
| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.|
| callback | AsyncCallback\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Yes | Callback used to return an array of the launcher ability information. |
## innerBundleManager.getLauncherAbilityInfos
getLauncherAbilityInfos(bundleName: string, userId: number) : Promise&lt;Array&lt;LauncherAbilityInfo&gt;&gt;
Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------ | ---- | ----------------------------------------------------- |
| bundleName | string | Yes | Bundle name of an application. |
| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ------------------------- |
| Promise\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Promise used to return an array of the launcher ability information.|
## innerBundleManager.on
on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback&lt;string&gt;) : void;
Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.LISTEN_BUNDLE_CHANGE
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------------------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. |
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.on
on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback): Promise&lt;string&gt;
Registers a callback to receive bundle status changes. This API uses a promise to return the result.
**Required permissions**
ohos.permission.LISTEN_BUNDLE_CHANGE
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------------------- | -------------------- | ---- | ------------------ |
| type | "BundleStatusChange" | Yes | Event type. |
| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.|
**Return value**
| Type | Description |
| --------------- | ----------------------------------- |
| Promise\<string> | Promise used to return a successful result or error information.|
## innerBundleManager.off
off(type:"BundleStatusChange", callback: AsyncCallback&lt;string&gt;) : void;
Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.LISTEN_BUNDLE_CHANGE
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ---------------------------------------------------- |
| type | "BundleStatusChange" | Yes | Event type. |
| callback | AsyncCallback\<string> | Yes | Callback used to return a successful result or error information.|
## innerBundleManager.off
off(type:"BundleStatusChange"): Promise&lt;string&gt;
Deregisters the callback that receives bundle status changes. This API uses a promise to return the result.
**Required permissions**
ohos.permission.LISTEN_BUNDLE_CHANGE
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type | Mandatory| Description |
| ---- | -------------------- | ---- | ---------------- |
| type | "BundleStatusChange" | Yes | Event type.|
**Return value**
| Type | Description |
| --------------- | ----------------------------------- |
| Promise\<string> | Promise used to return a successful result or error information.|
## innerBundleManager.getAllLauncherAbilityInfos
getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback&lt;Array&lt;LauncherAbilityInfo&gt;&gt;) : void;
Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- |
| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.|
| callback | AsyncCallback\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Yes | Callback used to return an array of the launcher ability information. |
## innerBundleManager.getAllLauncherAbilityInfos
getAllLauncherAbilityInfos(userId: number) : Promise&lt;Array&lt;LauncherAbilityInfo&gt;&gt;
Obtains the information about all launcher abilities. This API uses a promise to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ----------------------------------------------------- |
| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ------------------------- |
| Promise\<Array<[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md)>> | Promise used to return an array of the launcher ability information.|
## innerBundleManager.getShortcutInfos
getShortcutInfos(bundleName :string, callback: AsyncCallback&lt;Array&lt;ShortcutInfo&gt;&gt;) : void;
Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- |
| bundleName | string | Yes | Bundle name of an application. |
| callback | AsyncCallback\<Array<[ShortcutInfo](js-apis-bundle-ShortcutInfo.md)>> | Yes | Callback used to return an array of the shortcut information.|
## innerBundleManager.getShortcutInfos
getShortcutInfos(bundleName : string) : Promise&lt;Array&lt;ShortcutInfo&gt;&gt;
Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.BundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------ | ---- | ------------------------ |
| bundleName | string | Yes | Bundle name of an application.|
**Return value**
| Type | Description |
| -------------------------------------------------------- | ----------------------------- |
| Promise\<Array<[ShortcutInfo](js-apis-bundle-ShortcutInfo.md)>> | Promise used to return an array of the shortcut information.|
# distributedBundle
The **distributedBundle** module manages distributed bundles.
> **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.
## Modules to Import
```
import distributedBundle from '@ohos.distributedBundle';
```
## System Capability
SystemCapability.BundleManager.DistributedBundleFramework
## Required Permissions
| Permission | Permission Level | Description |
| ------------------------------------------ | ------------ | ------------------ |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.|
For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels).
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback&lt;RemoteAbilityInfo&gt;): void;
Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.DistributedBundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. |
| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Yes | Callback used to return the remote ability information.|
## distributedBundle.getRemoteAbilityInfo
getRemoteAbilityInfo(elementName: ElementName): Promise&lt;RemoteAbilityInfo&gt;
Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.DistributedBundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | -------------------------------------------- | ---- | ----------------------- |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise used to return the remote ability information.|
## distributedBundle.getRemoteAbilityInfos
getRemoteAbilityInfos(elementNames: Array&lt;ElementName&gt;, callback: AsyncCallback&lt;Array&lt;RemoteAbilityInfo&gt;&gt;): void;
Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.DistributedBundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- |
| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. |
| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.|
## distributedBundle.getRemoteAbilityInfos
getRemoteAbilityInfos(elementNames: Array&lt;ElementName&gt;): Promise&lt;Array&lt;RemoteAbilityInfo&gt;&gt;
Obtains information about remote abilities that match the given element names. This API uses a promise to return the result.
**Required permissions**
ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**System capability**
SystemCapability.BundleManager.DistributedBundleFramework
**System API**
This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | --------------------------------------------------- | ---- | ----------------------- |
| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10.|
**Return value**
| Type | Description |
| ------------------------------------------------------------ | --------------------------------- |
| Promise\<Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Promise used to return an array of the remote ability information.|
# Work Scheduler Callbacks # Work Scheduler Callbacks
> **NOTE**<br/> The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks.
> The initial APIs of this module are supported since API version 9. API version 9 is a canary version for trial use. The APIs of this version may be unstable.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
> **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 can be used only in the stage model.
## Modules to Import ## Modules to Import
``` ```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
``` ```
...@@ -20,13 +26,13 @@ Triggered when the Work Scheduler task starts. ...@@ -20,13 +26,13 @@ Triggered when the Work Scheduler task starts.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- | | ---- | ---------------------------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | Yes | Task to be added to the execution queue.| | work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | Yes | Target task. |
**Example** **Example**
``` ```ts
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) { onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo)); console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
...@@ -44,14 +50,14 @@ Triggered when the Work Scheduler task stops. ...@@ -44,14 +50,14 @@ Triggered when the Work Scheduler task stops.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- | | ---- | ---------------------------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | Yes | Task to be added to the execution queue.| | work | [workScheduler.WorkInfo](js-apis-workScheduler.md#workinfo) | Yes | Target task. |
**Example** **Example**
``` ```ts
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility { export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
onWorkStop(workInfo) { onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo)); console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
......
# wantConstant # wantConstant
The **wantConstant** module provides the action, entity, and flags used in **Want** objects. The **wantConstant** module provides the actions, entities, and flags used in **Want** objects.
> **NOTE** > **NOTE**
> >
...@@ -23,15 +23,15 @@ Enumerates the action constants of the **Want** object. ...@@ -23,15 +23,15 @@ Enumerates the action constants of the **Want** object.
| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | | ACTION_HOME | ohos.want.action.home | Action of returning to the home page. |
| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | | ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. |
| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | | ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. |
| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides radio network settings, for example, Wi-Fi option. | | ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. |
| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | | ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. |
| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | | ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. |
| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | | ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. |
| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all clock alarms. | | ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. |
| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | | ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. |
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. |
| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS. | | ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. |
| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | | ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. | | ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. |
| ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | | ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. |
......
...@@ -49,7 +49,7 @@ Checks whether an application has been granted the specified permission. This AP ...@@ -49,7 +49,7 @@ Checks whether an application has been granted the specified permission. This AP
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------- | ---- | ------------------------------------------ | | -------- | ------------------- | ---- | ------------------------------------------ |
| tokenID | number | Yes | ID of the application. | | tokenID | number | Yes | ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). |
| permissionName | string | Yes | Name of the permission to verify.| | permissionName | string | Yes | Name of the permission to verify.|
**Return value** **Return value**
...@@ -105,7 +105,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -105,7 +105,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
Grants a user granted permission to an application. This API uses a promise to return the result. Grants a user granted permission to an application. This API uses a promise to return the result.
This is a system API and cannot be called by third-party applications. This is a system API.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
...@@ -143,7 +143,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl ...@@ -143,7 +143,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. Grants a user granted permission to an application. This API uses an asynchronous callback to return the result.
This is a system API and cannot be called by third-party applications. This is a system API.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
...@@ -179,7 +179,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -179,7 +179,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
Revokes a user granted permission given to an application. This API uses a promise to return the result. Revokes a user granted permission given to an application. This API uses a promise to return the result.
This is a system API and cannot be called by third-party applications. This is a system API.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
...@@ -217,7 +217,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF ...@@ -217,7 +217,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result.
This is a system API and cannot be called by third-party applications. This is a system API.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
...@@ -253,7 +253,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g ...@@ -253,7 +253,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise&lt;number&g
Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. Obtains the flags of the specified permission of a given application. This API uses a promise to return the result.
This is a system API and cannot be called by third-party applications. This is a system API.
**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, ohos.permission.GRANT_SENSITIVE_PERMISSIONS, or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS **Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, ohos.permission.GRANT_SENSITIVE_PERMISSIONS, or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
......
# AccessibilityExtensionContext
The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities.
You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures.
> **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 can be used only in the stage model.
## Modules to Import
```js
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'
```
## FocusDirection
Enumerates the focus directions.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| -------- | ------- |
| up | Search for the next focusable item above the current item in focus.|
| down | Search for the next focusable item below the current item in focus.|
| left | Search for the next focusable item on the left of the current item in focus.|
| right | Search for the next focusable item on the right the current item in focus.|
| forward | Search for the next focusable item before the current item in focus.|
| backward | Search for the next focusable item after the current item in focus.|
## FocusType
Enumerates of the focus types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| ------------- | ----------- |
| accessibility | Accessibility focus.|
| normal | Normal focus. |
## Rect
Defines a rectangle.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Readable | Writable | Description |
| ------ | ------ | ---- | ---- | --------- |
| left | number | Yes | No | Left boundary of the rectangle.|
| top | number | Yes | No | Top boundary of the rectangle.|
| width | number | Yes | No | Width of the rectangle. |
| height | number | Yes | No | Height of the rectangle. |
## WindowType
Enumerates the window types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Description |
| ----------- | --------- |
| application | Application window.|
| system | System window.|
## AccessibilityExtensionContext.setEventTypeFilter
setEventTypeFilter(type: Array<accessibility.EventType>): Promise\<boolean>;
Sets the concerned event type.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------- |
| type | Array&lt;[EventType](js-apis-accessibility.md#EventType)&gt; | Yes | Event type.|
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```ts
this.context.setEventTypeFilter(['click', 'longClick']);
```
## AccessibilityExtensionContext.setTargetBundleName
setTargetBundleName(targetNames: Array\<string>): Promise\<boolean>;
Sets the concerned target bundle.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------- | ---- | -------- |
| targetNames | Array&lt;string&gt; | Yes | Name of the target bundle.|
**Return value**
| Type | Description |
| ---------------------- | --------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```ts
this.context.setTargetBundleName(['com.ohos.mms']);
```
## AccessibilityExtensionContext.getFocusElement
getFocusElement(isAccessibilityFocus?: boolean): Promise\<AccessibilityElement>;
Obtains the focus element.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------------------- | ------- | ---- | ------------------- |
| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is false.|
**Return value**
| Type | Description |
| ----------------------------------- | ---------------------- |
| Promise&lt;AccessibilityElement&gt; | Promise used to return the current focus element.|
**Example**
```ts
this.context.getFocusElement().then(focusElement => {
console.log("AxExtensionAbility getFocusElement success");
})
```
## AccessibilityExtensionContext.getWindowRootElement
getWindowRootElement(windowId?: number): Promise\<AccessibilityElement>;
Obtains the root element of a window.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | --------------------------- |
| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.|
**Return value**
| Type | Description |
| ----------------------------------- | ----------------------- |
| Promise&lt;AccessibilityElement&gt; | Promise used to return the root element.|
**Example**
```ts
this.context.getWindowRootElement().then(rootElement => {
console.log("AxExtensionAbility getWindowRootElement success");
})
```
## AccessibilityExtensionContext.getWindows
getWindows(displayId?: number): Promise<Array\<AccessibilityElement>>;
Obtains the list of windows visible to users.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ------------------------- |
| displayId | number | No | Screen from which the window information is obtained. If this parameter is not specified, it indicates the default home screen.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------------------------ |
| Promise&lt;Array&lt;AccessibilityElement&gt;&gt; | Promise used to return the window list. |
**Example**
```ts
this.context.getWindows().then(windows => {
console.log("AxExtensionAbility getWindows success");
})
```
## AccessibilityExtensionContext.gestureInject
gestureInject(gesturePath: GesturePath, listener: Callback\<boolean>): Promise\<boolean
Injects a gesture.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | -------------- |
| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. |
| listener | Callback&lt;boolean&gt; | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ---------------------- | ---------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```ts
let gesturePath = new GesturePath(100);
for (let i = 0; i < 10; i++) {
let gesturePoint = new GesturePosition(100, i * 200);
gesturePath.positions.push(gesturePoint);
}
this.context.gestureInject(gesturePath, (result) => {
console.info('gestureInject result: ' + result);
})
```
...@@ -23,23 +23,94 @@ import Want from '@ohos.application.Want'; ...@@ -23,23 +23,94 @@ import Want from '@ohos.application.Want';
| abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.|
| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.|
| type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. |
| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| | flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).|
| action | Read only | string | No | Action option. | | action | Read only | string | No | Action option. |
| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.js) module can be used to obtain application and bundle information. | | parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:<br>**ohos.aafwk.callerPid**: PID of the caller.<br>**ohos.aafwk.param.callerToken**: token of the caller.<br>**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.md) module can be used to obtain application and bundle information. |
| entities | Read only | Array\<string> | No | List of entities. | | entities | Read only | Array\<string> | No | List of entities. |
| moduleName<sup>9+</sup> | Read only | string | No | Module to which the ability belongs.| | moduleName<sup>9+</sup> | Read only | string | No | Module to which the ability belongs.|
**Example** **Example**
``` js - Basic usage
var want = {
"deviceId": "", // An empty deviceId indicates the local device. ``` js
"bundleName": "com.extreme.test", var want = {
"abilityName": "MainAbility", "deviceId": "", // An empty deviceId indicates the local device.
"moduleName": "entry" // moduleName is optional. "bundleName": "com.extreme.test",
}; "abilityName": "MainAbility",
this.context.startAbility(want, (error) => { "moduleName": "entry" // moduleName is optional.
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters uniquely identify an ability. };
console.log("error.code = " + error.code) this.context.startAbility(want, (error) => {
}) // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
``` console.log("error.code = " + error.code)
})
```
- Passing a file descriptor (FD)
``` js
var fd;
try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
} catch(e) {
console.log("openSync fail:" + JSON.stringify(e));
}
var want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional.
"parameters": {
"keyFd":{"type":"FD", "value":fd}
}
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
- Passing **RemoteObject** data
``` js
class Stub extends rpc.RemoteObject {
constructor(des) {
if (typeof des == 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
if (code === 1) {
console.log('onRemoteRequest called')
let token = data.readInterfaceToken();
let num = data.readInt();
this.method();
return true;
}
return false;
}
method() {
console.log('method called');
}
}
var remoteObject = new Stub('want-test');
var want = {
"deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test",
"abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional.
"parameters": {
"keyRemoteObject":{"type":"RemoteObject", "value":remoteObject}
}
};
this.context.startAbility(want, (error) => {
// Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability.
console.log("error.code = " + error.code)
})
```
<!--no_check-->
\ No newline at end of file
# ElementName # ElementName
The **ElementName** module provides the element name information.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. 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 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Provides the element name information.
## ElementName ## ElementName
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- | | ----------------------- | ---------| ---- | ---- | ------------------------- |
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册