提交 5beb0457 编写于 作者: K king_he 提交者: Gitee

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

# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>
<option name="testRunner" value="PLATFORM" />
<option name="distributionType" value="LOCAL" />
<option name="externalProjectPath" value="$PROJECT_DIR$" />
<option name="gradleHome" value="C:\Program Files\Huawei\DevEco Studio 3.0.0.800\tools\gradle" />
<option name="gradleJvm" value="#JAVA_INTERNAL" />
<option name="resolveModulePerSourceSet" value="false" />
<option name="useQualifiedModuleNames" value="false" />
</GradleProjectSettings>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/docs.iml" filepath="$PROJECT_DIR$/.idea/docs.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
......@@ -218,6 +218,11 @@ zh-cn/application-dev/reference/apis/js-apis-huks.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-useriam-userauth.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-system-cipher.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-data-ability.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-dataShare.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-distributed-data.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-distributedobject.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang
......
......@@ -4,7 +4,7 @@
This document provides guidance on building the Docker image for mini- and small-system devices.
The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.huaweicloud.com/authui/login.html?service=https%3A%2F%2Fconsole.huaweicloud.com%2Fswr%2F%3Fregion%3Dcn-south-1%26cloud_route_state%3D%2Fapp%2Fwarehouse%2FwarehouseMangeDetail%2Fgoldensir%2Fopenharmony-docker%2Fopenharmony-docker%3Ftype%3DownImage&locale=en-us#/login). Using the Docker image will help simplify environment configurations needed for the building. The following table lists container-based options needed for building in the standalone Docker environment.
The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.huaweicloud.com/authui/login.html?service=https%3A%2F%2Fconsole.huaweicloud.com%2Fswr%2F%3Fregion%3Dcn-south-1%26cloud_route_state%3D%2Fapp%2Fwarehouse%2FwarehouseMangeDetail%2Fgoldensir%2Fopenharmony-docker%2Fopenharmony-docker%3Ftype%3DownImage&locale=en-us#/login). Using the Docker image will help simplify environment configurations needed for the building. The following table lists container-based options needed for building in the standalone [Docker environment](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/gettools-acquire.md).
| Docker Image Repository | Tag | Description |
| :----------------------------------------------------------- | :------ | :-------------------------------------------------------- |
......
......@@ -3,7 +3,7 @@
## IDL Overview
To ensure successful communications between the client and server, interfaces recognized by both parties must be defined. The OpenHarmony Interface Definition Language (IDL) is a tool for defining such interfaces. OpenHarmony IDL decomposes objects to be transferred into primitives that can be understood by the operating system and encapsulates cross-boundary objects based on developers' requirements.
**Figure 1** IDL interface description
**Figure 1** IDL interface description
![IDL-interface-description](./figures/IDL-interface-description.png)
......@@ -29,16 +29,16 @@ IDL has the following advantages:
#### Primitive Type
| IDL Primitive Type| C++ Primitive Type| TS Primitive Type|
| -------- | -------- | -------- |
|void | void | void |
|boolean | bool | boolean |
|byte | int8_t | number |
|short | int16_t | number |
|int | int32_t | number |
|long | int64_t | number |
|float | float | number |
|double | double | number |
|String | std::string | string |
| -------- | -------- | -------- |
|void | void | void |
|boolean | bool | boolean |
|byte | int8_t | number |
|short | int16_t | number |
|int | int32_t | number |
|long | int64_t | number |
|float | float | number |
|double | double | number |
|String | std::string | string |
The preceding table lists the primitive types supported by IDL and the mappings to the C++ and TS primitive types.
......@@ -47,29 +47,34 @@ The sequenceable type is declared using the keyword **sequenceable**. This type
In C++, the declaration is placed in the file header in the format of **sequenceable includedir..namespace.typename**. It can be in any of the following forms:
```
```cpp
sequenceable includedir..namespace.typename
sequenceable includedir...typename
sequenceable namespace.typename
```
In the preceding information, **includedir** indicates the directory where the header file of the type is located, and the dot (.) is used as the separator. **namespace** indicates the namespace where the type is located, and the dot (.) is used as the separator. **typename** indicates the data type, which can contain only English characters. **includedir** and **namespace** are separated by two dots (..). If the declaration statement does not contain two dots, all characters except the last typename will be parsed as a namespace. Example:
```
```cpp
sequenceable a.b..C.D
```
The preceding statement is parsed into the following code in the C++ header file:
```
```cpp
#include "a/b/d.h"
using C::D;
```
In TS, the declaration is placed in the file header in the format of **sequenceable namespace.typename;**. It can be in the following form:
```
```ts
sequenceable idl.MySequenceable
```
In the preceding information, **namespace** indicates the namespace to which the data type belongs, **typename** indicates the data type name, and **MySequenceable** indicates that data can be passed during IPC using **Parcel** objects. The sequenceable type is not defined in the IDL file, but in the .ts file. Therefore, IDL adds the following statement to the generated .ts file based on the declaration:
```
```ts
import MySequenceable from "./my_sequenceable"
```
......@@ -80,19 +85,19 @@ The interface type refers to interfaces defined in IDL files. The interfaces def
The declaration form in C++ is similar to that of the sequenceable type. The declaration form is as follows:
```
```cpp
interface includedir..namespace.typename
```
In TS, the declaration form is as follows:
```
```ts
interface namespace.interfacename
```
In the preceding information, **namespace** indicates the namespace to which the interface belongs, and **interfacename** indicates the name of the interface. For example, **interface OHOS.IIdlTestObserver;** declares the **IIdlTestObserver** interface defined in another IDL file. This interface can be used as the parameter type or return value type of a method in the current file. IDL adds the following statement to the generated .ts file based on the statement:
```
```ts
import IIdlTestObserver from "./i_idl_test_observer"
```
......@@ -100,9 +105,9 @@ import IIdlTestObserver from "./i_idl_test_observer"
The array type is represented by T[], where **T** can be the primitive, sequenceable, interface, or array type. In C++, this type is generated as **std::vector&lt;T&gt;**.
The table below lists the mappings between the IDL array type and TS and C++ data types.
|IDL Data Type | C++ Data Type | TS Data Type |
| -------- | -------- | -------- |
|T[] | std::vector&lt;T&gt; | T[] |
|IDL Data Type | C++ Data Type | TS Data Type |
| ------- | -------- | -------- |
|T[] | std::vector&lt;T&gt; | T[] |
#### Container Type
IDL supports two container types: List and Map. The List container is represented in the format of **List&lt;T&gt;**. The Map container is represented in the format of **Map<KT,VT>**, where **T**, **KT**, and **VT** can be of the primitive, sequenceable, interface, array, or container type.
......@@ -114,26 +119,32 @@ In TS, the List container type is not supported, and the Map container type is g
The table below lists the mappings between the IDL container type and TS and C++ data types.
|IDL Data Type | C++ Data Type | TS Data Type |
| -------- | -------- | -------- |
|List&lt;T&gt; | std::list | Not supported|
|Map<KT,VT> | std::map | Map |
| -------- | -------- | ------- |
|List&lt;T&gt; | std::list | Not supported |
|Map<KT,VT> | std::map | Map |
### Specifications for Compiling IDL Files
Only one interface type can be defined in an IDL file, and the interface name must be the same as the file name. The interface definition of the IDL file is described in Backus-Naur form (BNF). The basic definition format is as follows:
```
[<*interface_attr_declaration*>]interface<*interface_name_with_namespace*>{<*method_declaration*>}
```
In the preceding information, <*interface_attr_declaration*> declares interface attributes. Currently, only the **oneway** attribute is supported, indicating that all methods in the interface are unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. The interface name must contain the complete interface header file directory, namespace, and method declaration. Empty interfaces are not allowed.
The method declaration format in the interface is as follows:
```
[<*method_attr_declaration*>]<*result_type*><*method_declaration*>
```
In the preceding information, <*method_attr_declaration*> describes the interface attributes. Currently, only the **oneway** attribute is supported, indicating that the method is unidirectional. Such a method returns value without waiting for the execution to complete. This attribute is optional. If this attribute is not set, synchronous call is used. <*result_type*> indicates the type of the return value, and <*method_declaration*> indicates the method name and parameter declaration.
The parameter declaration format is as follows:
```
[<*formal_param_attr*>]<*type*><*identifier*>
```
The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicating that the parameter is an input parameter, an output parameter, or both an input and an output parameter, respectively. A **oneway** method does not allow **output** or **inout** parameters or return values.
## How to Develop
......@@ -144,20 +155,20 @@ The value of <*formal_param_attr*> can be **in**, **out**, or **inout**, indicat
You can use C++ to create IDL files. An example IDL file is as follows:
```
```cpp
interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data);
}
```
You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, for **IIdlTestService.idl**, the generated files are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**.
You can run the **./idl -gen-cpp -d dir -c dir/iTest.idl** command (**-d** indicates the output directory) to generate the interface file, stub file, and proxy file in the **dir** directory in the execution environment. The names of the generated interface class files are the same as that of the IDL file, except that the file name extensions are **.h** and **.cpp**. For example, the files generated for **IIdlTestService.idl** are **i_idl_test_service.h**, **idl_test_service_proxy.h**, **idl_test_service_stub.h**, **idl_test_service_proxy.cpp**, and **idl_test_service_stub.cpp**.
#### Exposing Interfaces on the Server
The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file.
```
```cpp
#ifndef OHOS_IDLTESTSERVICESTUB_H
#define OHOS_IDLTESTSERVICESTUB_H
#include <iremote_stub.h>
......@@ -182,7 +193,7 @@ private:
You need to inherit the interface class defined in the IDL file and implement the methods in the class. In addition, you need to register the defined services with SAMGR during service initialization. In the following code snippet, **TestService** inherits the **IdlTestServiceStub** interface class and implements the **TestIntTransaction** and **TestStringTransaction** methods.
```
```cpp
#ifndef OHOS_IPC_TEST_SERVICE_H
#define OHOS_IPC_TEST_SERVICE_H
......@@ -207,7 +218,7 @@ private:
The sample code for registering a service is as follows:
```
```cpp
#include "test_service.h"
#include <string_ex.h>
......@@ -259,12 +270,11 @@ ErrCode TestService::TestStringTransaction(const std::string &data)
} // namespace OHOS
```
#### Calling Methods from the Client for IPC
The C++ client obtains the service proxy defined in the system through SAMGR and then invokes the interface provided by the proxy. The sample code is as follows:
```
```cpp
#include "test_client.h"
#include "if_system_ability_manager.h"
......@@ -316,16 +326,13 @@ void TestClient::StartStringTransaction()
} // namespace OHOS
```
### Development Using TS
#### Creating an IDL File
You can use TS to create IDL files. An example IDL file is as follows:
```
```ts
interface OHOS.IIdlTestService {
int TestIntTransaction([in] int data);
void TestStringTransaction([in] String data);
......@@ -338,7 +345,7 @@ Run the **./idl -c IIdlTestService.idl -gen-ts -d /data/ts/** command (**-d** in
The stub class generated by IDL is an abstract implementation of the interface class and declares all methods in the IDL file.
```
```ts
import {testIntTransactionCallback} from "./i_idl_test_service";
import {testStringTransactionCallback} from "./i_idl_test_service";
import IIdlTestService from "./i_idl_test_service";
......@@ -387,7 +394,7 @@ export default class IdlTestServiceStub extends rpc.RemoteObject implements IIdl
You need to inherit the interface class defined in the IDL file and implement the methods in the class. The following code snippet shows how to inherit the **IdlTestServiceStub** interface class and implement the **testIntTransaction** and **testStringTransaction** methods.
```
```ts
import {testIntTransactionCallback} from "./i_idl_test_service"
import {testStringTransactionCallback} from "./i_idl_test_service"
import IdlTestServiceStub from "./idl_test_service_stub"
......@@ -408,7 +415,7 @@ class IdlTestImp extends IdlTestServiceStub {
After the service implements the interface, the interface needs to be exposed to the client for connection. If your service needs to expose this interface, extend **Ability** and implement **onConnect()** to return **IRemoteObject** so that the client can interact with the service process. The following code snippet shows how to expose the **IRemoteAbility** interface to the client:
```
```ts
export default {
onStart() {
console.info('ServiceAbility onStart');
......@@ -442,7 +449,7 @@ export default {
When the client calls **connectAbility()** to connect to a Service ability, the **onConnect** callback in **onAbilityConnectDone** of the client receives the **IRemoteObject** instance returned by the **onConnect()** method of the Service ability. The client and Service ability are in different applications. Therefore, the directory of the client application must contain a copy of the .idl file (the SDK automatically generates the proxy class). The **onConnect** callback then uses the **IRemoteObject** instance to create the **testProxy** instance of the **IdlTestServiceProxy** class and calls the related IPC method. The sample code is as follows:
```
```ts
import IdlTestServiceProxy from './idl_test_service_proxy'
import featureAbility from '@ohos.ability.featureAbility';
......@@ -495,7 +502,7 @@ To create a class that supports the sequenceable type, perform the following ope
The following is an example of the **MySequenceable** class code:
```
```ts
import rpc from '@ohos.rpc';
export default class MySequenceable {
constructor(num: number, str: string) {
......@@ -523,8 +530,6 @@ export default class MySequenceable {
}
```
## How to Develop for Interworking Between C++ and TS
### TS Proxy and C++ Stub Development
......@@ -535,7 +540,7 @@ export default class MySequenceable {
2. Create a service object, inherit the interface class defined in the C++ stub file, and implement the methods in the class. An example is as follows:
```
```cpp
class IdlTestServiceImpl : public IdlTestServiceStub {
public:
IdlTestServiceImpl() = default;
......@@ -558,7 +563,7 @@ export default class MySequenceable {
C++ provides C++ service objects to TS in the format of native APIs. For example, C++ provides a **GetNativeObject** method, which is used to create an **IdlTestServiceImpl** instance. Using the **NAPI_ohos_rpc_CreateJsRemoteObject** method, you can create a JS remote object for the TS application.
```
```cpp
NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info)
{
sptr<IdlTestServiceImpl> impl = new IdlTestServiceImpl();
......@@ -572,8 +577,7 @@ NativeValue* GetNativeObject(NativeEngine& engine, NativeCallbackInfo& info)
Use TS to construct an IDL file and run commands to generate interfaces, stub files, and proxy files. An example proxy file is as follows:
```
```ts
import {testIntTransactionCallback} from "./i_idl_test_service";
import {testStringTransactionCallback} from "./i_idl_test_service";
import IIdlTestService from "./i_idl_test_service";
......@@ -634,7 +638,7 @@ export default class IdlTestServiceProxy implements IIdlTestService {
2. Construct a TS proxy and transfers the remote C++ service object to it.
3. Use the TS proxy to call the method declared in the IDL file to implement the interworking between the TS proxy and C++ stub. The following is an example:
```
```ts
import IdlTestServiceProxy from './idl_test_service_proxy'
import nativeMgr from 'nativeManager';
......
......@@ -65,18 +65,18 @@ The ability assistant enables you to start applications, atomic services, and te
- **dump**
Prints ability related information.
Prints ability-related information.
| Name | Level-2 Parameter | Description |
| ----------------- | -------------------- | ------------------------------------------------------------ |
| -h/--help | - | Prints help information. |
| -a/--all | - | Prints ability information in all missions. |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>NORMAL <br>DEFAULT_STANDARD<br>DEFAULT_SINGLE<br>LAUNCHER |
| -l/--mission-list | type (All logs are printed if this parameter is left unspecified.)| Prints mission stack information.<br>The following values are available for **type**:<br>- NORMAL <br>- DEFAULT_STANDARD<br>- DEFAULT_SINGLE<br>- LAUNCHER |
| -e/--extension | elementName | Prints extended component information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**.|
| -d/--data | | Prints Data ability information. |
| -u/--userId | UserId | Prints stack information of a specified user ID. This parameter must be used together with other parameters. <br/>Example commands: aa **dump -a -u 100** and **aa dump -d -u 100**. |
| -d/--data | - | Prints Data ability information. |
| -i/--ability | AbilityRecord ID | Prints detailed information about a specified ability. |
| -c/--client | | Prints detailed ability information. This parameter must be used together with other parameters. Example commands: **aa dump -a -c** and **aa dump -i 21 -c**.|
| -c/--client | - | Prints detailed ability information. This parameter must be used together with other parameters. <br/>Example commands: **aa dump -a -c** and **aa dump -i 21 -c**. |
**Method**
......
......@@ -13,7 +13,7 @@ The stage model is designed to make it easier to develop complex applications in
| -------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| Development mode | Web-like APIs are provided. The UI development is the same as that of the stage model. | Object-oriented development mode is provided. The UI development is the same as that of the FA model. |
| Engine instance | Each ability in a process exclusively uses a JS VM engine instance. | Multiple abilities in a process share one JS VM engine instance. |
| Intra-process object sharing| Not supported | Supported |
| Intra-process object sharing| Not supported. | Supported. |
| Bundle description file | The `config.json` file is used to describe the HAP and component information. Each component must use a fixed file name.| The `module.json` file is used to describe the HAP and component information. The entry file name can be specified.|
| Component | Four types of components are provided: Page ability (used for UI page display), Service ability (used to provide services), Data ability (used for data sharing), and Form ability (used to provide widgets).| Two types of components are provided: Ability (used for UI page display) and Extension (scenario-based service extension). |
......
......@@ -6,12 +6,13 @@
The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model.
- FA Model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- Stage Model
- FA model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- Stage model
The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model).
![contextIntroduction](figures/contextIntroduction.png)
......@@ -45,6 +46,34 @@ export default {
}
```
### Common Context-related Methods in the FA Model
The following context-related methods are available in the FA model:
```javascript
setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback<void>): void
setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise<void>;
```
The methods are used to set the display orientation of the current ability.
**Example**
```javascript
import featureAbility from '@ohos.ability.featureAbility'
import bundle from '../@ohos.bundle';
export default {
onCreate() {
// Obtain the context and call related APIs.
let context = featureAbility.getContext();
context.setDisplayOrientation(bundle.DisplayOrientation.LANDSCAPE).then(() => {
console.log("Set display orientation.")
})
console.info('Application onCreate')
},
onDestroy() {
console.info('Application onDestroy')
},
}
```
## Context in the Stage Model
The following describes the contexts provided by the stage model in detail.
......
......@@ -10,25 +10,26 @@ Basic concepts:
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> **NOTE**
>
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
The widget provider controls the widget content to display, component layout, and click events bound to components.
## Scenario
## Development Overview
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations:
In FA widget development, you need to carry out the following operations as a widget provider based on the [Feature Ability (FA) model](fa-brief.md).
- Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** instance.
- Update a widget through **FormProvider**.
- Develop the widget UI page.
- Develop the widget UI pages.
## Available APIs
The table below describes the lifecycle callbacks provided **LifecycleForm**.
The table below describes the lifecycle callbacks provided in **LifecycleForm**.
**Table 1** LifecycleForm APIs
......@@ -37,7 +38,7 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**.
| onCreate(want: Want): formBindingData.FormBindingData | Called to notify the widget provider that a **Form** instance (widget) has been created. |
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change in widget visibility. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. |
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. |
......@@ -73,7 +74,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default {
onCreate(want) {
console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as during widget instance retrieval or update.
// Persistently store widget information for subsequent use, such as widget instance retrieval or update.
let obj = {
"title": "titleOnCreate",
"detail": "detailOnCreate"
......@@ -120,7 +121,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
Configure the **config.json** file for the widget.
- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows:
- The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal structure is described as follows:
| Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ |
......@@ -144,7 +145,7 @@ Configure the **config.json** file for the widget.
}]
```
- The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal field structure is described as follows:
- The **abilities** module in the **config.json** file corresponds to the **LifecycleForm** of the widget. The internal structure is described as follows:
| Field | Description | Data Type | Default |
| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ |
......@@ -195,7 +196,7 @@ Configure the **config.json** file for the widget.
```
### Persistently Store Widget Data
### Persistently Storing Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
......@@ -206,7 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formId = want.parameters["ohos.extra.param.key.form_identity"];
let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// Persistently store widget information for subsequent use, such as widget instance retrieval or update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples".
storeFormInfo(formId, formName, tempFlag, want);
......@@ -233,21 +234,43 @@ You should override **onDestroy** to delete widget data.
For details about the persistence method, see [Lightweight Data Store Development](../database/database-preference-guidelines.md).
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
Note that the **Want** passed by the widget host to the widget provider contains a flag that indicates whether the requested widget is a temporary one.
- Normal widget: a widget that will be persistently used by the widget host
- Temporary widget: a widget that is temporarily used by the widget host
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
### Developing the Widget UI Page
### Updating Widget Data
When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The code snippet is as follows:
```javascript
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
"detail": "detailOnUpdate"
};
let formData = formBindingData.createFormBindingData(obj);
// Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
formProvider.updateForm(formId, formData).catch((error) => {
console.log('FormAbility updateForm, error:' + JSON.stringify(error));
});
}
```
### Developing Widget UI Pages
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **NOTE**
>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- HML:
- In the HML file:
```html
<div class="container">
<stack>
......@@ -262,7 +285,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
</div>
```
- CSS:
- In the CSS file:
```css
.container {
......@@ -303,7 +326,7 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
}
```
- JSON:
- In the JSON file:
```json
{
"data": {
......
......@@ -37,6 +37,8 @@ You can override the lifecycle callbacks provided by the Page ability in the **a
The ability supports two launch types: singleton and multi-instance.
You can specify the launch type by setting **launchType** in the **config.json** file.
**Table 1** Introduction to startup mode
| Launch Type | Description |Description |
| ----------- | ------- |---------------- |
| standard | Multi-instance | A new instance is started each time an ability starts.|
......@@ -48,7 +50,7 @@ By default, **singleton** is used.
## Development Guidelines
### Available APIs
**Table 1** APIs provided by featureAbility
**Table 2** APIs provided by featureAbility
| API | Description |
| --------------------------------------------------- | --------------- |
......@@ -86,8 +88,10 @@ By default, **singleton** is used.
);
```
### Starting a Remote Page Ability (Applying only to System Applications)
>Note: The **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications. Therefore, remote Page ability startup applies only to system applications.
### Starting a Remote Page Ability
>Note
>
>This feature applies only to system applications, since the **getTrustedDeviceListSync** API of the **DeviceManager** class is open only to system applications.
**Modules to Import**
......@@ -176,7 +180,7 @@ In the cross-device scenario, the application must also apply for the data synch
### Lifecycle APIs
**Table 2** Lifecycle callbacks
**Table 3** Lifecycle callbacks
| API | Description |
| ------------ | ------------------------------------------------------------ |
......
......@@ -238,7 +238,7 @@ You can use either of the following methods to connect to a Service ability:
}
```
### Connecting to a Remote Service Ability (Applying only to System Applications)
### Connecting to a Remote Service Ability
>**NOTE**
>
......
# Ability Development
## When to Use
Unlike the FA model, the [stage model](stage-brief.md) requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop abilities based on the stage model, implement the following logic:
- Create abilities for an application that involves screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
Ability development in the [stage model](stage-brief.md) is significantly different from that in the FA model. The stage model requires you to declare the application package structure in the `module.json` and `app.json` files during application development. For details about the configuration file, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). To develop an ability based on the stage model, implement the following logic:
- Create an ability that supports screen viewing and human-machine interaction. You must implement the following scenarios: ability lifecycle callbacks, obtaining ability configuration, requesting permissions, and notifying environment changes.
- Start an ability. You need to implement ability startup on the same device, on a remote device, or with a specified UI page.
- Call abilities. For details, see [Call Development](stage-call.md).
- Connect to and disconnect from a Service Extension ability. For details, see [Service Extension Ability Development](stage-serviceextension.md).
- Continue the ability on another device. For details, see [Ability Continuation Development](stage-ability-continuation.md).
### Launch Type
The ability supports three launch types: singleton, multi-instance, and instance-specific. Each launch type, specified by `launchType` in the `module.json` file, specifies the action that can be performed when the ability is started.
An ability can be launched in the **standard**, **singleton**, or **specified** mode, as configured by `launchType` in the `module.json` file. Depending on the launch type, the action performed when the ability is started differs, as described below.
| Launch Type | Description |Description |
| Launch Type | Description |Action |
| ----------- | ------- |---------------- |
| standard | Multi-instance | A new instance is started each time an ability starts.|
| singleton | Singleton | Only one instance exists in the system. If an instance already exists when an ability is started, that instance is reused.|
| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.|
| specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.|
By default, the singleton mode is used. The following is an example of the `module.json` file:
......@@ -78,29 +78,29 @@ To create Page abilities for an application in the stage model, you must impleme
onCreate(want, launchParam) {
console.log("MainAbility onCreate")
}
onDestroy() {
console.log("MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.log("MainAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data) => {
console.log("MainAbility load content succeed with data: " + JSON.stringify(data))
}).catch((error) => {
console.error("MainAbility load content failed with error: " + JSON.stringify(error))
})
}
onWindowStageDestroy() {
console.log("MainAbility onWindowStageDestroy")
}
onForeground() {
console.log("MainAbility onForeground")
}
onBackground() {
console.log("MainAbility onBackground")
}
......@@ -145,9 +145,9 @@ export default class MainAbility extends Ability {
}
```
### Requesting Permissions
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permissions for calendar access as an example.
If an application needs to obtain user privacy information or use system capabilities, for example, obtaining location information or using the camera to take photos or record videos, it must request the respective permission from consumers. During application development, you need to specify the involved sensitive permissions, declare the required permissions in `module.json`, and use the `requestPermissionsFromUser` API to request the permission from consumers in the form of a dialog box. The following uses the permission for calendar access as an example.
Declare the required permissions in the `module.json` file.
Declare the required permission in the `module.json` file.
```json
"requestPermissions": [
{
......@@ -155,7 +155,7 @@ Declare the required permissions in the `module.json` file.
}
]
```
Request the permissions from consumers in the form of a dialog box:
Request the permission from consumers in the form of a dialog box:
```ts
let context = this.context
let permissions: Array<string> = ['ohos.permission.READ_CALENDAR']
......@@ -166,11 +166,11 @@ context.requestPermissionsFromUser(permissions).then((data) => {
})
```
### Notifying of Environment Changes
Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by the configuration item in **Settings** or the icon in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md).
Environment changes include changes of global configurations and ability configurations. Currently, the global configurations include the system language and color mode. The change of global configurations is generally triggered by configuration items in **Settings** or icons in **Control Panel**. The ability configuration is specific to a single `Ability` instance, including the display ID, screen resolution, and screen orientation. The configuration is related to the display where the ability is located, and the change is generally triggered by the window. For details on the configuration, see [Configuration](../reference/apis/js-apis-configuration.md).
For an application in the stage model, when the configuration changes, its abilities are not restarted, but the `onConfigurationUpdated(config: Configuration)` callback is triggered. If the application needs to perform processing based on the change, you can overwrite `onConfigurationUpdated`. Note that the `Configuration` object in the callback contains all the configurations of the current ability, not only the changed configurations.
The following example shows the implement of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed.
The following example shows the implementation of the `onConfigurationUpdated` callback in the `AbilityStage` class. The callback is triggered when the system language and color mode are changed.
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
......@@ -184,7 +184,7 @@ export default class MyAbilityStage extends AbilityStage {
}
```
The following example shows the implement of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change.
The following example shows the implementation of the `onConfigurationUpdated` callback in the `Ability` class. The callback is triggered when the system language, color mode, or display parameters (such as the direction and density) change.
```ts
import Ability from '@ohos.application.Ability'
import ConfigurationConstant from '@ohos.application.ConfigurationConstant'
......@@ -205,7 +205,7 @@ export default class MainAbility extends Ability {
```
## Starting an Ability
### Available APIs
The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes and the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
The `Ability` class has the `context` attribute, which belongs to the `AbilityContext` class. The `AbilityContext` class has the `abilityInfo`, `currentHapModuleInfo`, and other attributes as well as the APIs used for starting abilities. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
**Table 3** AbilityContext APIs
|API|Description|
......@@ -235,9 +235,8 @@ context.startAbility(want).then((data) => {
```
### Starting an Ability on a Remote Device
This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications.
>This feature applies only to system applications, since the `getTrustedDeviceListSync` API of the `DeviceManager` class is open only to system applications.
In the cross-device scenario, you must specify the ID of the remote device. The sample code is as follows:
```ts
let context = this.context
var want = {
......@@ -268,7 +267,7 @@ function getRemoteDeviceId() {
}
}
```
Request the permission `ohos.permission.DISTRIBUTED_DATASYNC ` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions).
Request the permission `ohos.permission.DISTRIBUTED_DATASYNC` from consumers. This permission is used for data synchronization. For details about the sample code for requesting the permission, see [Requesting Permissions](##requesting-permissions).
### Starting an Ability with the Specified Page
If the launch type of an ability is set to `singleton` and the ability has been started, the `onNewWant` callback is triggered when the ability is started again. You can pass start options through the `want`. For example, to start an ability with the specified page, use the `uri` or `parameters` parameter in the `want` to pass the page information. Currently, the ability in the stage model cannot directly use the `router` capability. You must pass the start options to the custom component and invoke the `router` method to display the specified page during the custom component lifecycle management. The sample code is as follows:
......
......@@ -8,7 +8,7 @@ The following figure shows the design ideas of the stage model.
![stagedesign](figures/stagedesign.png)
The stage model is designed based on the following considerations:
The stage model is designed based on the following considerations:
- **Balance between application capabilities and overall system power consumption**
......
......@@ -4,7 +4,7 @@
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts:
......@@ -12,7 +12,8 @@ Basic concepts:
- Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
......@@ -187,7 +188,7 @@ To create a widget in the stage model, implement the lifecycle callbacks of **Fo
{
"forms": [{
"name": "widget",
"description": "This is a service widget.",
"description": "This is a widget.",
"src": "./js/widget/pages/index/index",
"window": {
"autoDesignWidth": true,
......@@ -252,7 +253,28 @@ Note that the **Want** passed by the widget host to the widget provider contains
Data of a temporary widget is not persistently stored. If it is deleted from the Widget Manager due to exceptions, such as crash of the widget framework, the widget provider will not be notified of which widget is deleted, and still keeps the data. In light of this, the widget provider should implement data clearing. If the widget host successfully converts a temporary widget into a normal one, the widget provider should also process the widget ID and store the data persistently. This prevents the widget provider from deleting the widget data when clearing temporary widgets.
### Updating Widget Data
When a widget application initiates a data update upon a scheduled or periodic update, the application obtains the latest data and calls **updateForm** to update the widget. The sample code is as follows:
```javascript
onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate');
let obj = {
"title": "titleOnUpdate",
"detail": "detailOnUpdate"
};
let formData = formBindingData.createFormBindingData(obj);
// Call the updateForm method to update the widget. Only the data passed through the input parameter is updated. Other information remains unchanged.
formProvider.updateForm(formId, formData).catch((error) => {
console.log('FormAbility updateForm, error:' + JSON.stringify(error));
});
}
```
### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
......
# Service Extension Ability Development
## When to Use
**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple, and it does not involve foreground or background. **ServiceExtensionAbility** is extended from **ExtensionAbility**.
**ExtensionAbility** is the base class of the new Extension component in the stage model. It is used to process missions without UIs. The lifecycle of an Extension ability is simple and does not involve foreground or background states. **ServiceExtensionAbility** is extended from **ExtensionAbility**.
You can customize a class that inherits from **ServiceExtensionAbility** and override the lifecycle callbacks in the base class to perform service logic operations during the initialization, connection, and disconnection processes.
## Available APIs
**Table 1** ServiceExtensionAbility lifecycle callbacks
**Table 1** ServiceExtensionAbility lifecycle APIs
|API|Description|
|:------|:------|
|onCreate|Called for the initialization when **startAbility** or **connectAbility** is invoked for a given ability for the first time.|
|onRequest|Called each time **startAbility** is invoked for a given ability. The initial value of **startId** is 1, and the value is incremented by one each time **startAbility** is invoked for that ability.|
|onConnect|Called when **connectAbility** is invoked for a given ability. This callback is not invoked for repeated calling of **connectAbility** for a specific ability. However, it will be invoked when **disconnectAbility** is called to disconnect an ability and then **connectAbility** is called to connect the ability again. The returned result is a **RemoteObject**.|
|onDisconnect|Called when **disconnectAbility** is called for a given ability. If the Extension ability is started by **connectAbility** and is not bound by other applications, the **onDestroy** callback will also be triggered to destroy the Extension ability.|
|onDestroy|Called when **terminateSelf** is invoked to terminate the ability.|
|onCreate(want: Want): void|Called for the initialization when **startAbility** or **connectAbility** is invoked for a given ability for the first time.|
|onRequest(want: Want, startId: number): void|Called each time **startAbility** is invoked for a given ability. The initial value of **startId** is **1**, and the value is incremented by one each time **startAbility** is invoked for that ability.|
|onConnect(want: Want): rpc.RemoteObject|Called when **connectAbility** is invoked for a given ability. This callback is not invoked for repeated calling of **connectAbility** for a specific ability. However, it will be invoked unless **connectAbility** is called after the ability has been disconnected using **disconnectAbility**. The returned result is a **RemoteObject**.|
|onDisconnect(want: Want): void|Called when **disconnectAbility** is called for a given ability. If the Extension ability is started by **connectAbility** and is not bound to other applications, the **onDestroy** callback will also be triggered to destroy the Extension ability.|
|onDestroy(): void|Called when **terminateSelf** is invoked to terminate the ability.|
## Constraints
- Currently, OpenHarmony does not support creation of a Service Extension ability for third-party applications.
OpenHarmony does not support creation of a Service Extension ability for third-party applications.
## How to Develop
1. Create a Service Extension ability.
1. Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**. The following is a configuration example of the **module.json** file:
Customize a class that inherits from **ServiceExtensionAbility** in the .ts file and override the lifecycle callbacks of the base class. The code sample is as follows:
```js
import rpc from '@ohos.rpc'
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
class ServiceExt extends ServiceExtensionAbility {
onCreate(want) {
console.log('onCreate, want:' + want.abilityName);
}
onRequest(want, startId) {
console.log('onRequest, want:' + want.abilityName);
}
onConnect(want) {
console.log('onConnect , want:' + want.abilityName);
return new StubTest("test");
}
onDisconnect(want) {
console.log('onDisconnect, want:' + want.abilityName);
}
onDestroy() {
console.log('onDestroy');
}
}
```
```json
"extensionAbilities":[{
"name": "ServiceExtAbility",
"icon": "$media:icon",
"description": "service",
"type": "service",
"visible": true,
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}]
```
2. Register the Service Extension ability.
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:
Declare the Service Extension ability in the **module.json** file by setting its **type** attribute to **service**.
**module.json configuration example**
```json
"extensionAbilities":[{
"name": "ServiceExtAbility",
"icon": "$media:icon",
"description": "service",
"type": "service",
"visible": true,
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}]
```
## Development Example
The following sample is provided to help you better understand how to develop a Service Extension ability:
- [ServiceExtensionAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility)
```js
import rpc from '@ohos.rpc'
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
This sample shows how to create a Service Extension ability in the **ServiceExtAbility.ts** file in the **ServiceExtensionAbility** directory.
class ServiceExt extends ServiceExtensionAbility {
console.log('onCreate, want:' + want.abilityName);
}
onRequest(want, startId) {
console.log('onRequest, want:' + want.abilityName);
}
onConnect(want) {
console.log('onConnect , want:' + want.abilityName);
return new StubTest("test");
}
onDisconnect(want) {
console.log('onDisconnect, want:' + want.abilityName);
}
onDestroy() {
console.log('onDestroy');
}
}
```
## Samples
The following sample is provided to help you better understand how to develop Service Extension abilities:
- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
......@@ -89,7 +89,7 @@ The RDB provides **RdbPredicates** for you to set database operation conditions.
| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.|
| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.|
| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field: string, value: string): RdbPredicats | Sets the **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.|
| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.|
| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.<br>- **field**: column name in the database table.<br>- **value**: value specified.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.<br>- **field**: column name in the database table.<br>- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.|
......@@ -204,7 +204,7 @@ You can obtain the distributed table name for a remote device based on the local
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db",}
data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE)
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
......
......@@ -13,6 +13,6 @@
- Vibrator
- [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md)
- Update Servcie
- Update Service
- [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md)
......@@ -12,7 +12,7 @@ Real-time location of the device is recommended for location-sensitive services.
The following table describes APIs available for obtaining device location information.
**Table1** APIs for obtaining device location information
**Table 1** APIs for obtaining device location information
| API | Description |
| -------- | -------- |
......@@ -54,7 +54,9 @@ The following table describes APIs available for obtaining device location infor
## How to Develop
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user. For details, see .
To learn more about the APIs for obtaining device location information, see [Geolocation](../reference/apis/js-apis-geolocation.md).
1. Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user. For details, see the following section.
The system provides the following location permissions:
- ohos.permission.LOCATION
......@@ -108,7 +110,7 @@ The following table describes APIs available for obtaining device location infor
```
**Table2** Common use cases of the location function
**Table 2** Common use cases of the location function
| Use&nbsp;Case | Constant | Description |
| -------- | -------- | -------- |
......@@ -139,7 +141,7 @@ The following table describes APIs available for obtaining device location infor
```
**Table3** Location priority policies
**Table 3** Location priority policies
| Policy | Constant | Description |
| -------- | -------- | -------- |
......@@ -174,7 +176,7 @@ The following table describes APIs available for obtaining device location infor
geolocation.off('locationChange', locationChange);
```
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
```
geolocation.getLastLocation((data) => {
......
......@@ -4,7 +4,7 @@ This development guide describes how to use i18n APIs that are not defined in EC
## Obtaining System Language and Region Information
APIs are provided to access the system language and region information.
You can use APIs provided in the following table to obtain the system language and region information.
### Available APIs
......@@ -17,7 +17,7 @@ APIs are provided to access the system language and region information.
| ohos.i18n | isRTL(locale: string): boolean<sup>7+</sup> | Checks whether the locale uses a right-to-left (RTL) language. |
| ohos.i18n | is24HourClock(): boolean<sup>7+</sup> | Checks whether the system uses a 24-hour clock. |
| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. |
| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country. |
| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. |
### How to Develop
......@@ -70,7 +70,7 @@ APIs are provided to access the system language and region information.
```
7. Obtain the localized display of a country.<br>
Call the **getDisplayCountry** method to obtain the localized display of a country. **country** indicates the country to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized.
```
var country = "US";
......@@ -344,14 +344,14 @@ When a text is displayed in more than one line, [BreakIterator](../reference/api
```
var firstPos = breakIterator.first(); // Sets a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end.
// Moves a BreakIterator object forward or backward by a certain number of break points.
var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text.
var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end.
// Move a BreakIterator object forward or backward by a certain number of break points.
// If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward.
// When the object is moved out of the text length range, -1 is returned.
var nextPos = breakIterator.next(-2);
var previousPos = breakIterator.previous(); // Moves a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned.
// Moves a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned.
var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned.
// Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned.
var followingPos = breakIterator.following(10);
```
......
......@@ -26,6 +26,20 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
1. Instantiate a **Locale** object.<br>
Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md) list.
A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-).
- Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese.
- Script: optional. It is represented by a four-letter code as defined in ISO-15924. The first letter is in uppercase, and the remaining three letters are in lowercase. For example, **Hant** represents the traditional Chinese, and **Hans** represents the simplified Chinese.
- Country or region: optional. It is represented by two-letter code as defined in ISO-3166. Both letters are in uppercase. For example, **CN** represents China, and **US** represents the United States.
- Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the Latin numbering system and Chinese calendar system are used. Extensions can also be passed via the second parameter.
| Extended Parameter ID| Description|
| -------- | -------- |
| ca | Calendar algorithm.|
| co | Collation type.|
| hc | Hour cycle.|
| nu | Numbering system.|
| kn | Whether numeric collation is used when sorting or comparing strings.|
| kf | Whether upper case or lower case is considered when sorting or comparing strings.|
```
var locale = "zh-CN";
......@@ -89,7 +103,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
```
2. Format the date and time.<br>
Call the **format** method to format a **Date** object. This method returns a string representing the formatting result.
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
```
Date date = new Date();
......@@ -97,7 +111,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
```
3. Format a period.<br>
Call the **formatRange** method to format a period. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
```
Date startDate = new Date();
......@@ -113,9 +127,9 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
```
## Number Formatting
## Formatting Numbers
Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format a number for a specific locale.
Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for a specific locale.
### Available APIs
......@@ -161,7 +175,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format a number fo
```
## String Sorting
## Sorting Strings
Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting.
......@@ -248,7 +262,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
```
## Formatting Relative Time
## Formatting the Relative Time
Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the relative time for a specific locale.
......
......@@ -56,7 +56,7 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
3. Define the callback `OnSurfaceCreated`. During the creation of a `Surface`, the callback is used to initialize the rendering environment, for example, the `Skia` rendering environment, and write the content to be displayed to `NativeWindow`.
```c++
void OnSufaceCreatedCB(NativeXComponent* component, void* window) {
void OnSurfaceCreatedCB(NativeXComponent* component, void* window) {
// Obtain the width and height of the native window.
uint64_t width_ = 0, height_ = 0;
OH_NativeXComponent_GetXComponentSize(nativeXComponent, window, &width_, &height_);
......@@ -89,8 +89,8 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
// Create Skia Canvas and write the content to the native window.
...
// After the write operation is complete, flush the buffer by using OH_NativeWindwo_NativeWindowFlushBuffer so that the data is displayed on the screen.
Regoin region{nullptr, 0};
// After the write operation is complete, flush the buffer by using OH_NativeWindow_NativeWindowFlushBuffer so that the data is displayed on the screen.
Region region{nullptr, 0};
OH_NativeWindow_NativeWindowFlushBuffer(nativeWindow_, buffer, fenceFd, region)
}
```
......@@ -99,9 +99,9 @@ The following steps describe how to use `OH_NativeXComponent` in OpenHarmony to
```c++
OH_NativeXComponent_Callback &callback_;
callback_->OnSurfaceCreated = OnSufaceCreatedCB;
callback_->OnSurfaceChanged = OnSufaceChangedCB;
callback_->OnSurfaceDestoryed = OnSufaceDestoryedCB;
callback_->OnSurfaceCreated = OnSurfaceCreatedCB;
callback_->OnSurfaceChanged = OnSurfaceChangedCB;
callback_->OnSurfaceDestoryed = OnSurfaceDestoryedCB;
callback_->DispatchTouchEvent = DispatchTouchEventCB;
OH_NativeXComponent_RegisterCallback(nativeXComponent, callback_)
```
......@@ -11,4 +11,4 @@
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [Resource File Categories](basic-resource-file-categories.md)
- [SysCap](syscap.md)
- [HarmonyAppProvision Configuration File](app-provision-structure.md)
# HarmonyAppProvision Configuration File
The **HarmonyAppProvision** configuration file (also called profile) is the file where you declare permission and signature information for your application.
## Configuration File Internal Structure
The **HarmonyAppProvision** file consists of several parts, which are described in the table below.
**Table 1** Configuration file internal structure
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- |
| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No |
| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No|
| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No|
| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) and **release** (for application release). The recommended value is **debug**.| String | Yes | No|
| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No|
| validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No |
| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No |
| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | No |
| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | No |
| debug-info | Additional debug information. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | No |
An example of the **HarmonyAppProvision** file is as follows:
```json
{
"version-code": 1,
"version-name": "1.0.0",
"uuid": "string",
"type": "debug",
"validity": {
"not-before": 1586422743,
"not-after": 1617958743
},
"bundle-info" : {
"developer-id": "OpenHarmony",
"development-certificate": "Base64 string",
"distribution-certificate": "Base64 string",
"bundle-name": "com.OpenHarmony.app.test",
"apl": "normal",
"app-feature": "hos_normal_app"
},
"acls": {
"allowed-acls": ["string"]
},
"permissions": {
"restricted-permissions": ["string"]
},
"debug-info" : {
"device-id-type": "udid",
"device-ids": ["string"]
},
"issuer": "OpenHarmony"
}
```
### Internal Structure of the validity Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ---------- | ------------------------------- | ------- | ------- | --------- |
| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No |
| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No |
### Internal Structure of the bundle-info Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | -------- | --------- |
| developer-id | Unique ID of the developer.| String | Yes | No |
| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No |
| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise | No |
| bundle-name | Bundle name of the application.| String | Yes | No |
| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No |
| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes | No |
### Internal structure of the acls Object
The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 4** Internal structure of the acls object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No |
### Internal Structure of the permissions Object
The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 5** Internal structure of the permissions object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No | No |
### Internal Structure of the debug-info Object
The **debug-info** object contains debug information of your application, mainly device management and control information.
**Table 6** Internal structure of the debug-info object
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No |
| device-ids | IDs of devices on which your application can be debugged.| String array | No | No |
......@@ -15,7 +15,7 @@ You can develop applications or services in the low-code approach using either o
- 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.
- 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
......@@ -52,7 +52,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
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)
![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>
......@@ -62,7 +62,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
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.
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)
......@@ -70,7 +70,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
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)
![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.
......@@ -85,7 +85,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
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)
![en-us_image_0000001233368868](figures/en-us_image_0000001233368868.png)
2. [Delete the existing template components from the canvas.](#delete_origin_content)
......@@ -110,7 +110,7 @@ Add **Column**, **Text**, and **Button** components to the first page. A column
}
}
```
- 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.
- 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)
......
......@@ -13,7 +13,7 @@ You can develop applications or services in the low-code approach using either o
- 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.
- 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
......@@ -53,15 +53,15 @@ 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.
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)
![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)
![en-us_image_0000001216448880](figures/en-us_image_0000001216448880.gif)
3. Add a **Text** component.
......@@ -86,10 +86,14 @@ Open the index.visual file, right-click the existing template components on the
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; **Visual**, name the page **second**, and click **Finish**. Below, you can see the structure of the **pages** folder.
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**.
![en-us_image_0000001223882030](figures/en-us_image_0000001223882030.png)
<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)
......
......@@ -75,6 +75,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
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.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken
......@@ -111,6 +113,8 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl
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.
**Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken
......@@ -145,6 +149,8 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF
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.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken
......@@ -181,6 +187,8 @@ 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.
This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken
......@@ -215,7 +223,9 @@ 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.
**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, GRANT_SENSITIVE_PERMISSIONS, or REVOKE_SENSITIVE_PERMISSIONS
This is a system API and cannot be called by third-party applications.
**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, ohos.permission.GRANT_SENSITIVE_PERMISSIONS, or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
**System capability**: SystemCapability.Security.AccessToken
......
......@@ -320,10 +320,10 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.replaceAllElements((value, index) => {
arrayList.replaceAllElements((value: number, index: number)=> {
return value = 2 * value;
});
arrayList.replaceAllElements((value, index) => {
arrayList.replaceAllElements((value: number, index: number) => {
return value = value - 2;
});
```
......@@ -394,8 +394,8 @@ arrayList.add(2);
arrayList.add(4);
arrayList.add(5);
arrayList.add(4);
arrayList.sort((a, b) => a - b);
arrayList.sort((a, b) => b - a);
arrayList.sort((a: number, b: number) => a - b);
arrayList.sort((a: number, b: number) => b - a);
arrayList.sort();
```
......
......@@ -3063,7 +3063,7 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) {
console.log("Success in reading the buffer data");
}
};
});
```
......
......@@ -128,6 +128,7 @@ Cancels the suspension delay.
**Example**
```js
let id = 1;
backgroundTaskManager.cancelSuspendDelay(id);
```
......@@ -313,14 +314,14 @@ Provides the information about the suspension delay.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
| Name | Value| Description |
| ----------------------- | ------ | ---------------------------- |
| DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | 7 | WLAN-related (reserved). |
| VOIP | 8 | Voice and video call (reserved). |
| TASK_KEEPING | 9 | Computing task (effective only for specific devices).|
| Name | Value| Description |
| ----------------------- | ------ | ------------------------------------------------------------ |
| DATA_TRANSFER | 1 | Data transfer. |
| AUDIO_PLAYBACK | 2 | Audio playback. |
| AUDIO_RECORDING | 3 | Audio recording. |
| LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
| WIFI_INTERACTION | 7 | WLAN-related.<br>This is a system API and cannot be called by third-party applications.|
| VOIP | 8 | Audio and video calls.<br>This is a system API and cannot be called by third-party applications.|
| TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
# Bluetooth
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> **NOTE**<br>
> 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 Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
Provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
## Modules to Import
......@@ -201,7 +201,7 @@ Obtains the connection state of a profile.
| Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- |
| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.|
| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.|
**Return value**
......@@ -212,7 +212,7 @@ Obtains the connection state of a profile.
**Example**
```js
let result = bluetooth.getProfileConnState(PROFILE_A2DP_SOURCE);
let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
```
......@@ -355,7 +355,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de
```js
// The device can be discovered and connected only when the discoverable and connectable mode is used.
let result = bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
```
......@@ -720,7 +720,7 @@ bluetooth.off('stateChange', onReceiveEvent);
```
## bluetooth.sppListen<sup>8+</sup><a name="sppListen<"></a>
## bluetooth.sppListen<sup>8+</sup><a name="sppListen"></a>
sppListen(name: string, option: SppOption, callback: AsyncCallback&lt;number&gt;): void
......@@ -773,6 +773,14 @@ Listens for a connection to be made to this socket from the client and accepts i
**Example**
```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
let clientNumber = -1;
function acceptClientSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
......@@ -807,6 +815,7 @@ Initiates an SPP connection to a remote device from the client.
**Example**
```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
......@@ -838,6 +847,14 @@ Closes the listening socket of the server.
**Example**
```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
bluetooth.sppCloseServerSocket(serverNumber);
```
......@@ -860,6 +877,15 @@ Closes the client socket.
**Example**
```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.sppCloseClientSocket(clientNumber);
```
......@@ -888,6 +914,15 @@ Writes data to the remote device through the socket.
**Example**
```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
let arrayBuffer = new ArrayBuffer(8);
let data = new Uint8Array(arrayBuffer);
data[0] = 123;
......@@ -923,6 +958,15 @@ No value is returned.
**Example**
```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
function dataRead(dataBuffer) {
let data = new Uint8Array(dataBuffer);
console.log('bluetooth data is: ' + data[0]);
......@@ -954,6 +998,15 @@ No value is returned.
**Example**
```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.off('sppRead', clientNumber);
```
......@@ -981,14 +1034,14 @@ Obtains a profile object.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE);
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
```
## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a>
getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile
Obtains the profile object instance based on **ProfileId**. API version 9 is added with **HidHostProfile**.
Obtains a profile instance. **HidHostProfile** is added in API version 9.
**System capability**: SystemCapability.Communication.Bluetooth.Core
......@@ -996,7 +1049,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add
| Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- |
| profileId | [ProfileId](#ProfileId) | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.|
| profileId | [ProfileId](#ProfileId) | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.|
**Return value**
......@@ -1007,7 +1060,7 @@ Obtains the profile object instance based on **ProfileId**. API version 9 is add
**Example**
```js
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST);
let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
```
......@@ -1239,7 +1292,7 @@ No value is returned.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE)
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let retArray = a2dpSrc.getConnectionDevices();
```
......@@ -1257,7 +1310,7 @@ Obtains the connection state of the profile.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1268,7 +1321,7 @@ Obtains the connection state of the profile.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE)
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');
```
......@@ -1277,7 +1330,7 @@ let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX');
Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a>
### connect<sup>8+</sup><a name="a2dp-connect"></a>
connect(device: string): boolean
......@@ -1302,12 +1355,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE)
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX');
```
### disconnect<sup>8+</sup><a name="disconnect"></a>
### disconnect<sup>8+</sup><a name="a2dp-disconnect"></a>
disconnect(device: string): boolean
......@@ -1332,7 +1385,7 @@ Disconnects an A2DP connection.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE);
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX');
```
......@@ -1362,7 +1415,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data));
}
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE);
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
a2dpSrc.on('connectionStateChange', onReceiveEvent);
```
......@@ -1392,7 +1445,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('a2dp state = '+ JSON.stringify(data));
}
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE);
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
a2dpSrc.on('connectionStateChange', onReceiveEvent);
a2dpSrc.off('connectionStateChange', onReceiveEvent);
```
......@@ -1410,7 +1463,7 @@ Obtains the playing state of a device.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1421,7 +1474,7 @@ Obtains the playing state of a device.
**Example**
```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE);
let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
```
......@@ -1431,7 +1484,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a>
### connect<sup>8+</sup><a name="hfp-connect"></a>
connect(device: string): boolean
......@@ -1445,7 +1498,7 @@ Sets up a Hands-free Profile (HFP) connection of a device.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1456,12 +1509,12 @@ Sets up a Hands-free Profile (HFP) connection of a device.
**Example**
```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX');
```
### disconnect<sup>8+</sup><a name="disconnect"></a>
### disconnect<sup>8+</sup><a name="hfp-disconnect"></a>
disconnect(device: string): boolean
......@@ -1475,7 +1528,7 @@ Disconnects the HFP connection of a device.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1486,7 +1539,7 @@ Disconnects the HFP connection of a device.
**Example**
```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX');
```
......@@ -1516,7 +1569,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data));
}
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent);
```
......@@ -1546,7 +1599,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('hfp state = '+ JSON.stringify(data));
}
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
hfpAg.on('connectionStateChange', onReceiveEvent);
hfpAg.off('connectionStateChange', onReceiveEvent);
```
......@@ -1573,7 +1626,7 @@ Connects to the HidHost service of a device.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1584,7 +1637,7 @@ Connects to the HidHost service of a device.
**Example**
```js
let hidHostProfile = bluetooth.getProfile(PROFILE_HID_HOST);
let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX');
```
......@@ -1605,7 +1658,7 @@ Disconnects from the HidHost service of a device.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1616,7 +1669,7 @@ Disconnects from the HidHost service of a device.
**Example**
```js
let hidHostProfile = bluetooth.getProfile(PROFILE_HID_HOST);
let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX');
```
......@@ -1646,7 +1699,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data));
}
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST);
let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
hidHost.on('connectionStateChange', onReceiveEvent);
```
......@@ -1676,7 +1729,7 @@ No value is returned.
function onReceiveEvent(data) {
console.info('hidHost state = '+ JSON.stringify(data));
}
let hidHost = bluetooth.getProfile(PROFILE_HID_HOST);
let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST);
hidHost.on('connectionStateChange', onReceiveEvent);
hidHost.off('connectionStateChange', onReceiveEvent);
```
......@@ -1819,7 +1872,7 @@ cccV[0] = 1;
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptorsN};
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
characteristics[0] = characteristic;
// Create a gattService instance.
......@@ -1911,8 +1964,11 @@ Notifies the connected client device when a characteristic value changes.
**Example**
```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: notifyCcc.characteristicValue, confirm: false};
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false};
let server = bluetooth.BLE.createGattServer();
server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic);
```
......@@ -2138,7 +2194,7 @@ Subscribes to the descriptor read request events.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.|
| callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request from the GATT client. |
| callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request event from the GATT client. |
**Return value**
......@@ -2279,7 +2335,6 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite");
```
### on('connectStateChange')
on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void
......@@ -2488,7 +2543,7 @@ Obtains all services of the remote BLE device. This API uses a promise to return
// Promise
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
let services = device.getServices();
var services = device.getServices();
console.log("bluetooth services size is ", services.length);
for (let i = 0; i < services.length; i++) {
......@@ -2826,8 +2881,11 @@ Sets the function of notifying the GATT client when the characteristic value of
**Example**
```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.setNotifyCharacteristicChanged(notifyCcc, false);
device.setNotifyCharacteristicChanged(characteristic, false);
```
......@@ -3296,11 +3354,19 @@ Defines the scan filter parameters.
**System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Type | Readable | Writable | Description |
| ----------- | ------ | ---- | ---- | ---------------------------------------- |
| deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. |
| name | string | Yes | Yes | Name of the BLE device to filter. |
| serviceUuid | string | Yes | Yes | UUID of the service, for example, **00001888-0000-1000-8000-00805f9b34fb**.|
| Name | Type | Readable| Writable| Description |
| ---------------------------------------- | ----------- | ---- | ---- | ------------------------------------------------------------ |
| deviceId | string | Yes | Yes | Address of the BLE device to filter, for example, XX:XX:XX:XX:XX:XX. |
| name | string | Yes | Yes | Name of the BLE device to filter. |
| serviceUuid | string | Yes | Yes | Service UUID of the device to filter, for example, **00001888-0000-1000-8000-00805f9b34fb**.|
| serviceUuidMask<sup>9+</sup> | string | Yes | Yes | Service UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.|
| serviceSolicitationUuid<sup>9+</sup> | string | Yes | Yes | Service solicitation UUID of the device to filter, for example, **00001888-0000-1000-8000-00805F9B34FB**.|
| serviceSolicitationUuidMask<sup>9+</sup> | string | Yes | Yes | Service solicitation UUID mask of the device to filter, for example, **FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF**.|
| serviceData<sup>9+</sup> | ArrayBuffer | Yes | Yes | Service data of the device to filter, for example, **[0x90, 0x00, 0xF1, 0xF2]**.|
| serviceDataMask<sup>9+</sup> | ArrayBuffer | Yes | Yes | Service data mask of the device to filter, for example, **[0xFF,0xFF,0xFF,0xFF]**.|
| manufacturerId<sup>9+</sup> | number | Yes | Yes | Manufacturer ID of the device to filter, for example, **0x0006**. |
| manufactureData<sup>9+</sup> | ArrayBuffer | Yes | Yes | Manufacturer data of the device to filter, for example, **[0x1F,0x2F,0x3F]**.|
| manufactureDataMask<sup>9+</sup> | ArrayBuffer | Yes | Yes | Manufacturer data mask of the device to filter, for example, **[0xFF, 0xFF, 0xFF]**.|
## ScanOptions
......
# Configuration Policy
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are system APIs and cannot be called by third-party applications.
The configuration policy provides the capability of obtaining the custom configuration directory and file path based on the predefined custom configuration level.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module are system APIs and cannot be called by third-party applications.
## Modules to Import
```
```js
import configPolicy from '@ohos.configPolicy';
```
## getOneCfgFile
getOneCfgFile(relPath: string, callback: AsyncCallback&lt;string&gt;): void
getOneCfgFile(relPath: string, callback: AsyncCallback&lt;string&gt;)
Obtains the path of a configuration file with the specified name and highest priority. This API uses an asynchronous callback to return the result.
For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys-pod/etc/config.xml** (in ascending order of priority), then **/sys-pod/etc/config.xml** is returned.
For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml** (in ascending order of priority), then **/sys_pod/etc/config.xml** is returned.
**System capability**: SystemCapability.Customization.ConfigPolicy
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| relPath | string | Yes| Name of the configuration file.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the path of the configuration file.|
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | --------------------- |
| relPath | string | Yes | Name of the configuration file. |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the path of the configuration file.|
**Example**
```
configPolicy.getOneCfgFile('config.xml', (error, value) => {
```js
configPolicy.getOneCfgFile('etc/config.xml', (error, value) => {
if (error == undefined) {
console.log(value);
console.log("value is " + value);
} else {
console.log(error);
console.log("error occurs "+ error);
}
});
```
......@@ -48,19 +50,19 @@ Obtains the path of a configuration file with the specified name and highest pri
**System capability**: SystemCapability.Customization.ConfigPolicy
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| relPath | string | Yes| Name of the configuration file.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----- |
| relPath | string | Yes | Name of the configuration file.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the path of the configuration file.|
| Type | Description |
| --------------------- | ------------ |
| Promise&lt;string&gt; | Promise used to return the path of the configuration file.|
**Example**
```
configPolicy.getOneCfgFile('config.xml').then(value => {
console.log(value);
```js
configPolicy.getOneCfgFile('etc/config.xml').then(value => {
console.log("value is " + value);
}).catch(error => {
console.log("getOneCfgFile promise " + error);
});
......@@ -69,26 +71,25 @@ Obtains the path of a configuration file with the specified name and highest pri
## getCfgFiles
getCfgFiles(relPath: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
getCfgFiles(relPath: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;)
Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml**
and **/sys-pod/etc/config.xml**, then **/system/etc/config.xml, /sys-pod/etc/config.xml** is returned.
Obtains all configuration files with the specified name and lists them in ascending order of priority. This API uses an asynchronous callback to return the result. For example, if the **config.xml** file is stored in **/system/etc/config.xml** and **/sys_pod/etc/config.xml**, then **/system/etc/config.xml, /sys_pod/etc/config.xml** is returned.
**System capability**: SystemCapability.Customization.ConfigPolicy
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| relPath | string | Yes| Name of the configuration file.|
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes| Callback used to return the file list.|
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ------------- |
| relPath | string | Yes | Name of the configuration file. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the file list.|
**Example**
```
configPolicy.getCfgFiles('config.xml', (error, value) => {
```js
configPolicy.getCfgFiles('etc/config.xml', (error, value) => {
if (error == undefined) {
console.log(value);
console.log("value is " + value);
} else {
console.log(error);
console.log("error occurs "+ error);
}
});
```
......@@ -103,19 +104,19 @@ Obtains all configuration files with the specified name and lists them in ascend
**System capability**: SystemCapability.Customization.ConfigPolicy
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| relPath | string | Yes| Name of the configuration file.|
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ----- |
| relPath | string | Yes | Name of the configuration file.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the file list.|
| Type | Description |
| ---------------------------------- | ---- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the file list.|
**Example**
```
configPolicy.getCfgFiles('config.xml').then(value => {
console.log(value);
```js
configPolicy.getCfgFiles('etc/config.xml').then(value => {
console.log("value is " + value);
}).catch(error => {
console.log("getCfgFiles promise " + error);
});
......@@ -124,24 +125,24 @@ Obtains all configuration files with the specified name and lists them in ascend
## getCfgDirList
getCfgDirList(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
getCfgDirList(callback: AsyncCallback&lt;Array&lt;string&gt;&gt;)
Obtains the configuration level directory list. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Customization.ConfigPolicy
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes| Callback used to return the configuration level directory list.|
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------- |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback used to return the configuration level directory list.|
**Example**
```
```js
configPolicy.getCfgDirList((error, value) => {
if (error == undefined) {
console.log(value);
console.log("value is " + value);
} else {
console.log(error);
console.log("error occurs "+ error);
}
});
```
......@@ -156,14 +157,14 @@ Obtains the configuration level directory list. This API uses a promise to retur
**System capability**: SystemCapability.Customization.ConfigPolicy
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the configuration level directory list.|
| Type | Description |
| ---------------------------------- | -------- |
| Promise&lt;Array&lt;string&gt;&gt; | Promise used to return the configuration level directory list.|
**Example**
```
```js
configPolicy.getCfgDirList().then(value => {
console.log(value);
console.log("value is " + value);
}).catch(error => {
console.log("getCfgDirList promise " + error);
});
......
# Display
Provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays.
> **NOTE**<br/>
> **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.
## Modules to Import
......@@ -139,7 +141,7 @@ Obtains all the display objects.
| Type | Description |
| ----------------------------------------------- | ------------------------------------------------------- |
| Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return an array containing all the display objects.|
| Promise&lt;Array&lt;[Display](#display)&gt;&gt; | Promise used to return all the display objects.|
**Example**
......@@ -163,7 +165,7 @@ Enables listening.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>-&nbsp;**add**: listening for whether a display is added<br>-&nbsp;**remove**: listening for whether a display is removed<br>-&nbsp;**change**: listening for whether a display is changed|
| type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| callback | Callback&lt;number&gt; | Yes| Callback used to return the ID of the display.|
**Example**
......@@ -186,7 +188,7 @@ Disables listening.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Listening type. The available values are as follows:<br>-&nbsp;**add**: listening for whether a display is added<br>-&nbsp;**remove**: listening for whether a display is removed<br>-&nbsp;**change**: listening for whether a display is changed|
| type | string | Yes| Listening type. The available values are as follows:<br>- **add**: listening for whether a display is added<br>- **remove**: listening for whether a display is removed<br>- **change**: listening for whether a display is changed|
| callback | Callback&lt;number&gt; | No| Callback used to return the ID of the display.|
**Example**
......
......@@ -576,13 +576,12 @@ Provides KV store configuration.
Defines the KV store types.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
| Name | Default Value| Description |
| --- | ---- | ----------------------- |
| DEVICE_COLLABORATION | 0 | Device KV store. |
| SINGLE_VERSION | 1 | Single KV store. |
| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. |
| DEVICE_COLLABORATION | 0 | Device KV store. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore |
| SINGLE_VERSION | 1 | Single KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
## SecurityLevel
......
# HiAppEvent
This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> 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.
......
......@@ -23,7 +23,7 @@ Checks whether logs are printable based on the specified service domain, log tag
| Name| Type | Mandatory| Description |
| ------ | --------------------- | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| level | [LogLevel](#loglevel) | Yes | Log level. |
......@@ -67,7 +67,7 @@ DEBUG logs are not recorded in official versions by default. They are available
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......@@ -98,7 +98,7 @@ Prints INFO logs.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......@@ -129,7 +129,7 @@ Prints WARN logs.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......@@ -160,7 +160,7 @@ Prints ERROR logs.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......@@ -191,7 +191,7 @@ Prints FATAL logs.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value as required.|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**. You can define the value within your application as required.|
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| format | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
......
# Distributed Call Chain Tracing
This module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> 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.
......
# Performance Tracing
This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> 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.
......
......@@ -1461,7 +1461,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID.
```
## RelativeTimeFormat<sup>8+</sup>
## TimeZone<sup>8+</sup>
### getID<sup>8+</sup>
......
......@@ -364,10 +364,10 @@ list.add(2);
list.add(4);
list.add(5);
list.add(4);
list.replaceAllElements((value, index) => {
list.replaceAllElements((value: number, index: number) => {
return value = 2 * value;
});
list.replaceAllElements((value, index) => {
list.replaceAllElements((value: number, index: number) => {
return value = value - 2;
});
```
......@@ -439,8 +439,8 @@ list.add(2);
list.add(4);
list.add(5);
list.add(4);
list.sort((a, b) => a - b);
list.sort((a, b) => b - a);
list.sort((a: number, b: number) => a - b);
list.sort((a: number, b: number) => b - a);
```
### getSubList
......@@ -472,9 +472,9 @@ list.add(2);
list.add(4);
list.add(5);
list.add(4);
let result = list.subList(2, 4);
let result1 = list.subList(4, 3);
let result2 = list.subList(2, 6);
let result = list.getSubList(2, 4);
let result1 = list.getSubList(4, 3);
let result2 = list.getSubList(2, 6);
```
### clear
......
......@@ -190,7 +190,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This
**Example**
```js
systemTime.getCurrentTime().then((data) => {
systemTime.getRealActiveTime().then((data) => {
console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to systemTime.getRealActiveTime because ` + JSON.stringify(error));
......
......@@ -11,5 +11,5 @@
- [HUKS Overview](huks-overview.md)
- [HUKS Development](huks-guidelines.md)
- hapsigner
- [hapsigner Overview](hapsigntool-overview.md)
- [hapsigner Guide](hapsigntool-guidelines.md)
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
文件模式从 100755 更改为 100644
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册