提交 ec4bbdb6 编写于 作者: S shawn_he 提交者: Gitee

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

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
# DFX
- Application Event Logging
- [Overview of Application Event Logging](hiappevent-overview.md)
- [Development of Application Event Logging](hiappevent-guidelines.md)
- Performance Tracing
- [Overview of Performance Tracing](hitracemeter-overview.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- Error Management
- [Development of Error Manager](errormanager-guidelines.md)
- [Development of Application Recovery](apprecovery-guidelines.md)
# Development of Application Event Logging
## When to Use
## Introduction
The event logging function helps applications log various information generated during running.
A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage.
## Available APIs
HiAppEvent is a module that provides the event logging function for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of applications.
## Basic Concepts
- **Logging**
Logs changes caused by user operations to provide service data for development, product, and O&M analysis.
## Event Design Specifications
- Event domain: identifies the domain of an event. You are advised to set this parameter to the service module name to differentiate service modules.
- Event name: specifies the name of an event. You are advised to set this parameter to a specific service name to differentiate services.
- Event type: specifies the type of an event. Four event types are supported:
- Behavior event: used to record the daily operation behavior of a user, for example, button click and page redirection.
- Fault event: used to locate and analyze application faults, for example, frame freezing, network disconnection, and call drop.
- Statistical event: used to collect statistics on key application behaviors, for example, usage duration and number of visits.
- Security event: used to record events related to application security, for example, password change and user authorization.
- Event parameter: specifies the parameters of an event. Each event can contain a group of parameters. You are advised to set this parameter to an event attribute or event context to depict the event details.
JS application event logging APIs are provided by the **hiAppEvent** module.
## Available APIs
The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiviewdfx-hiappevent.md).
......@@ -17,33 +34,68 @@ The following table provides only a brief description of related APIs. For detai
| write(AppEventInfo info, AsyncCallback\<void> callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result.|
| write(AppEventInfo info): Promise\<void> | Logs application events in asynchronous mode. This API uses a promise to return the result. |
**Table 2** APIs for event logging configuration
**Table 3** APIs for watcher management
| API | Description |
| ------------------------------------ | ---------------------------------------------------- |
| configure(ConfigOption config): void | Sets the configuration options for application event logging.|
| -------------------------------------------------- | -------------------------------------------- |
| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher to subscribe to expected application events.|
| removeWatcher(Watcher watcher): void | Adds an event watcher to unsubscribe from expected application events.|
**Table 3** APIs for watcher management
## How to Develop
| API | Description |
| -------------------------------------------------- | -------------------- |
| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.|
| removeWatcher(Watcher watcher): void | Removes an event watcher.|
The following example illustrates how to log and subscribe to button click events of users.
**Table 4** APIs for clearing logging data
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **entryability** > **EntryAbility.ts**, and double-click **EntryAbility.ts**. Then, add an event watcher to subscribe to button click events. The complete sample code is as follows:
| API | Description |
| ----------------- | -------------------- |
| clearData(): void | Clears local logging data.|
```js
import hilog from '@ohos.hilog';
import Ability from '@ohos.application.Ability'
import Window from '@ohos.window'
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'
## How to Develop
export default class EntryAbility extends Ability {
onCreate(want, launchParam) {
hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO);
hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate');
hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? '');
hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:' + JSON.stringify(launchParam) ?? '');
The following uses a one-time event watcher as an example to illustrate the development procedure.
hiAppEvent.addWatcher({
// Add a watcher. You can customize the watcher name. The system identifies different watchers based on their names.
name: "watcher1",
// Subscribe to application events you are interested in, for example, button click events.
appEventFilters: [{ domain: "button" }],
// Set the subscription callback trigger condition. In this example, a callback is triggered if one event is logged.
triggerCondition: { row: 1 },
// Implement the subscription callback function to apply custom processing to the event logging data obtained through subscription.
onTrigger: function (curRow, curSize, holder) {
// If the watcher incurs an error while it is working, return a null holder object after recording the error in the log.
if (holder == null) {
hilog.error(0x0000, 'testTag', "HiAppEvent holder is null")
return
}
let eventPkg = null
// Fetch the subscription event package based on the specified threshold (512 KB by default) until all subscription event data is fetched.
// If all subscription event data is fetched, return a null event package object. The subscription callback process is ended.
while ((eventPkg = holder.takeNext()) != null) {
// Apply custom processing to the event logging data in the event package, for example, print the event logging data in the log.
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.packageId=%{public}d`, eventPkg.packageId)
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.row=%{public}d`, eventPkg.row)
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.size=%{public}d`, eventPkg.size)
for (const eventInfo of eventPkg.data) {
hilog.info(0x0000, 'testTag', `HiAppEvent eventPkg.info=%{public}s`, eventInfo)
}
}
}
})
}
}
1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows:
2. Choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add a button, and enable logging of button click events in its **onClick** function. The complete sample code is as follows:
```ts
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent';
```js
import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'
import hilog from '@ohos.hilog'
@Entry
@Component
......@@ -57,61 +109,21 @@ The following uses a one-time event watcher as an example to illustrate the deve
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button("1 writeTest").onClick(()=>{
// Perform event logging based on the input event parameters.
Button("writeTest").onClick(()=>{
// Enable event logging in the button click function to log button click events.
hiAppEvent.write({
domain: "test_domain",
name: "test_event",
eventType: hiAppEvent.EventType.FAULT,
params: {
int_data: 100,
str_data: "strValue"
}
// Define the event domain.
domain: "button",
// Define the event name.
name: "click",
// Define the event type.
eventType: hiAppEvent.EventType.BEHAVIOR,
// Define event parameters.
params: { click_time: 100 }
}).then(() => {
console.log(`HiAppEvent success to write event`);
hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`)
}).catch((err) => {
console.error(`code: ${err.code}, message: ${err.message}`);
});
})
Button("2 addWatcherTest").onClick(()=>{
// Add an event watcher based on the input subscription parameters.
hiAppEvent.addWatcher({
name: "watcher1",
appEventFilters: [{ domain: "test_domain" }],
triggerCondition: {
row: 2,
size: 1000,
timeOut: 2
},
onTrigger: function (curRow, curSize, holder) {
// If the holder object is null, return an error after recording it in the log.
if (holder == null) {
console.error("HiAppEvent holder is null");
return;
}
// Set the size threshold to 1,000 bytes for obtaining an event package.
holder.setSize(1000);
let eventPkg = null;
// Obtain the event package based on the configured size threshold. If returned event package is null, all event data has been obtained.
while ((eventPkg = holder.takeNext()) != null) {
// Parse the obtained event package and display the result on the Log page.
console.info(`HiAppEvent eventPkg.packageId=${eventPkg.packageId}`);
console.info(`HiAppEvent eventPkg.row=${eventPkg.row}`);
console.info(`HiAppEvent eventPkg.size=${eventPkg.size}`);
// Traverse and parse event string arrays in the obtained event package.
for (const eventInfo of eventPkg.data) {
console.info(`HiAppEvent eventPkg.data=${eventInfo}`);
}
}
}
});
})
Button("3 removeWatcherTest").onClick(()=>{
// Remove the specified event watcher.
hiAppEvent.removeWatcher({
name: "watcher1"
hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`)
})
})
}
......@@ -122,25 +134,19 @@ The following uses a one-time event watcher as an example to illustrate the deve
}
```
2. Touch the run button on the IDE to run the project.
3. Touch the run button on the IDE to run the project. Then, touch the **writeTest** button on the application UI to trigger application event logging.
3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window:
4. View the information printed in the **Log** window. If logging of the button click event is successful, you will see a message indicating successful event logging as well as the log information specific to processing of the event logging data in the subscription callback.
```
success to write event: 0
```
4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window.
```js
HiAppEvent success to write event
```
HiAppEvent eventPkg.packageId=0
HiAppEvent eventPkg.row=2
HiAppEvent eventPkg.size=308
HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"}
HiAppEvent eventPkg.row=1
HiAppEvent eventPkg.size=124
HiAppEvent eventPkg.info={"domain_":"button","name_":"click","type_":4,"time_":1670268234523,"tz_":"+0800","pid_":3295,"tid_":3309,"click_time":100}
```
5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
......
# Overview of Application Event Logging
The HiAppEvent module provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application.
You can use this module to develop application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
## Basic Concepts
**Logging**
A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis.
\ No newline at end of file
# Development of Distributed Call Chain Tracing
## When to Use
## Introduction
HiTraceChain is the module that provides APIs to implement call chain tracing throughout a service process. With HiTraceChain, you can quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls. The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process.
## Basic Concepts
- **chainId**
Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced.
## Available APIs
......
# Overview of Distributed Call Chain Tracing
hiTraceChain is a lightweight implementation of the cloud-based distributed call chain tracing. It allows applications to trace cross-thread, cross-process, and cross-device service calls.
## Basic Concepts
- **chainId**
Distributed call chain tracing ID, which is a part of **HiTraceId** and is used to identify the service process being traced.
## Working Principles
The hiTraceChain module generates a unique **chainId** for a service process and passes it to various information (including application events, system time, and logs) specific to the service process. During debugging and fault locating, you can use the unique **chainId** to quickly correlate various information related to the service process.
## Constraints
All APIs provided by the hiTraceChain module work in synchronous mode.
# Development of Performance Tracing
## When to Use
## Introduction
HiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by HiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
## Basic Concepts
- **hiTraceMeter Tag**
Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected.
## Working Principles
- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface.
- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device.
## Constraints
Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
## Available APIs
......
# Overview of Performance Tracing
hiTraceMeter is a tool for you to trace service processes and monitor system performance. Through encapsulating and extending the ftrace inside the kernel, hiTraceMeter supports performance tracing for code execution in the user space. You can use hiTraceMeter APIs to implement performance tracing and use the hiTraceMeter CLI tool to collect traced data.
## Basic Concepts
- **hiTraceMeter Tag**
Tag used for tracing data categorization. It is also known as **hiTraceMeter Category**. Generally, one subsystem maps to a tag. The tag is passed as the **Tag** parameter in performance tracing APIs. When you use the hiTraceMeter CLI tool to collect tracing data, only the tracing data specified by the **Tag** parameter is collected.
## Working Principles
- The application calls hiTraceMeter APIs to perform performance tracing. The APIs output the tracing data to the kernel's ftrace data buffer through the kernel's sysfs file interface.
- The hiTraceMeter CLI tool reads the tracing data in the ftrace data buffer and saves the trace data as a text file on the device.
## Constraints
Due to the asynchronous I/O feature of JS, the hiTraceMeter module provides only asynchronous APIs.
......@@ -34,7 +34,7 @@ Column() {
You can use **ForEach** to obtain data from arrays and create components for each data item.
```
```ts
ForEach(
arr: any[],
itemGenerator: (item: any, index?: number) => void,
......@@ -275,7 +275,7 @@ struct MyComponent {
>
> ```ts
> LazyForEach(dataSource,
> item => Text(`${item.i}. item.data.label`)),
> item => Text(`${item.i}. item.data.label`),
> item => item.data.id.toString())
> ```
......
......@@ -4,7 +4,7 @@ Both the public SDK and full SDK are toolkits for application development. <br>T
The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **XComponent**, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps.
> **NOTE**
>
......@@ -16,7 +16,8 @@ Manually download the system-specific full SDK package from the mirror. For deta
## Checking the Local SDK Location
In this example, an ArkTS project is used. For a JS project, replace **ets** with **js**.
In this example, an eTS project is used. For a JS project, replace **ets** with **js**.
In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK.
......@@ -35,11 +36,15 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
b. Verify that the SDK contains system APIs (such as APIs defined in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, and **@ohos.bluetooth.d.ts**).
Note: The criteria for identifying system APIs are subject to the released API documentation.
Note: The criteria for identifying system APIs are subject to the official API documentation.
2. Replace the SDK. The following uses public-SDK-3.x.x.x for Windows as an example.
a. Decompress the downloaded full SDK file: `ets-windows-3.x.x.x-Release.zip`
a. Decompress the downloaded full SDK file: **ets-windows-3.x.x.x-Release.zip**
![image-20220613165018184](figures/en-us_image_0000001655129264.png)
......@@ -51,13 +56,13 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
![image-20220613161352157](figures/en-us_image_0000001655129041.png)
Note: The name of the backup version directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.x.x.x_backup**.
Note: The name of the backup version directory must be different from the value of the **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.1.6.6_backup**.
![image-20220613165018184](figures/en-us_image_0000001655129398.png)
The configuration in the **oh-uni-package.json** file is as follows, where the value of `apiVersion` is subject to the API version of the SDK, and the value of `version` is subject to the version number in the SDK file.
The configuration in the **oh-uni-package.json** file is as follows, where the value of **apiVersion** is subject to the API version of the SDK, and the value of **version** is subject to the version number in the SDK file.
```
```json
{
"apiVersion": "X",
"displayName": "Ets",
......@@ -71,19 +76,19 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
```
Delete all files in the original SDK (3.x.x.x) directory. Failure to do so may result in some files being unable to be overwritten.
**Delete all files in the original SDK (3.x.x.x) directory.** Failure to do so may result in some files being unable to be overwritten.
Copy the full SDK to the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\*3.x.x.x*** directory in the location of the local SDK.
Copy all files in the **ets** directory in the full SDK to the **ets\3.x.x.x** directory in the location of the local SDK.
Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number.
In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the `npm install` command to download the **node_modules** dependency package.
In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package.
![image-20220613171111405](figures/en-us_image_0000001655129333.png)
......@@ -92,3 +97,21 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo
c. Check for system APIs.
![image-20220613213038104](figures/en-us_image_0000001655129372.png)
## Appendix: macOS Security Alarm Handling
After the SDK is switched to the full SDK in DevEco Studio on macOS, an alarm is generated when the Previewer is opened.
![alarm](figures/alarm.png)
To clear the alarm, perform the following steps:
1. Start the Terminal application.
2. In Terminal, run **sudo spctl -- master - disable**.
3. In **System Preferences**, choose **Security & Privacy**, click the **General** tab and select **Anywhere** under **Allow apps downloaded from**.
![alarmHand](figures/alarmHand.png)
Now, applications downloaded from third-party sources will not be blocked, meaning that you can open the Previewer. For security purposes, change the **Allow apps downloaded from** settings back to the original option when the Previewer is not in use.
......@@ -40,10 +40,10 @@ Creates an **Animator** object.
easing: 'friction',
delay: 0,
fill: 'forwards',
direction: "normal",
direction: 'normal',
iterations: 3,
begin: 200.0,
end: 400.0,
end: 400.0
};
animator.create(options);
```
......@@ -83,10 +83,10 @@ let options = {
easing: 'friction',
delay: 0,
fill: 'forwards',
direction: "normal",
direction: 'normal',
iterations: 3,
begin: 200.0,
end: 400.0,
end: 400.0
};
try {
animator.reset(options);
......@@ -283,7 +283,7 @@ export default {
easing: 'friction',
delay: 0,
fill: 'forwards',
direction: "normal",
direction: 'normal',
iterations: 2,
begin: 200.0,
end: 400.0
......@@ -516,7 +516,7 @@ let options = {
easing: 'friction',
delay: 0,
fill: 'forwards',
direction: "normal",
direction: 'normal',
iterations: 3,
begin: 200.0,
end: 400.0,
......
# Data Share Extension Ability
# @ohos.application.DataShareExtensionAbility
The **DataShareExtensionAbility** module provides Extension abilities for data share services.
The **DataShareExtensionAbility** module provides extension abilities for data share services.
>**NOTE**
>
......@@ -23,7 +23,7 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [ExtensionContext](js-apis-extension-context.md) | Yes| No|Context of the DataShare Extension ability.|
| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.|
## onCreate
......@@ -37,7 +37,7 @@ Called by the server to initialize service logic when the DataShare client conne
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.|
| want | [Want](js-apis-application-want.md#want) | Yes | **Want** information, including the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
**Example**
......@@ -83,7 +83,7 @@ Inserts data into the database. This API can be overridden as required.
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri |string | Yes | URI of the data to insert.|
| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.|
| valueBucket |[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| Data to insert.|
| callback |AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the index of the data inserted.|
**Example**
......@@ -127,8 +127,8 @@ Updates data in the database. This API can be overridden as required.
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to update.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.|
| valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.|
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.|
| valueBucket | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| New data.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of updated data records.|
**Example**
......@@ -170,7 +170,7 @@ Deletes data from the database. This API can be overridden as required.
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- |
| uri | string | Yes | URI of the data to delete. |
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of data records deleted.|
**Example**
......@@ -212,7 +212,7 @@ Queries data from the database. This API can be overridden as required.
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to query.|
| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.|
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.|
| columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is empty, all columns will be queried.|
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback invoked to return the result set.|
......@@ -258,7 +258,7 @@ Batch inserts data into the database. This API is called by the server and can b
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------- |
| uri | string | Yes | URI of the data to insert. |
| valueBuckets | Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes | Data to insert. |
| valueBuckets | Array&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes | Data to insert. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of inserted data records.|
**Example**
......
......@@ -1704,7 +1704,7 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | -------------------------- |
| type | string | Yes | Cause of the call disconnection.|
| callback | Callback<[DisconnectedDetails](#disconnecteddetails8)> | Yes | Callback used to return the result. |
| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | Yes | Callback used to return the result. |
**Example**
......@@ -1812,7 +1812,7 @@ This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------------- | ---- | -------------------- |
| type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.|
| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails8)> | No | Callback used to return the result. |
| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. |
**Example**
......@@ -2909,10 +2909,14 @@ This is a system API.
**System capability**: SystemCapability.Telephony.CallManager
| Name | Type | Mandatory| Description |
| ----------- | ---------------------------------------------------- | ---- | ---------------- |
| ------------------------ | ---------------------------------------------------- | ---- | ---------------- |
| transferNum | string | Yes | Call transfer number. |
| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. |
| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.|
| startHour<sup>9+</sup> | number | No | Hour in the start time.|
| startMinute<sup>9+</sup> | number | No | Minute in the start time.|
| endHour<sup>9+</sup> | number | No | Hour in the end time.|
| endMinute<sup>9+</sup> | number | No | Minute in the end time.|
## CallTransferType<sup>8+</sup>
......@@ -3128,10 +3132,14 @@ This is a system API.
**System capability**: SystemCapability.Telephony.CallManager
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------- | ---- | -------- |
| status | [TransferStatus](#transferstatus8) | Yes | Transfer status.|
| number | string | Yes | Number. |
| Name | Type | Mandatory| Description |
| ------------------------ | ---------------------------------- | ---- | ---------------- |
| status | [TransferStatus](#transferstatus8) | Yes | Call transfer status. |
| number | string | Yes | Call transfer number. |
| startHour<sup>9+</sup> | number | Yes | Hour in the start time.|
| startMinute<sup>9+</sup> | number | Yes | Minute in the start time.|
| endHour<sup>9+</sup> | number | Yes | Hour in the end time.|
| endMinute<sup>9+</sup> | number | Yes | Minute in the end time.|
## CallWaitingStatus<sup>7+</sup>
......@@ -3172,7 +3180,20 @@ This is a system API.
| TRANSFER_DISABLE | 0 | Call transfer disabled.|
| TRANSFER_ENABLE | 1 | Call transfer enabled.|
## DisconnectedDetails<sup>8+</sup>
## DisconnectedDetails<sup>9+</sup>
Defines the cause of a call disconnection.
This is a system API.
**System capability**: SystemCapability.Telephony.CallManager
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------ | ---- | --------------- |
| reason | [DisconnectedReason](#disconnectedreason8) | Yes | Cause of the call disconnection. |
| message | string | Yes | Message indicating the call disconnection.|
## DisconnectedReason<sup>8+</sup>
Enumerates causes of call disconnection.
......@@ -3181,26 +3202,85 @@ This is a system API.
**System capability**: SystemCapability.Telephony.CallManager
| Name | Value | Description |
| --------------------------- | ---- | ---------------------- |
| UNASSIGNED_NUMBER | 1 | Unallocated number. |
| NO_ROUTE_TO_DESTINATION | 3 | No route to the destination. |
| CHANNEL_UNACCEPTABLE | 6 | Unacceptable channel. |
| ------------------------------------------------------------ | ---- | --------------------------------------- |
| UNASSIGNED_NUMBER | 1 | Unallocated (unassigned) number. |
| NO_ROUTE_TO_DESTINATION | 3 | No route to destination. |
| CHANNEL_UNACCEPTABLE | 6 | Channel unacceptable. |
| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). |
| CALL_COMPLETED_ELSEWHERE<sup>9+</sup> | 13 | Call completed elsewhere. |
| NORMAL_CALL_CLEARING | 16 | Normal call clearing. |
| USER_BUSY | 17 | User busy. |
| NO_USER_RESPONDING | 18 | No user response. |
| USER_ALERTING_NO_ANSWER | 19 | Alerting but no answer.|
| NO_USER_RESPONDING | 18 | No user responding. |
| USER_ALERTING_NO_ANSWER | 19 | User alerting, no answer. |
| CALL_REJECTED | 21 | Call rejected. |
| NUMBER_CHANGED | 22 | Number changed. |
| DESTINATION_OUT_OF_ORDER | 27 | Destination fault. |
| INVALID_NUMBER_FORMAT | 28 | Invalid number format. |
| CALL_REJECTED_DUE_TO_FEATURE_AT_THE_DESTINATION<sup>9+</sup> | 24 | Call rejected due to feature at the destination.|
| FAILED_PRE_EMPTION<sup>9+</sup> | 25 | Failed preemption. |
| NON_SELECTED_USER_CLEARING<sup>9+</sup> | 26 | Non-selected user clearing. |
| DESTINATION_OUT_OF_ORDER | 27 | Destination out of order. |
| INVALID_NUMBER_FORMAT | 28 | Invalid number format (incomplete number). |
| FACILITY_REJECTED<sup>9+</sup> | 29 | Facility rejected. |
| RESPONSE_TO_STATUS_ENQUIRY<sup>9+</sup> | 30 | Response to status enquiry. |
| NORMAL_UNSPECIFIED<sup>9+</sup> | 31 | Normal, unspecified. |
| NO_CIRCUIT_CHANNEL_AVAILABLE<sup>9+</sup> | 34 | No circuit/channel available. |
| NETWORK_OUT_OF_ORDER | 38 | Network fault. |
| TEMPORARY_FAILURE | 41 | Temporary fault. |
| TEMPORARY_FAILURE | 41 | Temporary failure. |
| SWITCHING_EQUIPMENT_CONGESTION<sup>9+</sup> | 42 | Switching equipment congestion. |
| ACCESS_INFORMATION_DISCARDED<sup>9+</sup> | 43 | Access information discarded. |
| REQUEST_CIRCUIT_CHANNEL_NOT_AVAILABLE<sup>9+</sup> | 44 | Requested circuit/channel unavailable |
| RESOURCES_UNAVAILABLE_UNSPECIFIED<sup>9+</sup> | 47 | Resources unavailable, unspecified. |
| QUALITY_OF_SERVICE_UNAVAILABLE<sup>9+</sup> | 49 | QoS unavailable. |
| REQUESTED_FACILITY_NOT_SUBSCRIBED<sup>9+</sup> | 50 | Requested facility not subscribed. |
| INCOMING_CALLS_BARRED_WITHIN_THE_CUG<sup>9+</sup> | 55 | Incoming calls barred within the CUG. |
| BEARER_CAPABILITY_NOT_AUTHORIZED<sup>9+</sup> | 57 | Bearer capability not authorized. |
| BEARER_CAPABILITY_NOT_PRESENTLY_AVAILABLE<sup>9+</sup> | 58 | Bearer capability presently available. |
| SERVICE_OR_OPTION_NOT_AVAILABLE_UNSPECIFIED<sup>9+</sup> | 63 | Service or option not available, unspecified. |
| BEARER_SERVICE_NOT_IMPLEMENTED<sup>9+</sup> | 65 | Bearer service not implemented. |
| ACM_EQUALTO_OR_GREATER_THAN_THE_MAXIMUM_VALUE<sup>9+</sup> | 68 | ACM greater than or equal to the maximum value. |
| REQUESTED_FACILITY_NOT_IMPLEMENTED<sup>9+</sup> | 69 | Requested facility not implemented. |
| ONLY_RESTRICTED_DIGITAL_INFO_BEARER_CAPABILITY_IS_AVAILABLE<sup>9+</sup> | 70 | Only restricted digital information capability available. |
| SERVICE_OR_OPTION_NOT_IMPLEMENTED_UNSPECIFIED<sup>9+</sup> | 79 | Service or option not implemented, unspecified. |
| INVALID_TRANSACTION_IDENTIFIER_VALUE<sup>9+</sup> | 81 | Invalid transaction identifier value. |
| USER_NOT_MEMBER_OF_CUG<sup>9+</sup> | 87 | User not member of CUG. |
| INCOMPATIBLE_DESTINATION<sup>9+</sup> | 88 | Incompatible destination. |
| INVALID_TRANSIT_NETWORK_SELECTION<sup>9+</sup> | 91 | Invalid transit network selection. |
| SEMANTICALLY_INCORRECT_MESSAGE<sup>9+</sup> | 95 | Semantically incorrect message. |
| INVALID_MANDATORY_INFORMATION<sup>9+</sup> | 96 | Invalid mandatory information. |
| MESSAGE_TYPE_NON_EXISTENT_OR_NOT_IMPLEMENTED<sup>9+</sup> | 97 | Message type non-existent or not implemented. |
| MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE<sup>9+</sup> | 98 | Message type not compatible with protocol state. |
| INFORMATION_ELEMENT_NON_EXISTENT_OR_NOT_IMPLEMENTED<sup>9+</sup> | 99 | IE non-existent or not implemented. |
| CONDITIONAL_IE_ERROR<sup>9+</sup> | 100 | Conditional IE error. |
| MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE<sup>9+</sup> | 101 | Message not compatible with protocol state. |
| RECOVERY_ON_TIMER_EXPIRED<sup>9+</sup> | 102 | Recovery on timer expiry. |
| PROTOCOL_ERROR_UNSPECIFIED<sup>9+</sup> | 111 | Protocol error, unspecified. |
| INTERWORKING_UNSPECIFIED<sup>9+</sup> | 127 | Interworking, unspecified. |
| CALL_BARRED<sup>9+</sup> | 240 | Call barred. |
| FDN_BLOCKED<sup>9+</sup> | 241 | FDN blocked. |
| IMSI_UNKNOWN_IN_VLR<sup>9+</sup> | 242 | IMSI unknown in VLR. |
| IMEI_NOT_ACCEPTED<sup>9+</sup> | 243 | IMEI not accepted. |
| DIAL_MODIFIED_TO_USSD<sup>9+</sup> | 244 | Dial request modified to USSD request. |
| DIAL_MODIFIED_TO_SS<sup>9+</sup> | 245 | Dial request modified to SS request. |
| DIAL_MODIFIED_TO_DIAL<sup>9+</sup> | 246 | Dial request modified to dial with different number. |
| RADIO_OFF<sup>9+</sup> | 247 | Radio off. |
| OUT_OF_SERVICE<sup>9+</sup> | 248 | Out of service. |
| NO_VALID_SIM<sup>9+</sup> | 249 | No valid SIM. |
| RADIO_INTERNAL_ERROR<sup>9+</sup> | 250 | Radio internal error. |
| NETWORK_RESP_TIMEOUT<sup>9+</sup> | 251 | Network response timeout. |
| NETWORK_REJECT<sup>9+</sup> | 252 | Request rejected by network. |
| RADIO_ACCESS_FAILURE<sup>9+</sup> | 253 | Radio access failure. |
| RADIO_LINK_FAILURE<sup>9+</sup> | 254 | Radio link failure. |
| RADIO_LINK_LOST<sup>9+</sup> | 255 | Radio link lost. |
| RADIO_UPLINK_FAILURE<sup>9+</sup> | 256 | Radio uplink failure. |
| RADIO_SETUP_FAILURE<sup>9+</sup> | 257 | Radio setup failure. |
| RADIO_RELEASE_NORMAL<sup>9+</sup> | 258 | Radio release normal. |
| RADIO_RELEASE_ABNORMAL<sup>9+</sup> | 259 | Radio release abnormal. |
| ACCESS_CLASS_BLOCKED<sup>9+</sup> | 260 | Access class blocked. |
| NETWORK_DETACH<sup>9+</sup> | 261 | Network detached. |
| INVALID_PARAMETER | 1025 | Invalid parameter. |
| SIM_NOT_EXIT | 1026 | SIM card not exit. |
| SIM_PIN_NEED | 1027 | SIM card PIN required. |
| SIM_NOT_EXIT | 1026 | SIM not exit. |
| SIM_PIN_NEED | 1027 | SIM PIN needed. |
| CALL_NOT_ALLOW | 1029 | Call not allowed. |
| SIM_INVALID | 1045 | Invalid SIM card. |
| SIM_INVALID | 1045 | No valid SIM. |
| UNKNOWN | 1279 | Unknown reason. |
## MmiCodeResults<sup>9+</sup>
......
# Lightweight Storage
# @ohos.data.storage
Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
The **DataStorage** module provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
> **NOTE**
......
......@@ -72,7 +72,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| ---------- | ----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.|
**Example**
......@@ -181,7 +181,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
**Return value**
| Type | Description |
| :------------------------------------- | :-------------------------------- |
| ------------------------------------- | -------------------------------- |
| Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.|
......@@ -374,7 +374,7 @@ Defines an HTTP request method.
**System capability**: SystemCapability.Communication.NetStack
| Name | Value | Description |
| :------ | ------- | :------------------ |
| ------ | ------- | ------------------ |
| OPTIONS | "OPTIONS" | OPTIONS method.|
| GET | "GET" | GET method. |
| HEAD | "HEAD" | HEAD method. |
......@@ -459,7 +459,7 @@ Creates a default object to store responses to HTTP access requests.
**Return value**
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| ---------- | ----------------------------------------------------------- |
| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.|
**Example**
......@@ -602,6 +602,6 @@ Enumerates HTTP protocol versions.
**System capability**: SystemCapability.Communication.NetStack
| Name | Description |
| :-------- | :----------- |
| -------- | ----------- |
| HTTP1_1 | HTTP1.1 |
| HTTP2 | HTTP2 |
# Media Query
# @ohos.mediaquery
The **mediaquery** module provides different styles for different media types.
......@@ -14,64 +14,64 @@ import mediaquery from '@ohos.mediaquery'
```
## Required Permissions
None.
## mediaquery.matchMediaSync
matchMediaSync(condition: string): MediaQueryListener
Sets the media query criteria and returns the corresponding listening handle.
Sets the media query condition. This API returns the corresponding media query listener.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------------------------------------- |
| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).|
| condition | string | Yes | Media query condition. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).|
**Return value**
| Type | Description |
| ------------------ | ---------------------- |
| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.|
| MediaQueryListener | Media query listener, which is used to register or deregister the listening callback.|
**Example**
```js
```js
let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events.
```
```
## MediaQueryListener
Media query handle, including the first query result when the handle is applied for.
Implements the media query listener, including the first query result when the listener is applied for.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
### Attributes
| Name | Type | Readable | Writable | Description |
| ------- | ------- | ---- | ---- | ---------- |
| matches | boolean | Yes | No | Whether the match condition is met. |
| media | string | Yes | No | Matching condition of a media event.|
| Name | Type | Readable| Writable| Description |
| ------- | ------- | ---- | ---- | -------------------- |
| matches | boolean | Yes | No | Whether the media query condition is met. |
| media | string | Yes | No | Media query condition.|
### on
on(type: 'change', callback: Callback&lt;MediaQueryResult&gt;): void
Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change.
Registers the media query listener. The callback is triggered when the media attributes change.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ---------------- |
| type | string | Yes | Must enter the string **change**.|
| type | string | Yes | Listener type. The value is fixed at **'change'**.|
| callback | Callback&lt;MediaQueryResult&gt; | Yes | Callback registered with media query. |
**Example**
For details, see [off Example](#off).
......@@ -79,17 +79,19 @@ Registers a callback with the corresponding query condition by using the handle.
off(type: 'change', callback?: Callback&lt;MediaQueryResult&gt;): void
Deregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change.
Deregisters the media query listener, so that no callback is triggered when the media attributes change.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | -------------------------------- | ---- | ----------------------------- |
| type | boolean | Yes | Must enter the string **change**. |
| Name | Type | Mandatory| Description |
| -------- | -------------------------------- | ---- | ---------------------------------------------------------- |
| type | string | Yes | Listener type. The value is fixed at **'change'**. |
| callback | Callback&lt;MediaQueryResult&gt; | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.|
**Example**
```js
import mediaquery from '@ohos.mediaquery'
......@@ -101,20 +103,23 @@ Deregisters a callback with the corresponding query condition by using the handl
// do something here
}
}
listener.on('change', onPortrait) // Register a callback.
listener.off('change', onPortrait) // Deregister a callback.
listener.on('change', onPortrait) // Register the media query listener.
listener.off('change', onPortrait) // Deregister the media query listener.
```
## MediaQueryResult
Provides the media query result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
### Attributes
| Name | Type | Readable | Writable | Description |
| ------- | ------- | ---- | ---- | ---------- |
| matches | boolean | Yes | No | Whether the match condition is met. |
| media | string | Yes | No | Matching condition of a media event.|
| Name | Type | Readable| Writable| Description |
| ------- | ------- | ---- | ---- | -------------------- |
| matches | boolean | Yes | No | Whether the media query condition is met. |
| media | string | Yes | No | Media query condition.|
### Example
......
......@@ -61,7 +61,7 @@ connection.getDefaultNet().then(function (netHandle) {
})
```
## connection.getDefaultNetSync
## connection.getDefaultNetSync<sup>9+</sup>
getDefaultNetSync(): NetHandle;
......@@ -303,6 +303,55 @@ connection.getDefaultNet().then(function (netHandle) {
})
```
## connection.isDefaultNetMetered<sup>9+</sup>
isDefaultNetMetered(callback: AsyncCallback\<boolean>): void
Checks whether the data traffic usage on the current network is metered. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**:
```js
connection.isDefaultNetMetered(function (error, has) {
console.log(JSON.stringify(error))
console.log('has: ' + has)
})
```
## connection.isDefaultNetMetered<sup>9+</sup>
isDefaultNetMetered(): Promise\<boolean>
Checks whether the data traffic usage on the current network is metered. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Core
**Return value**
| Type | Description |
| ----------------- | ----------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The value **true** indicates the data traffic usage is metered.|
**Example**:
```js
connection.isDefaultNetMetered().then(function (has) {
console.log('has: ' + has)
})
```
## connection.reportNetConnected
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
......@@ -495,7 +544,7 @@ enableAirplaneMode(callback: AsyncCallback\<void>): void
Enables the airplane mode. This API uses an asynchronous callback to return the result.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -519,7 +568,7 @@ enableAirplaneMode(): Promise\<void>
Enables the airplane mode. This API uses a promise to return the result.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -543,7 +592,7 @@ disableAirplaneMode(callback: AsyncCallback\<void>): void
Disables the airplane mode. This API uses an asynchronous callback to return the result.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -567,7 +616,7 @@ disableAirplaneMode(): Promise\<void>
Disables the airplane mode. This API uses a promise to return the result.
This is a system API.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -823,7 +872,7 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle**
| ------ | ------ | ------------------------- |
| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.|
### bindSocket
### bindSocket<sup>9+</sup>
bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\<void>): void;
......@@ -1091,10 +1140,10 @@ Provides an instance that bears data network capabilities.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. |
| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).|
## NetCapabilities
......@@ -1102,12 +1151,12 @@ Defines the network capability set.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| --------------------- | ---------------------------------- | ------------------------ |
| linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.|
| linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.|
| networkCap | Array<[NetCap](#netcap)> | Network capability. |
| bearerTypes | Array<[NetBearType](#netbeartype)> | Network type. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.|
| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.|
| networkCap | Array<[NetCap](#netcap)> | No | Network capability. |
| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. |
## NetCap
......@@ -1141,14 +1190,14 @@ Defines the network connection properties.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------------- | ---------------------------------- | ---------------- |
| interfaceName | string | NIC card name. |
| domains | string | Domain. The default value is **""**.|
| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information. |
| routes | Array<[RouteInfo](#routeinfo)> | Route information. |
| dnses | Array&lt;[NetAddress](#netaddress)&gt; | Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Maximum transmission unit (MTU). |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| interfaceName | string | Yes | NIC card name. |
| domains | string | Yes | Domain. The default value is **""**.|
| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. |
| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. |
| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).|
| mtu | number | Yes | Maximum transmission unit (MTU). |
## LinkAddress
......@@ -1156,10 +1205,10 @@ Network link information.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------------ | ------------------------- | -------------------- |
| address | [NetAddress](#netaddress) | Link address. |
| prefixLength | number | Length of the link address prefix.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| address | [NetAddress](#netaddress) | Yes | Link address. |
| prefixLength | number | Yes | Length of the link address prefix.|
## RouteInfo
......@@ -1167,13 +1216,13 @@ Network route information.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| -------------- | --------------------------- | ---------------- |
| interface | string | NIC card name. |
| destination | [LinkAddress](#linkaddress) | Destination IP address. |
| gateway | [NetAddress](#netaddress) | Gateway address. |
| hasGateway | boolean | Whether a gateway is present. |
| isDefaultRoute | boolean | Whether the route is the default route.|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| interface | string | Yes | NIC card name. |
| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. |
| gateway | [NetAddress](#netaddress) | Yes | Gateway address. |
| hasGateway | boolean | Yes | Whether a gateway is present. |
| isDefaultRoute | boolean | Yes | Whether the route is the default route.|
## NetAddress
......@@ -1181,8 +1230,8 @@ Defines the network address.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ------- | ------ | ------------------------------ |
| address | string | Network address. |
| family | number | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | Port number. The value ranges from **0** to **65535**. |
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| address | string | Yes | Network address. |
| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No | Port number. The value ranges from **0** to **65535**. |
......@@ -14,7 +14,7 @@ import ethernet from '@ohos.net.ethernet'
## ethernet.setIfaceConfig
setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\<void>): void;
setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\<void>): void
Sets the network interface configuration. This API uses an asynchronous callback to return the result.
......@@ -46,7 +46,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro
## ethernet.setIfaceConfig
setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>;
setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\<void>
Sets the network interface configuration. This API uses a promise to return the result.
......@@ -80,7 +80,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro
## ethernet.getIfaceConfig
getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void;
getIfaceConfig(iface: string, callback: AsyncCallback\<InterfaceConfiguration>): void
Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result.
......@@ -115,7 +115,7 @@ ethernet.getIfaceConfig("eth0", (error, value) => {
## ethernet.getIfaceConfig
getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>;
getIfaceConfig(iface: string): Promise\<InterfaceConfiguration>
Obtains the configuration of a network interface. This API uses a promise to return the result.
......@@ -153,7 +153,7 @@ ethernet.getIfaceConfig("eth0").then((data) => {
## ethernet.isIfaceActive
isIfaceActive(iface?: string, callback: AsyncCallback\<number>): void;
isIfaceActive(iface?: string, callback: AsyncCallback\<number>): void
Checks whether a network interface is active. This API uses an asynchronous callback to return the result.
......@@ -165,7 +165,7 @@ Checks whether a network interface is active. This API uses an asynchronous call
| Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | -------------------------------------------------- |
| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. |
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. |
| callback | AsyncCallback\<number> | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.|
**Example**
......@@ -182,7 +182,7 @@ ethernet.isIfaceActive("eth0", (error, value) => {
## ethernet.isIfaceActive
isIfaceActive(iface?: string): Promise\<number>;
isIfaceActive(iface: string): Promise\<number>
Checks whether a network interface is active. This API uses a promise to return the result.
......@@ -194,7 +194,7 @@ Checks whether a network interface is active. This API uses a promise to return
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------------------------- |
| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.|
| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.|
**Return value**
......@@ -214,7 +214,7 @@ ethernet.isIfaceActive("eth0").then((data) => {
## ethernet.getAllActiveIfaces
getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void;
getAllActiveIfaces(callback: AsyncCallback\<Array\<string>>): void
Obtains all active network interfaces. This API uses an asynchronous callback to return the result.
......@@ -245,7 +245,7 @@ ethernet.getAllActiveIfaces((error, value) => {
## ethernet.getAllActiveIfaces
getAllActiveIfaces(): Promise\<Array\<string>>;
getAllActiveIfaces(): Promise\<Array\<string>>
Obtains all active network interfaces. This API uses a promise to return the result.
......@@ -280,14 +280,14 @@ Defines the network configuration for the Ethernet connection.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Description |
| ----------------------- | ----------------------------------- | ------------------------------------------------------------ |
| mode | [IPSetMode](#ipsetmode) | Configuration mode of the Ethernet connection.|
| ipAddr | string | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| route | string | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| gateway | string | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
| Name | Type | Mandatory | Description |
| -------- | ------- | --------- | ----------- |
| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.|
| ipAddr | string | Yes | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.|
| route | string | Yes | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| gateway | string | Yes | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
## IPSetMode
......
......@@ -18,9 +18,11 @@ isSharingSupported(callback: AsyncCallback\<boolean>): void
Checks whether network sharing is supported. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -43,9 +45,11 @@ isSharingSupported(): Promise\<boolean>
Checks whether network sharing is supported. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value**
......@@ -69,9 +73,11 @@ isSharing(callback: AsyncCallback\<boolean>): void
Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -96,7 +102,9 @@ Checks whether network sharing is in progress. This API uses a promise to return
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value**
......@@ -122,7 +130,9 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -146,9 +156,11 @@ startSharing(type: SharingIfaceType): Promise\<void>
Starts network sharing of a specified type. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -179,9 +191,11 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\<void>): void
Stops network sharing of a specified type. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -205,9 +219,11 @@ stopSharing(type: SharingIfaceType): Promise\<void>
Stops network sharing of a specified type. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -238,9 +254,11 @@ getStatsRxBytes(callback: AsyncCallback\<number>): void
Obtains the volume of mobile data traffic received via network sharing. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -263,9 +281,11 @@ getStatsRxBytes(): Promise\<number>
Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value**
......@@ -289,9 +309,11 @@ getStatsTxBytes(callback: AsyncCallback\<number>): void
Obtains the volume of mobile data traffic sent via network sharing. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -314,9 +336,11 @@ getStatsTxBytes(): Promise\<number>
Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value**
......@@ -340,9 +364,11 @@ getStatsTotalBytes(callback: AsyncCallback\<number>): void
Obtains the volume of mobile data traffic sent and received via network sharing. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -365,9 +391,11 @@ getStatsTotalBytes(): Promise\<number>
Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Return value**
......@@ -391,15 +419,17 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\<Array\<strin
Obtains the names of NICs in the specified network sharing state. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return an array of NIC names.|
**Example**
......@@ -418,15 +448,17 @@ getSharingIfaces(state: SharingIfaceState): Promise\<Array\<string>>
Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.|
**Return value**
......@@ -451,9 +483,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\<SharingIfaceSta
Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -478,9 +512,11 @@ getSharingState(type: SharingIfaceType): Promise\<SharingIfaceState>
Obtains the network sharing state of the specified type. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -511,9 +547,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\<Array\<strin
Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -538,9 +576,11 @@ getSharableRegexes(type: SharingIfaceType): Promise\<Array\<string>>
Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -571,9 +611,11 @@ on(type: 'sharingStateChange', callback: Callback\<boolean>): void
Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -597,9 +639,11 @@ off(type: 'sharingStateChange', callback?: Callback\<boolean>): void
Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -623,9 +667,11 @@ on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIface
Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -649,15 +695,17 @@ off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfa
Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| type | string | No | Event name.|
| type | string | Yes | Event name.|
| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.|
**Example**
......@@ -675,9 +723,11 @@ on(type: 'sharingUpstreamChange', callback: Callback\<NetHandle>): void
Subscribes to upstream network changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -701,9 +751,11 @@ off(type: 'sharingUpstreamChange', callback?: Callback\<NetHandle>): void
Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL
**System capability**: SystemCapability.Communication.NetManager.Core
**System capability**: SystemCapability.Communication.NetManager.NetSharing
**Parameters**
......@@ -725,7 +777,9 @@ sharing.off('sharingUpstreamChange', (error, data) => {
Enumerates the network sharing states of an NIC.
**System capability**: SystemCapability.Communication.NetManager.Core
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.NetSharing
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
......@@ -737,7 +791,9 @@ Enumerates the network sharing states of an NIC.
Enumerates the network sharing types of an NIC.
**System capability**: SystemCapability.Communication.NetManager.Core
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.NetManager.NetSharing
| Name | Value | Description |
| ------------------------ | ---- | ---------------------- |
......
# Prompt
# @ohos.prompt
The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus.
......@@ -146,11 +146,11 @@ Describes the options for showing the dialog box.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the dialog box. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Text body. |
| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
## ShowDialogSuccessResponse
......@@ -158,9 +158,9 @@ Describes the dialog box response result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Description |
| ----- | ------ | ------------------- |
| index | number | Index of the selected button in the **buttons** array.|
| Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ------------------------------- |
| index | number | No | Index of the selected button in the **buttons** array.|
## prompt.showActionMenu
......@@ -255,10 +255,10 @@ Describes the options for showing the action menu.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup> | No | Title of the text to display. |
| buttons | Array&lt;[Button](#button)&gt; | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
## ActionMenuSuccessResponse
......
# Prompt
# @ohos.promptAction
The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus.
......@@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -181,11 +181,11 @@ Describes the options for showing the dialog box.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Title of the dialog box. |
| message | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Text body. |
| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?] | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.|
## ShowDialogSuccessResponse
......@@ -193,9 +193,9 @@ Describes the dialog box response result.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Description |
| ----- | ------ | ------------------- |
| index | number | Index of the selected button in the **buttons** array.|
| Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ------------------------------- |
| index | number | No | Index of the selected button in the **buttons** array.|
## promptAction.showActionMenu
......@@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -314,10 +314,10 @@ Describes the options for showing the action menu.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description |
| ------- | ---------------------------------------- | ---- | ---------------------------------------- |
| Name | Type | Mandatory| Description |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| title | string\| [Resource](../arkui-ts/ts-types.md#resource)<sup>9+</sup>| No | Title of the dialog box. |
| buttons | Array&lt;[Button](#button)&gt; | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?] | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.|
## ActionMenuSuccessResponse
......
# Page Routing
# @ohos.router
The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page.
......@@ -40,9 +40,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100002 | Uri error. The uri of router is not exist. |
| 100003 | Page stack error. The pages are pushed too much. |
| 100001 | If UI execution context not found. |
| 100002 | If the uri is not exist. |
| 100003 | If the pages are pushed too much. |
**Example**
......@@ -54,8 +54,8 @@ try {
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
})
.then(() => {
// success
......@@ -89,9 +89,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100002 | Uri error. The uri of router is not exist. |
| 100003 | Page stack error. The pages are pushed too much. |
| 100001 | If UI execution context not found. |
| 100002 | If the uri is not exist. |
| 100003 | If the pages are pushed too much. |
**Example**
......@@ -103,8 +103,8 @@ try {
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
}, (err) => {
if (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
......@@ -143,9 +143,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100002 | Uri error. The uri of router is not exist. |
| 100003 | Page stack error. The pages are pushed too much. |
| 100001 | If UI execution context not found. |
| 100002 | If the uri is not exist. |
| 100003 | If the pages are pushed too much. |
**Example**
......@@ -157,8 +157,8 @@ try {
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
}, router.RouterMode.Standard)
.then(() => {
// success
......@@ -193,9 +193,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100002 | Uri error. The uri of router is not exist. |
| 100003 | Page stack error. The pages are pushed too much. |
| 100001 | If UI execution context not found. |
| 100002 | If the uri is not exist. |
| 100003 | If the pages are pushed too much. |
**Example**
......@@ -207,8 +207,8 @@ try {
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
......@@ -247,8 +247,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 200002 | Uri error. The uri of router is not exist. |
| 100001 | If UI execution context not found, only throw in standard system. |
| 200002 | If the uri is not exist. |
**Example**
......@@ -257,8 +257,8 @@ try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message',
},
data1: 'message'
}
})
.then(() => {
// success
......@@ -292,8 +292,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 200002 | Uri error. The uri of router is not exist. |
| 100001 | If UI execution context not found, only throw in standard system. |
| 200002 | If the uri is not exist. |
**Example**
......@@ -302,8 +302,8 @@ try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message',
},
data1: 'message'
}
}, (err) => {
if (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
......@@ -344,8 +344,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 200002 | Uri error. The uri of router is not exist. |
| 100001 | If UI execution context not found, only throw in standard system. |
| 200002 | If the uri is not exist. |
**Example**
......@@ -354,8 +354,8 @@ try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message',
},
data1: 'message'
}
}, router.RouterMode.Standard)
.then(() => {
// success
......@@ -390,8 +390,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 200002 | Uri error. The uri of router is not exist. |
| 100001 | If UI execution context not found, only throw in standard system. |
| 200002 | If the uri is not exist. |
**Example**
......@@ -400,8 +400,8 @@ try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message',
},
data1: 'message'
}
}, router.RouterMode.Standard, (err) => {
if (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
......@@ -465,7 +465,7 @@ Obtains the number of pages in the current stack.
**Example**
```js
var size = router.getLength();
let size = router.getLength();
console.log('pages stack size = ' + size);
```
......@@ -486,7 +486,7 @@ Obtains state information about the current page.
**Example**
```js
var page = router.getState();
let page = router.getState();
console.log('current index = ' + page.index);
console.log('current name = ' + page.name);
console.log('current path = ' + page.path);
......@@ -498,11 +498,11 @@ Describes the page routing state.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Description |
| ----- | ------ | ---------------------------------- |
| index | number | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.|
| name | string | Name of the current page, that is, the file name. |
| path | string | Path of the current page. |
| Name | Type | Mandatory| Description |
| ----- | ------ | ---- | ------------------------------------------------------------ |
| index | number | Yes | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.|
| name | string | No | Name of the current page, that is, the file name. |
| path | string | Yes | Path of the current page. |
## router.enableBackPageAlert<sup>9+</sup>
......@@ -524,7 +524,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | Internal error. |
| 100001 | If UI execution context not found. |
**Example**
......@@ -590,7 +590,7 @@ Describes the page routing options.
| Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| url | string | Yes | URL of the target page, in either of the following formats:<br>- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:<br>- pages/index/index<br>- pages/detail/detail<br>- Particular path. If the URL is a slash (/), the home page is displayed.|
| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.|
| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.|
> **NOTE**
......@@ -603,8 +603,8 @@ Enumerates the routing modes.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Description |
| -------- | ---------------------------------------- |
| Standard | Standard mode.<br>The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. |
| -------- | ------------------------------------------------------------ |
| Standard | Standard mode.<br>The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.|
| Single | Singleton mode.<br>If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.<br>If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.|
## Examples
......@@ -618,8 +618,8 @@ export default {
router.push({
url: 'pages/detail/detail',
params: {
data1: 'message',
},
data1: 'message'
}
});
}
}
......@@ -649,11 +649,11 @@ struct Index {
text: 'This is the value on the first page.',
data: {
array: [12, 45, 78]
},
}
}
}
try {
await router.push(options)
await router.pushUrl(options)
} catch (err) {
console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`)
}
......@@ -704,7 +704,7 @@ struct Second {
this.secondData = (this.data.array[1]).toString()
})
.margin({top:20})
Text('Value from the first page '+'' + this.secondData)
Text(`This is the data passed from the first page: ${this.secondData}`)
.fontSize(20)
.margin({top:20})
.backgroundColor('red')
......@@ -741,8 +741,8 @@ router.push({
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
});
```
## router.push<sup>(deprecated)</sup>
......@@ -772,8 +772,8 @@ router.push({
data1: 'message',
data2: {
data3: [123, 456, 789]
},
},
}
}
},router.RouterMode.Standard);
```
......@@ -799,8 +799,8 @@ This API is deprecated since API version 9. You are advised to use [replaceUrl<s
router.replace({
url: 'pages/detail',
params: {
data1: 'message',
},
data1: 'message'
}
});
```
......@@ -812,7 +812,7 @@ Replaces the current page with another one in the application and destroys the c
This API is deprecated since API version 9. You are advised to use [replaceUrl<sup>9+</sup>](#routerreplaceurl9) instead.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**System capability**: SystemCapability.ArkUI.ArkUI.Lite
**Parameters**
......@@ -827,8 +827,8 @@ This API is deprecated since API version 9. You are advised to use [replaceUrl<s
router.replace({
url: 'pages/detail/detail',
params: {
data1: 'message',
},
data1: 'message'
}
}, router.RouterMode.Standard);
```
......
......@@ -2934,6 +2934,37 @@ Enumerates contact types.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Value | Description |
| :-------------- | ---- | ---------- |
| -------------- | ---- | ---------- |
| GENERAL_CONTACT | 1 | Common contact number.|
| FIXED_DIALING | 2 | Fixed dialing number. |
## OperatorConfigKey<sup>9+</sup>
Enumerates carrier configuration keys.
**System API**: This is a system API.
**System capability**: SystemCapability.Telephony.CoreService
| Name | Value | Description |
| ------------------------------------------------------- | ---------------------------------------------------- | -------------------- |
| KEY_VOICE_MAIL_NUMBER_STRING | "voice_mail_number_string" | Voice mailbox number. |
| KEY_IMS_SWITCH_ON_BY_DEFAULT_BOOL | "ims_switch_on_by_default_bool" | Fixed dialing number. |
| KEY_HIDE_IMS_SWITCH_BOOL | "hide_ims_switch_bool" | Whether to hide the IMS switch. |
| KEY_VOLTE_SUPPORTED_BOOL | "volte_supported_bool" | Whether to support VoLTE. |
| KEY_NR_MODE_SUPPORTED_LIST_INT_ARRAY | "nr_mode_supported_list_int_array" | List of supported NR modes. |
| KEY_VOLTE_PROVISIONING_SUPPORTED_BOOL | "volte_provisioning_supported_bool" | Whether to support VoLTE provisioning. |
| KEY_SS_OVER_UT_SUPPORTED_BOOL | "ss_over_ut_supported_bool" | Whether SS over UT is supported. |
| KEY_IMS_GBA_REQUIRED_BOOL | "ims_gba_required_bool" | Whether GBA is required for IMS. |
| KEY_UT_PROVISIONING_SUPPORTED_BOOL | "ut_provisioning_supported_bool" | Whether to support UT provisioning. |
| KEY_IMS_PREFER_FOR_EMERGENCY_BOOL | "ims_prefer_for_emergency_bool" | IMS preferences for emergency. |
| KEY_CALL_WAITING_SERVICE_CLASS_INT | "call_waiting_service_class_int" | Call waiting service. |
| KEY_CALL_TRANSFER_VISIBILITY_BOOL | "call_transfer_visibility_bool" | Call transfer visibility. |
| KEY_IMS_CALL_DISCONNECT_REASONINFO_MAPPING_STRING_ARRAY | "ims_call_disconnect_reasoninfo_mapping_string_array" | List of IMS call disconnection reasons.|
| KEY_FORCE_VOLTE_SWITCH_ON_BOOL | "force_volte_switch_on_bool" | Whether to forcibly turn on VoLTE. |
| KEY_ENABLE_OPERATOR_NAME_CUST_BOOL | "enable_operator_name_cust_bool" | Whether to display the carrier name.|
| KEY_OPERATOR_NAME_CUST_STRING | "operator_name_cust_string" | Carrier name. |
| KEY_SPN_DISPLAY_CONDITION_CUST_INT | "spn_display_condition_cust_int" | SPN display rule. |
| KEY_PNN_CUST_STRING_ARRAY | "pnn_cust_string_array" | PLMN name |
| KEY_OPL_CUST_STRING_ARRAY | "opl_cust_string_array" | PLMN information of the carrier. |
| KEY_EMERGENCY_CALL_STRING_ARRAY | "emergency_call_string_array" | Emergency call list. |
......@@ -870,7 +870,7 @@ promise.then(data => {
## sms.isImsSmsSupported<sup>8+</sup>
isImsSmsSupported(callback: AsyncCallback<boolean\>): void
isImsSmsSupported(slotId: number, callback: AsyncCallback<boolean\>): void
Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result.
......@@ -882,12 +882,14 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------- |
| slotId | number | Yes | SIM card slot ID. <br>- **0**: card slot 1<br>- **1**: card slot 2|
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.|
**Example**
```js
sms.isImsSmsSupported((err, data) => {
let slotId = 0;
sms.isImsSmsSupported(slotId, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
......@@ -895,7 +897,7 @@ sms.isImsSmsSupported((err, data) => {
## sms.isImsSmsSupported<sup>8+</sup>
isImsSmsSupported(): Promise<boolean\>
isImsSmsSupported(slotId: number): Promise<boolean\>
Checks whether SMS is supported on IMS. This API uses a promise to return the result.
......@@ -903,6 +905,12 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re
**System capability**: SystemCapability.Telephony.SmsMms
**Parameters**
| Name| Type | Mandatory | Description |
| ------ | ------ | ---- | -------------------------------------- |
| slotId | number | Yes | Card slot ID.<br>- **0**: card slot 1<br>- **1**: card slot 2|
**Return value**
| Type | Description |
......@@ -912,7 +920,8 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re
**Example**
```js
let promise = sms.isImsSmsSupported();
let slotId = 0;
let promise = sms.isImsSmsSupported(slotId);
promise.then(data => {
console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
......
......@@ -21,7 +21,7 @@ Creates a **UDPSocket** object.
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| --------------------------------- | ---------------------- |
| [UDPSocket](#udpsocket) | **UDPSocket** object.|
......@@ -87,7 +87,7 @@ Binds the IP address and port number. The port number can be specified or random
**Return value**
| Type | Description |
| :-------------- | :----------------------------------------- |
| -------------- | ----------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -164,7 +164,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------- |
| -------------- | --------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -230,7 +230,7 @@ Closes a UDPSocket connection. This API uses a promise to return the result.
**Return value**
| Type | Description |
| :-------------- | :----------------------------------------- |
| -------------- | ----------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -252,7 +252,7 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -292,7 +292,7 @@ getState\(\): Promise<SocketStateBase\>
Obtains the status of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -302,7 +302,7 @@ Obtains the status of the UDPSocket connection. This API uses a promise to retur
**Return value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| ----------------------------------------------- | ----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
**Example**
......@@ -331,7 +331,7 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback<void\>\): voi
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -379,7 +379,7 @@ setExtraOptions\(options: UDPExtraOptions\): Promise<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -395,7 +395,7 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| -------------- | --------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -454,7 +454,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -514,7 +514,7 @@ off\(type: 'listening' | 'close', callback?: Callback<void\>\): void
Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -579,7 +579,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -678,7 +678,7 @@ Creates a **TCPSocket** object.
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| --------------------------------- | ---------------------- |
| [TCPSocket](#tcpsocket) | **TCPSocket** object.|
**Example**
......@@ -743,7 +743,7 @@ Binds the IP address and port number. The port number can be specified or random
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------------------- |
| -------------- | ------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -809,7 +809,7 @@ Sets up a connection to the specified IP address and port number. This API uses
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------------- |
| -------------- | --------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -831,7 +831,7 @@ send\(options: TCPSendOptions, callback: AsyncCallback<void\>\): void
Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -873,7 +873,7 @@ send\(options: TCPSendOptions\): Promise<void\>
Sends data over a TCPSocket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -889,7 +889,7 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------------- |
| -------------- | ------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -957,7 +957,7 @@ Closes a TCPSocket connection. This API uses a promise to return the result.
**Return value**
| Type | Description |
| :-------------- | :----------------------------------------- |
| -------------- | ----------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
**Example**
......@@ -979,7 +979,7 @@ getRemoteAddress\(callback: AsyncCallback<NetAddress\>\): void
Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1018,7 +1018,7 @@ getRemoteAddress\(\): Promise<NetAddress\>
Obtains the remote address of a socket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1028,7 +1028,7 @@ Obtains the remote address of a socket connection. This API uses a promise to re
**Return value**
| Type | Description |
| :------------------------------------------ | :------------------------------------------ |
| ------------------------------------------ | ------------------------------------------ |
| Promise<[NetAddress](#netaddress)> | Promise used to return the result.|
**Example**
......@@ -1056,7 +1056,7 @@ getState\(callback: AsyncCallback<SocketStateBase\>\): void
Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1096,7 +1096,7 @@ getState\(\): Promise<SocketStateBase\>
Obtains the status of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1106,7 +1106,7 @@ Obtains the status of the TCPSocket connection. This API uses a promise to retur
**Return value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| ----------------------------------------------- | ----------------------------------------- |
| Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.|
......@@ -1135,7 +1135,7 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback<void\>\): voi
Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1184,7 +1184,7 @@ setExtraOptions\(options: TCPExtraOptions\): Promise<void\>
Sets other properties of the TCPSocket connection. This API uses a promise to return the result.
>**NOTE**
>**NOTE**<br/>
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called.
**Required permissions**: ohos.permission.INTERNET
......@@ -1200,7 +1200,7 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| -------------- | --------------------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
......@@ -1263,7 +1263,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So
Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -1324,7 +1324,7 @@ off\(type: 'connect' | 'close', callback?: Callback<void\>\): void
Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -1388,7 +1388,7 @@ off\(type: 'error', callback?: ErrorCallback\): void
Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>**NOTE**<br/>
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
**System capability**: SystemCapability.Communication.NetStack
......@@ -1464,7 +1464,7 @@ Creates a **TLSSocket** object.
**Return value**
| Type | Description |
| :--------------------------------- | :---------------------- |
| --------------------------------- | ---------------------- |
| [TLSSocket](#tlssocket9) | **TLSSocket** object.|
**Example**
......@@ -1534,7 +1534,7 @@ Binds the IP address and port number. This API uses a promise to return the resu
**Return value**
| Type | Description |
| :-------------- | :------------------------------------------------------- |
| -------------- | ------------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
......@@ -1608,7 +1608,7 @@ Obtains the status of the TLSSocket connection. This API uses a promise to retur
**Return value**
| Type | Description |
| :----------------------------------------------- | :----------------------------------------- |
| ----------------------------------------------- | ----------------------------------------- |
| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
......@@ -1705,7 +1705,7 @@ Sets other properties of the TCPSocket connection after successful binding of th
**Return value**
| Type | Description |
| :-------------- | :--------------------------------------------------- |
| -------------- | --------------------------------------------------- |
| Promise\<void\> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
......@@ -1984,7 +1984,7 @@ Obtains the remote address of a TLSSocket connection. This API uses a promise to
**Return value**
| Type | Description |
| :------------------------------------------ | :------------------------------------------ |
| ------------------------------------------ | ------------------------------------------ |
| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.|
**Error codes**
......@@ -2490,7 +2490,7 @@ Defines TLS connection options.
| -------------- | ------------------------------------- | --- |-------------- |
| address | [NetAddress](#netaddress) | Yes | Gateway address. |
| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.|
| ALPNProtocols | Array\<string> | No| Application Layer Protocol Negotiation (ALPN) protocols. |
| ALPNProtocols | Array\<string> | Yes| Application Layer Protocol Negotiation (ALPN) protocols. |
## TLSSecureOptions<sup>9+</sup>
......
......@@ -96,10 +96,9 @@
- Custom Components
- [Basic Usage](js-components-custom-basic-usage.md)
- [Style Inheritance](js-components-custom-style.md)
- [Custom Events](js-components-custom-events.md)
- [props](js-components-custom-props.md)
- [Event Parameter](js-components-custom-event-parameter.md)
- [Style Inheritance](js-components-custom-style.md)
- [slot](js-components-custom-slot.md)
- [Lifecycle Definition](js-components-custom-lifecycle.md)
- [Dynamic Component Creation](js-components-create-elements.md)
- [Data Type Attributes](js-appendix-types.md)
# Dynamic Component Creation
You can dynamically add components with specified attributes and styles to pages.
> **NOTE**
>
> This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## createElement
createElement(tag: string): Element
Creates a component object.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| tag | string | Yes | Component name.|
**Return value**
| Type | Description |
| ----------- | ------------- |
| Element | Component object corresponding to the value of **tag**.|
```js
let newImage = dom.createElement('image')
```
## setAttribute
setAttribute(name: string, value: string): void
Dynamically sets the attributes of this component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| name | string | Yes | Attribute name.|
| value | string | Yes | Attribute value.|
```js
newImage.setAttribute('src', 'common/testImage.jpg')
```
## setStyle
setStyle(name: string, value: string): boolean
Dynamically sets the style of this component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| name | string | Yes | Style name.|
| value | string | Yes | Style value.|
**Return value**
| Type | Description |
| ----------- | ------------- |
| boolean | Returns **true** if the setting is successful; returns **false** otherwise.|
```js
newImage.setStyle('width', '120px')
```
## addChild
addChild(child: Element): void
Adds a dynamically created component to the parent component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| child | Element | Yes | Component object.|
```js
newDiv.addChild(newImage)
```
## Example
```html
<!-- xxx.hml -->
<div class="container">
<div id="parentDiv" class="parent"></div>
<button onclick="appendDiv" class="btn">Dynamically create a <div> component.</button>
<button onclick="appendImage" class="btn">Dynamically create an <image> component and add it to the newly created <div> component.</button>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
align-items: center;
width: 100%;
}
.parent {
flex-direction: column;
}
.btn {
width: 70%;
height: 60px;
margin: 15px;
}
```
```js
// xxx.js
let newDiv = null
let newImage = null
export default {
appendDiv() {
let parent = this.$element('parentDiv')
newDiv = dom.createElement('div')
newDiv.setStyle('width', '150px')
newDiv.setStyle('height', '150px')
newDiv.setStyle('backgroundColor', '#AEEEEE')
newDiv.setStyle('marginTop', '15px')
parent.addChild(newDiv)
},
appendImage() {
newImage = dom.createElement('image')
newImage.setAttribute('src', 'common/testImage.jpg')
newImage.setStyle('width', '120px')
newImage.setStyle('height', '120px')
newDiv.addChild(newImage)
}
}
```
# Basic Usage
# Basic Usage of Custom Components
Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can import a custom component to the host page through **element** as shown in the following code snippet:
Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can introduce a custom component to the host page through **element** as shown in the following code snippet:
```html
<element name='comp' src='../../common/component/comp.hml'></element>
<div>
......@@ -8,8 +9,8 @@ Custom components are existing components encapsulated based on service requirem
</div>
```
The following is an example of using a custom component with **if-else**, which displays **comp1** when **showComp1** is set to **true** and displays **comp2** otherwise.
The following is an example of using a custom component with **if-else**:
```html
<element name='comp1' src='../../common/component/comp1/comp1.hml'></element>
<element name='comp2' src='../../common/component/comp2/comp2.hml'></element>
......@@ -19,18 +20,142 @@ The following is an example of using a custom component with **if-else**:
</div>
```
The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default.
## Custom Events
To bind an event to a custom child component, use the **(on|@)event-name="bindParentVmMethod"** syntax. **this.$emit('eventName', { params: 'passedParameters' })** is used in the child component to trigger the event and pass parameters to the parent component. The parent component then calls the **bindParentVmMethod** API and receives parameters passed by the child component.
> **NOTE**
>
> For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** in the parent component instead of **childrenEvent** used in the child component.
**Example 1 with parameters passed**
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{showObj}}">hello world</text>
</div>
```
```css
/* comp.css */
.item {
width: 700px;
flex-direction: column;
height: 300px;
align-items: center;
margin-top: 100px;
}
.text-style {
font-weight: 500;
font-family: Courier;
font-size: 40px;
}
```
```js
// comp.js
export default {
data: {
showObj: false,
},
childClicked () {
this.$emit('eventType1');
this.showObj = !this.showObj;
},
}
```
The following example describes how to import **comp** to the parent component:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
<comp @event-type1="textClicked"></comp>
</div>
```
```css
/* xxx.css */
.container {
background-color: #f8f8ff;
flex: 1;
flex-direction: column;
align-content: center;
}
```
```js
// xxx.js
export default {
textClicked () {}
}
```
**Example 2 with no parameters passed**
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{ showObj }}">hello world</text>
</div>
```
```js
// comp.js
export default {
childClicked () {
this.$emit('eventType1', { text: 'Receive the parameters from the child component.' });
this.showObj = !this.showObj;
},
}
```
In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/comp/comp.hml'></element>
<div class="container">
<text>Parent component: {{text}}</text>
<comp @event-type1="textClicked"></comp>
</div>
```
```js
// xxx.js
export default {
data: {
text: 'Start'
},
textClicked (e) {
this.text = e.detail.text;
},
}
```
![EventParameters](figures/EventParameters.gif)
## Custom Component Data
- The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default.
- Event binding: Use **(on|@)***child1* syntax to bind a child component event to a custom component. In the child component, use **this.$emit('***child1***', {params:'***parameter to pass***'})** for event triggering and value transferring. In the parent component, call **bindParentVmMethod** method and receive the parameters passed from the child component.
> **NOTE**
>
> For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** instead of **childrenEvent**: **\@children-event="bindParentVmMethod"**.
In the JS file of a custom component, you can define, pass, and process data by declaring fields such as **data**, **props**, and **computed**. For details about how to use **props** and **computed**, see [Data Transfer and Processing](js-components-custom-props.md).
**Table 1** Objects
**Table 1** Custom component data
| Name | Type | Description |
| -------- | --------------- | ---------------------------------------- |
| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).<br>Do not use this attribute and **private** or **public** at the same time.(Rich) |
| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.|
| computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.|
| data | Object \| Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**).<br>Do not use this attribute and **private** or **public** at the same time.|
| props | Array \| Object | Used for communication between components. This attribute can be passed to components through **\<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**) in the name. Currently, **props** does not support functions.|
| computed | Object | Used for pre-processing for reading and setting parameters. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.|
# Event Parameter
A child component can also pass parameters to an upper-layer component through the bound event. The following example describes how to pass parameters through the custom event:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click to View Hidden Text</text>
<text class="text-style" if="{{ showObj }}">hello world</text>
</div>
```
```js
// comp.js
export default {
childClicked () {
this.$emit('eventType1', {text: 'Received parameters from the child component.'});
this.showObj = !this.showObj;
},
}
```
In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/comp/comp.hml'></element>
<div class="container">
<text>Parent component: {{text}}</text>
<comp @event-type1="textClicked"></comp>
</div>
```
```js
// xxx.js
export default {
data: {
text: 'Start'
},
textClicked (e) {
this.text = e.detail.text;
},
}
```
![EventParameters](figures/EventParameters.gif)
# Custom Events
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{showObj}}">hello world</text>
</div>
```
```css
/* comp.css */
.item {
width: 700px;
flex-direction: column;
height: 300px;
align-items: center;
margin-top: 100px;
}
.text-style {
font-weight: 500;
font-family: Courier;
font-size: 40px;
}
```
```js
// comp.js
export default {
data: {
showObj: false,
},
childClicked () {
this.$emit('eventType1');
this.showObj = !this.showObj;
},
}
```
The following example describes how to introduce the child component:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
<comp @event-type1="textClicked"></comp>
</div>
```
```css
/* xxx.css */
.container {
background-color: #f8f8ff;
flex: 1;
flex-direction: column;
align-content: center;
}
```
```js
// xxx.js
export default {
textClicked () {},
}
```
For more information, see [Basic Usage](./js-components-custom-basic-usage.md).
# props<a name="EN-US_TOPIC_0000001173164675"></a>
# Data Transfer and Processing
You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name \(**compProp**\) should be converted to the kebab case format \(**comp-prop**\) when you reference the attribute in an external parent component. You can add **props** to a custom component, and pass the attribute to the child component.
```
## props
You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name (**compProp**) should be converted to the kebab case format (**comp-prop**) when you reference the attribute in an external parent component. The following is sample for adding **props** to a custom component and passing the attribute to the child component.
```html
<!-- comp.hml -->
<div class="item">
<text class="title-style">{{compProp}}</text>
</div>
```
```
```js
// comp.js
export default {
props: ['compProp'],
}
```
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp/comp.hml'></element>
<div class="container">
......@@ -24,21 +27,22 @@ export default {
</div>
```
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**.
> **NOTE**
>
> The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**.
## Default Value<a name="section448655843113"></a>
### Default Value
You can set the default value for a child component attribute via **default**. The default value is used if the parent component does not have **default** set. In this case, the **props** attribute must be in object format instead of an array.
```
```html
<!-- comp.hml -->
<div class="item">
<text class="title-style">{{title}}</text>
</div>
```
```
```js
// comp.js
export default {
props: {
......@@ -49,21 +53,21 @@ export default {
}
```
In this example, a **<text\>** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component.
In this example, a **\<text>** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component.
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp/comp.hml'></element>
<div class="container">
<comp title=" Custom component "></comp>
<comp title="Custom component"></comp>
</div>
```
## Unidirectional Value Transfer<a name="section9681151218247"></a>
### Unidirectional Value Transfer
Data can be transferred only from the parent component to child components. You are not allowed to change the value passed to the child component. However, you can receive the value passed by **props** as a default value in **data**, and then change the **data** value.
```
```js
// comp.js
export default {
props: ['defaultCount'],
......@@ -78,11 +82,11 @@ export default {
}
```
## Monitoring Data Changes by **$watch**<a name="section205821113182114"></a>
### Monitoring Data Changes by **$watch**
To listen for attribute changes in a component, you can use the **$watch** method to add a callback. The following code snippet shows how to use **$watch**:
```
```js
// comp.js
export default {
props: ['title'],
......@@ -95,11 +99,12 @@ export default {
}
```
## Computed Property<a name="section1088954011234"></a>
## computed
To improve the development efficiency, you can use a computed property to pre-process an attribute in a custom component before reading or setting the attribute. In the **computed** field, you can set a getter or setter to be triggered when the attribute is read or written, respectively. The following is an example:
```
```js
// comp.js
export default {
props: ['title'],
......@@ -129,5 +134,4 @@ export default {
}
```
The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value. You need a setter \(such as **notice** in the sample code\) to set the value of the computed property.
The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value (such as **time** defined during initialization in **data**). You need a setter (such as **notice** in the sample code) to set the value of the computed property.
# slot<a name="EN-US_TOPIC_0000001127284840"></a>
# slot
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Default Slot<a name="section68133181214"></a>
You can use the **<slot\>** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows:
## Default Slot
```
You can use the **\<slot>** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style">The following uses the content defined in the parent component.</text>
......@@ -16,8 +18,7 @@ You can use the **<slot\>** tag to create a slot inside a custom component to
```
The following references the custom component:
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
......@@ -27,11 +28,12 @@ The following references the custom component:
</div>
```
## Named Slot<a name="section18337143291211"></a>
When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **<name\>** attribute.
## Named Slot
```
When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **<name>** attribute.
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style">The following uses the content defined in the parent component.</text>
......@@ -41,8 +43,7 @@ When multiple slots are need inside a custom component, you can name them, so th
```
The following references the custom component:
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
......@@ -53,6 +54,6 @@ The following references the custom component:
</div>
```
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>**<name\>** and **<slot\>** do not support dynamic data binding.
> **NOTE**
>
> **\<name>** and **\<slot>** do not support dynamic data binding.
# Style Inheritance
> **NOTE**<br/>
> The APIs of this module are supported since API 9. Updates will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
A custom component has the **inherit-class** attribute, which is defined in the following table.
| Name | Type | Default Value| Mandatory| Description |
| ------------ | ------ | ------ | ---- | ------------------------------------------------------ |
| inherit-class | string | - | No | Class styles inherited from the parent component, seperated by spaces.|
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------ | ---- | ---- | -------------------------------- |
| inherit-class | string | - | No | Class styles inherited from the parent component, separated by spaces.|
To enable a custom component to inherit the styles of its parent component, set the **inherit-calss** attribute for the custom component.
The example below is a code snippet in the HML file of the parent page that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**.
The example below is a code snippet in the HML file of the parent component that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**.
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
......@@ -20,9 +23,10 @@ The example below is a code snippet in the HML file of the parent page that refe
</div>
```
Code snippet in the CSS file of the parent page:
```html
// xxx.css
Code snippet in the CSS file of the parent component:
```css
/* xxx.css */
.parent-class1 {
background-color:red;
border:2px;
......@@ -34,6 +38,7 @@ Code snippet in the CSS file of the parent page:
```
Code snippet in the HML file of the custom component, where **parent-class1** and **parent-class2** are styles inherited from the parent component:
```html
<!--comp.hml-->
<div class="item">
......
......@@ -52,7 +52,7 @@ Not supported
```
![zh-cn_image_0000001173324703](figures/en-us_image_0000001173324703.gif)
![en-us_image_0000001173324703](figures/en-us_image_0000001173324703.gif)
```html
......@@ -68,7 +68,7 @@ Not supported
```
![zh-cn_image_0000001167662852](figures/en-us_image_0000001167662852.gif)
![en-us_image_0000001167662852](figures/en-us_image_0000001167662852.gif)
```html
......@@ -83,7 +83,7 @@ Not supported
```
![zh-cn_image_0000001127284938](figures/en-us_image_0000001127284938.gif)
![en-us_image_0000001127284938](figures/en-us_image_0000001127284938.gif)
```html
......@@ -117,4 +117,4 @@ Not supported
```
![animate-4](figures/animate-4.gif)
![en-us_image_0000001127125126](figures/en-us_image_0000001127125126.gif)
# GridCol
The **\<GridCol>** component must be used as a child component of the [GridRow](ts-container-gridrow.md) container.
The **\<GridCol>** component must be used as a child component of the **[\<GridRow>](ts-container-gridrow.md)** container.
> **NOTE**
>
......@@ -16,10 +16,10 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
## Attributes
......
......@@ -22,20 +22,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| sticky | [Sticky](#sticky)| Sticky effect of the list item.<br>Default value: **Sticky.None**|
| editable | boolean \| [EditMode](#editmode)| Whether to enter editing mode, where the list item can be deleted or moved.<br>Default value: **false**|
| sticky<sup>(deprecated)</sup> | [Sticky](#stickydeprecated) | Sticky effect of the list item.<br>Default value: **Sticky.None**<br>This API is deprecated since API version 9. You are advised to use **sticky** of the [\<List>](ts-container-list.md#attributes) component. |
| editable<sup>(deprecated)</sup> | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | Whether the current list item is selectable by mouse drag.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<List>** container.<br>Default value: **true**|
| swipeAction<sup>9+</sup> | {<br>start?: CustomBuilder,<br>end?:CustomBuilder,<br>edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),<br>} | Component displayed when the list item is swiped out from the screen edge.<br>- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).<br>- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).<br>- **edgeEffect**: scroll effect.<br>|
## Sticky
## Sticky<sup>(deprecated)</sup>
This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\<List>** component.
| Name| Description|
| -------- | -------- |
| None | The list item is not sticky.|
| Normal | The list item is sticky with no special effects.|
| Opacity | The list item is sticky with opacity changes.|
## EditMode
## EditMode<sup>(deprecated)</sup>
This API is deprecated since API version 9.
| Name | Description |
| ------ | --------- |
| None | The editing operation is not restricted. |
......@@ -63,41 +64,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
@Component
struct ListItemExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State editFlag: boolean = false
build() {
Column() {
List({ space: 20, initialIndex: 0 }) {
ListItem() {
Text('sticky:Normal , click me edit list')
.width('100%').height(40).fontSize(12).fontColor(0xFFFFFF)
.textAlign(TextAlign.Center).backgroundColor(0x696969)
.onClick(() => {
this.editFlag = !this.editFlag
})
}.sticky(Sticky.Normal)
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.editable(this.editFlag)
}, item => item)
}
.editMode(true)
.onItemDelete((index: number) => {
console.info(this.arr[index - 1] + 'Delete')
this.arr.splice(index - 1,1)
this.editFlag = false
return true
}).width('90%')
}, item => item)
}.width('90%')
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
}
}
```
![en-us_image_0000001257138339](figures/en-us_image_0000001257138339.gif)
![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif)
```ts
// xxx.ets
......
......@@ -46,7 +46,7 @@ struct PositionExample1 {
.fontSize(16)
.backgroundColor(0xFFE4C4)
// To arrange the child components from left to right, set direction of the parent container to Direction.Auto or Direction.Ltr, or leave it to the default value.
// To arrange the child components from left to right, set direction of the parent container to Direction.Ltr.
Text('direction').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
......@@ -55,19 +55,19 @@ struct PositionExample1 {
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
}
.width('90%')
.direction(Direction.Auto)
.direction(Direction.Ltr)
// To arrange the child components from right to left, set direction of the parent container to Direction.Rtl.
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3).textAlign(TextAlign.End)
Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C).textAlign(TextAlign.End)
Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3).textAlign(TextAlign.End)
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C).textAlign(TextAlign.End)
}
.width('90%')
.direction(Direction.Rtl)
}
}
.width('100%').margin({ top: 5 }).direction(Direction.Rtl)
.width('100%').margin({ top: 5 })
}
}
```
......
......@@ -12,14 +12,14 @@ The show/hide event is triggered when a component is mounted or unmounted from t
| Name | Bubbling Supported| Description |
| ------------------------------------------------ | -------- | -------------------------- |
| onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.|
| onDisappear(event: () =&gt; void) | No | Triggered when the component is hidden. |
| onDisAppear(event: () =&gt; void) | No | Triggered when the component is hidden.|
## Example
```ts
// xxx.ets
import prompt from '@ohos.prompt'
import promptAction from '@ohos.promptAction'
@Entry
@Component
......@@ -38,14 +38,14 @@ struct AppearExample {
Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
.onAppear(() => {
this.changeAppear = 'Hide Text'
prompt.showToast({
promptAction.showToast({
message: 'The text is shown',
duration: 2000
})
})
.onDisAppear(() => {
this.changeAppear = 'Show Text'
prompt.showToast({
promptAction.showToast({
message: 'The text is hidden',
duration: 2000
})
......
......@@ -37,6 +37,8 @@
- [RDB Error Codes](errorcode-data-rdb.md)
- [Distributed KV Store Error Codes](errorcode-distributedKVStore.md)
- [Preferences Error Codes](errorcode-preferences.md)
- File Management
- [File Management Error Codes](errorcode-filemanagement.md)
- Network Management
- [Upload and Download Error Codes](errorcode-request.md)
- Connectivity
......
# File Management Error Codes
The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes
## Basic File I/O Error Codes
### 13900001 Operation Not Permitted
**Error Message**
Operation not permitted
**Possible Causes**
The current operation on the file is not allowed.
**Solution**
Check the permission for the file.
### 13900002 File or Directory Not Exist
**Error Message**
No such file or directory
**Possible Causes**
The file or directory does not exist.
**Solution**
Check whether the file directory exists.
### 13900003 Process Not Exist
**Error Message**
No such process
**Possible Causes**
The process does not exist.
**Solution**
1. Check whether the process is killed unexpectedly.
2. Check whether the service related to the process has started.
### 13900004 System Call Interrupted
**Error Message**
Interrupted system call
**Possible Causes**
The system call is interrupted by another thread.
**Solution**
1. Check the multi-thread code logic.
2. Invoke the system call again.
### 13900005 I/O Error
**Error Message**
I/O error
**Possible Causes**
The I/O request is invalid.
**Solution**
Initiate the I/O request again.
### 13900006 Device or Address Not Exist
**Error Message**
No such device or address
**Possible Causes**
The device information or address is incorrect.
**Solution**
Check that the device information or address is correct.
### 13900007 Long Parameter List
**Error Message**
Arg list too long
**Possible Causes**
The parameter list is too long.
**Solution**
Reduce the number of parameters.
### 13900008 Invalid File Descriptor
**Error Message**
Bad file descriptor
**Possible Causes**
This file descriptor is closed.
**Solution**
Check whether the file descriptor is closed.
### 13900009 Child Process Not Exist
**Error Message**
No child processes
**Possible Causes**
The child process cannot be created.
**Solution**
Check the maximum number of processes in the system.
### 13900010 Resource Unavailable
**Error Message**
Try again
**Possible Causes**
The resources are blocked.
**Solution**
Request resources.
### 13900011 Memory Overflow
**Error Message**
Out of memory
**Possible Causes**
A memory overflow occurs.
**Solution**
1. Check the memory overhead.
2. Control the memory overhead.
### 13900012 Permission Denied
**Error Message**
Permission denied
**Possible Causes**
1. You do not have the permission to operate the file.
2. The file sandbox path is incorrect.
**Solution**
1. Check that you have the permission to operate the file.
2. Check that the file sandbox path is correct.
### 13900013 Incorrect Address
**Error Message**
Bad address
**Possible Causes**
The address is incorrect.
**Solution**
Check that the address is correct.
### 13900014 Device or Resource Not Available
**Error Message**
Device or resource busy
**Possible Causes**
The requested resource is unavailable.
**Solution**
Request the resource again.
### 13900015 File Already Exists
**Error Message**
File exists
**Possible Causes**
The file to be created already exists.
**Solution**
Check whether the file path is correct.
### 13900016 Invalid Cross-Device Link
**Error Message**
Cross-device link
**Possible Causes**
The link between devices is incorrect.
**Solution**
Check the devices and create the link correctly.
### 13900017 Device Not Exist
**Error Message**
No such device
**Possible Causes**
The device is not identified.
**Solution**
Check the connection to the target device.
### 13900018 Invalid Directory
**Error Message**
Not a directory
**Possible Causes**
The specified directory is invalid.
**Solution**
Check that the directory is correct.
### 13900019 The Specified Object Is a Directory
**Error Message**
Is a directory
**Possible Causes**
The specified object is a directory.
**Solution**
Check that the specified data is correct.
### 13900020 Invalid Parameter
**Error Message**
Invalid argument
**Possible Causes**
Invalid input parameter is detected.
**Solution**
Check that the input parameters are valid.
### 13900021 Too Many File Descriptors Opened
**Error Message**
File table overflow
**Possible Causes**
The number of file descriptors opened has reached the limit.
**Solution**
Close the file descriptors that are no longer required.
### 13900022 Too Many Files Opened
**Error Message**
Too many open files
**Possible Causes**
The number of files opened has reached the limit.
**Solution**
Close the files that are not required.
### 13900023 Text File Not Respond
**Error Message**
Text file busy
**Possible Causes**
The executable file of the program is in use.
**Solution**
Close the program that is being debugged.
### 13900024 File Oversized
**Error Message**
File too large
**Possible Causes**
The file size exceeds the limit.
**Solution**
Check whether the file size exceeds the limit.
### 13900025 Insufficient Space on the Device
**Error Message**
No space left on device
**Possible Causes**
The device storage space is insufficient.
**Solution**
Clear the space of the device.
### 13900026 Invalid Shift
**Error Message**
Illegal seek
**Possible Causes**
Seek is used in pipe or FIFO.
**Solution**
Check the use of seek.
### 13900027 Read-Only File System
**Error Message**
Read-only file system
**Possible Causes**
The file system allows read operations only.
**Solution**
Check whether the file is read-only.
### 13900028 Links Reach the Limit
**Error Message**
Too many links
**Possible Causes**
The number of links to the file has reached the limit.
**Solution**
Delete the links that are no longer required.
### 13900029 Resource Deadlock
**Error Message**
Resource deadlock would occur
**Possible Causes**
Resource deadlock occurs.
**Solution**
Terminate the deadlock process.
### 13900030 Long File Name
**Error Message**
Filename too Long
**Possible Causes**
The length of the path or file name exceeds the limit.
**Solution**
Modify the path or file name.
### 13900031 Function Not Implemented
**Error Message**
Function not implemented
**Possible Causes**
The function is not supported by the system.
**Solution**
Check the system version and update the system if required.
### 13900032 Directory Not Empty
**Error Message**
Directory not empty
**Possible Causes**
The specified directory is not empty.
**Solution**
1. Check the directory.
2. Ensure that the directory is empty.
### 13900033 Too Many Symbol Links
**Error Message**
Too many symbolic links
**Possible Causes**
There are too many symbolic links.
**Solution**
Delete unnecessary symbol links.
### 13900034 Operation Blocked
**Error Message**
Operation would block
**Possible Causes**
The operation is blocked.
**Solution**
Perform the operation again.
### 13900035 Invalid File Descriptor
**Error Message**
Invalid request desecriptor
**Possible Causes**
The requested file descriptor is invalid.
**Solution**
Check that the file descriptor is valid.
### 13900036 Target Is Not a Character Stream Device
**Error Message**
Device not a stream
**Possible Causes**
The device pointed to by the file descriptor is not a character stream device.
**Solution**
Check whether the file descriptor points to a stream device.
### 13900037 No Data Available
**Error Message**
No data available
**Possible Causes**
The required data is not available.
**Solution**
Request the data again.
### 13900038 Value Mismatches the Data Type
**Error Message**
Value too large for defined data type
**Possible Causes**
The specified value is out of the range defined for the data type.
**Solution**
Modify the data type.
### 13900039 File Descriptor Corrupted
**Error Message**
File descriptor in bad state
**Possible Causes**
The file descriptor is corrupted.
**Solution**
Check that the file descriptor is valid.
### 13900040 System Call Interrupted
**Error Message**
Interrupted systen call should be restarted
**Possible Causes**
The system call is interrupted.
**Solution**
Invoke the system call again.
### 13900041 Disk Quota Exceeded
**Error Message**
Quota exceeded
**Possible Causes**
The disk space is insufficient.
**Solution**
Clear disk space.
### 13900042 Unknown Error
**Error Message**
Unknown error
**Possible Causes**
The error is unidentified.
**Solution**
1. Call the API again.
2. Restart the service.
## User Data Management Error Codes
### 14000001 Invalid File Name
**Error Message**
Invalid display name
**Possible Causes**
The file name contains invalid characters.
**Solution**
Modify the file name.
### 14000002 Invalid URI
**Error Message**
Invalid uri
**Possible Causes**
The URI is invalid.
**Solution**
Use the obtained URI.
### 14000003 Invalid File Name Extension
**Error Message**
Invalid file extension
**Possible Causes**
The file name extension is incorrect.
**Solution**
Modify the file name extension.
### 14000004 File in Recycle Bin
**Error Message**
File has been put into trash bin
**Possible Causes**
The file is moved to the Recycle Bin.
**Solution**
Check whether the file is in the Recycle Bin.
## Spatial Statistics Error Codes
### 13600001 IPC Failed
**Error Message**
IPC error
**Possible Causes**
The called service does not exist.
**Solution**
Check whether the service is started.
### 13600002 File System Not Supported
**Error Message**
Not supported filesystem
**Possible Causes**
The file system is not supported.
**Solution**
Use a supported file system.
### 13600003 Mount Failed
**Error Message**
Failed to mount
**Possible Causes**
The **mount** command fails.
**Solution**
Remove the card and run the **mount** command again.
### 13600004 Unmount Failed
**Error Message**
Failed to unmount
**Possible Causes**
The device does not respond.
**Solution**
Check whether the file is being used. If yes, kill the thread that uses the file.
### 13600005 Incorrect Volume State
**Error Message**
Incorrect volume state
**Possible Causes**
The volume state is incorrect.
**Solution**
Check whether the current volume state is correct.
### 13600006 Failed to Create a Directory or Node
**Error Message**
Prepare directory or node error
**Possible Causes**
The directory or node to be created already exists.
**Solution**
Check whether the directory or node to be created already exists.
### 13600007 Failed to Delete a Directory or Node
**Error Message**
Delete directory or node error
**Possible Causes**
The specified directory or node has been deleted.
**Solution**
Check whether the specified directory or node exists.
### 13600008 Object Not Exist
**Error Message**
No such object
**Possible Causes**
1. The specified volume ID is incorrect.
2. The specified bundle name is incorrect.
**Solution**
1. Check whether the specified volume exists.
2. Check whether the specified bundle name exists.
### 13600009 Invalid User ID
**Error Message**
User id out of range
**Possible Causes**
The specified user ID is incorrect.
**Solution**
Check that the user ID is correct.
## User File Access Error Codes
### 14300001 IPC Failed
**Error Message**
IPC error
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300002 Incorrect URI Format
**Error Message**
Invalid uri
**Possible Causes**
The URI is invalid.
**Solution**
Check that the URI is in correct format.
### 14300003 Failed to Obtain the Server Ability Information
**Error Message**
Fail to get fileextension info
**Possible Causes**
The BMS interface is abnormal.
**Solution**
Check for basic system capability errors.
### 14300004 Incorrect Result Returned by js-server
**Error Message**
Get wrong result
**Possible Causes**
The data returned by the server is incorrect.
**Solution**
Check the data returned by the server.
### 14300005 Failed to Register Notify
**Error Message**
Fail to register notification
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300006 Failed to Unregister Notify
**Error Message**
Fail to remove notification
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300007 Failed to Initialize the Notify Agent
**Error Message**
Fail to init notification agent
**Possible Causes**
The specified Notify agent has not been registered.
**Solution**
Check whether the specified Notify agent is registered.
### 14300008 Failed to Notify the Agent
**Error Message**
Fail to notify agent
**Possible Causes**
1. The service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check whether the client is normal.
......@@ -8,7 +8,7 @@
- User Authentication
- [User Authentication Overview](userauth-overview.md)
- [User Authentication Development](userauth-guidelines.md)
- Key Management
- HUKS
- [HUKS Overview](huks-overview.md)
- [HUKS Development](huks-guidelines.md)
- Crypto Framework
......@@ -20,3 +20,4 @@
- hapsigner
- [hapsigner Overview](hapsigntool-overview.md)
- [hapsigner Guide](hapsigntool-guidelines.md)
- [HarmonyAppProvision Configuration File](app-provision-structure.md)
\ No newline at end of file
......@@ -2,58 +2,46 @@
## When to Use
In this example, the app requires the **ohos.permission.PERMISSION1** and **ohos.permission.PERMISSION2** permissions to implement core functions.
The [Ability Privilege Level (APL)](accesstoken-overview.md#app-apls) of an application can be **normal**, **system_basic**, or **system_core**. The default APL is **normal**. The [permission types](accesstoken-overview.md#permission-types) include **system_grant** and **user_grant**. For details about the permissions for apps, see the [App Permission List](permission-list.md).
- The ability privilege level (APL) of the app is **normal**.
- The level of **ohos.permission.PERMISSION1** is **normal**, and the authorization mode is **system_grant**.
- The level of **ohos.permission.PERMISSION2** is **system_basic**, and the authorization mode is **user_grant**.
This document describes the following operations:
> **CAUTION**
>
> In this scenario, the required permissions include a **user_grant** permission. You can check whether the caller has the required permission through permission verification.
>
> If the permission verification result indicates that the app has not obtained that permission, dynamic user authorization is required.
- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file)
- [Declaring Permissions in the ACL](#declaring-permissions-in-the-acl)
- [Requesting User Authorization](#requesting-user-authorization)
- [Pre-Authorizing user_grant Permissions](#pre-authorizing-user_grant-permissions)
## Available APIs
## Declaring Permissions in the Configuration File
The table below lists only the API used in this guide. For more information, see [Ability Access control](../reference/apis/js-apis-ability-context.md).
During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see Application Models. The application bundle and configuration file vary with the application model.
| API | Description |
| ------------------------------------------------------------ | --------------------------------------------------- |
| requestPermissionsFromUser(permissions: Array&lt;string&gt;, requestCallback: AsyncCallback&lt;PermissionRequestResult&gt;) : void; | Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result.|
> **NOTE**<br>The default APL of an application is **normal**. When an application needs the **system_basic** or **system_core** APL, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-permissions-in-the-acl).
## Declaring Permissions
The following table describes the fields in the configuration file.
Declare the permissions required by the app one by one in the project configuration file. The app cannot obtain the permissions that are not declared in the configuration file. The ability framework provides two models: Feature Ability (FA) model and stage model. For more information, see [Ability Framework Overview](../ability/ability-brief.md).
| Field | Mandatory| Description |
| --------- | -------- | ------------------------------------------------------------ |
| name | Yes | Name of the permission. |
| reason | No | Reason for requesting the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| usedScene | No | Application scenario of the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| abilities | No | Abilities that require the permission. The value is an array.<br>**Applicable model**: stage|
| ability | No | Abilities that require the permission. The value is an array.<br>**Applicable model**: FA|
| when | No | Time when the permission is used. <br>Value:<br>- **inuse**: The permission applies only to a foreground application.<br>- **always**: The permission applies to both the foreground and background applications.|
Note that the app bundle structure and configuration file vary with the ability framework model.
The following table describes the tags in the configuration file.
| Field | Description |
| --------- | ------------------------------------------------------------ |
| name | Name of the permission. |
| reason | Reason for requesting the permission. This field is mandatory for a user_grant permission.|
| usedScene | Scenario of the permission. This field is mandatory for a user_grant permission.|
| ability | Abilities that use the permission. The value is an array.<br>**Applicable model**: FA |
| abilities | Abilities that use the permission. The value is an array.<br>**Applicable model**: stage |
| when | Time when the permission is used. The value can be **inuse** (the permission can be used only in the foreground) or **always** (the permission can be used in foreground and background).|
### FA Model
For the apps based on the FA model, declare the required permissions in the **config.json** file.
### Stage Model
**Example**
If the application is based on the stage model, declare the permissions in [**module.json5**](../quick-start/module-configuration-file.md).
```json
{
"module" : {
"reqPermissions":[
// ...
"requestPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"ability": [
"abilities": [
"FormAbility"
],
"when":"inuse"
......@@ -63,7 +51,7 @@ For the apps based on the FA model, declare the required permissions in the **co
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"ability": [
"abilities": [
"FormAbility"
],
"when":"always"
......@@ -74,21 +62,20 @@ For the apps based on the FA model, declare the required permissions in the **co
}
```
### Stage Model
For the apps based on the stage model, declare the required permissions in the **module.json5** file.
### FA Model
**Example**
If the application is based on the FA model, declare the required permissions in **config.json**.
```json
{
"module" : {
"requestPermissions":[
// ...
"reqPermissions":[
{
"name" : "ohos.permission.PERMISSION1",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"ability": [
"FormAbility"
],
"when":"inuse"
......@@ -98,7 +85,7 @@ For the apps based on the stage model, declare the required permissions in the *
"name" : "ohos.permission.PERMISSION2",
"reason": "$string:reason",
"usedScene": {
"abilities": [
"ability": [
"FormAbility"
],
"when":"always"
......@@ -109,60 +96,152 @@ For the apps based on the stage model, declare the required permissions in the *
}
```
## Declaring the ACL
The permission level of **ohos.permission.PERMISSION2** is **system_basic**, which is higher than the app's APL. In this case, use the ACL.
## Declaring Permissions in the ACL
In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher that the app's APL in the app's profile. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md).
If an application of the **normal** level requires permissions corresponding to the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL.
For example, declare the required permission in the **acls** field:
For example, if an application needs to access audio files of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the related permissions to the **acl** field in the [HarmonyAppProvision configuration file](app-provision-structure.md).
```json
{
"acls": {
"allowed-acls": [
"ohos.permission.PERMISSION2"
// ...
"acls":{
"allowed-acls":[
"ohos.permission.WRITE_AUDIO",
"ohos.permission.CAPTURE_SCREEN"
]
}
}
```
## Applying for the user_grant Permission
## Requesting User Authorization
If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from users. A permission verification is performed first to determine whether the current invoker has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example.
<img src="figures/permission-read_calendar.png" width="40%;" />
After the permissions are declared, the system grants the system_grant permission during the installation of the app. The user_grant permission must be authorized by the user.
> **NOTE**<br>Each time before an API protected by a permission is accessed, the **requestPermissionsFromUser()** API will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent.
Therefore, before allowing the app to call the API protected by the **ohos.permission.PERMISSION2** permission, the system needs to verify whether the app has the permission to do so.
### Stage Model
Example: Request the permission to read calendar information for an app.
If the verification result indicates that the app has the permission, the app can access the target API. Otherwise, the app needs to request user authorization and then proceeds based on the authorization result. For details, see [Access Control Overview](accesstoken-overview.md).
1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file).
> **CAUTION**
>
> The permission authorized by a user is not permanent, because the user may revoke the authorization at any time. Each time before the API protected by the permission is called, call **requestPermissionsFromUser()** to request the permission.
2. Call **requestPermissionsFromUser()** in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of **requestPermissionsFromUser()** indicates whether the application has the target permission. If yes, the target API can be called normally.
## Example
Request user authorization in UIAbility.
The procedure for requesting user authorization is as follows:
```typescript
import UIAbility from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { Permissions } from '@ohos.abilityAccessCtrl';
1. Obtain the ability context.
2. Call **requestPermissionsFromUser()** to request user authorization. The API determines whether to display a dialog box to request user authorization based on whether the app has the permission.
3. Check whether the app has the permission based on the return value. If the app has the permission, the API can be invoked.
export default class EntryAbility extends UIAbility {
// ...
onWindowStageCreate(windowStage: Window.WindowStage) {
// Main window is created, set main page for this ability
let context = this.context;
let AtManager = abilityAccessCtrl.createAtManager();
// The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
AtManager.requestPermissionsFromUser(context, permissions).then((data) => {
console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
let grantStatus: Array<number> = data.authResults;
if (grantStatus[0] === -1) {
// The authorization fails.
} else {
// The authorization is successful.
}
}).catch((err) => {
console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
})
// ...
}
}
```
Request user authorization on the UI.
```typescript
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import { Permissions } from '@ohos.abilityAccessCtrl';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
reqPermissions() {
let context = getContext(this) as common.UIAbilityContext;
let AtManager = abilityAccessCtrl.createAtManager();
// The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
const permissions: Array<Permissions> = ['ohos.permission.READ_CALENDAR'];
AtManager.requestPermissionsFromUser(context, permissions).then((data) => {
console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
let grantStatus: Array<number> = data.authResults;
if (grantStatus[0] === -1) {
// The authorization fails.
} else {
// The authorization is successful.
}
}).catch((err) => {
console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
})
}
// Page display.
build() {
// ...
}
}
```
### FA Model
Call [requestPermissionsFromUser()](../reference/apis/js-apis-inner-app-context.md#contextrequestpermissionsfromuser7) to request user authorization.
```js
// OnWindowStageCreate of the ability
onWindowStageCreate() {
var context = this.context
// onWindowStageCreate() of Ability
onWindowStageCreate() {
let context = this.context;
let array:Array<string> = ["ohos.permission.PERMISSION2"];
// requestPermissionsFromUser determines whether to display a dialog box based on the permission authorization status.
// The return value of requestPermissionsFromUser determines whether to display a dialog box to request user authorization.
context.requestPermissionsFromUser(array).then(function(data) {
console.log("data type:" + typeof(data));
console.log("data:" + data);
console.log("data permissions:" + data.permissions);
console.log("data result:" + data.authResults);
console.log("data:" + JSON.stringify(data));
console.log("data permissions:" + JSON.stringify(data.permissions));
console.log("data result:" + JSON.stringify(data.authResults));
}, (err) => {
console.error('Failed to start ability', err.code);
});
}
}
```
## Pre-Authorizing user_grant Permissions
By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed apps, you can pre-authroize the permissions, for example, the **ohos.permission.MICROPHONE** permission, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the **user_grant** permissions in the file are granted. The **install_list_permissions.json** file contains the following fields:
- **bundleName**: bundle name of the application.
- `app_signature`: fingerprint information of the application. For details, see [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#configuration-in-install-list-capabilityjson).
- **permissions**: **name** specifies the name of the **user_grant** permission to pre-authorize. **userCancellable** specifies whether the user can revoke the pre-authorization. The value **true** means the user can revoke the pre-authorization; the vaue **false** means the opposite.
> **NOTE**<br>This file is available only for preinstalled applications.
```json
[
// ...
{
"bundleName": "com.example.myapplication", // Bundle Name.
"app_signature": ["****"], // Fingerprint information.
"permissions":[
{
"name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
"userCancellable": false // The user cannot revoke the authorization.
},
{
"name": "ohos.permission.PERMISSION_X", // Permission to pre-authorize.
"userCancellable": true // The user can revoke the authorization.
}
]
}
]
```
> **NOTE**<br>
> For details about the APIs, see [AbilityContext](../reference/apis/js-apis-ability-context.md).
<!--no_check-->
\ No newline at end of file
......@@ -2,14 +2,14 @@
OpenHarmony AccessTokenManager (ATM) implements unified app permission management based on access tokens.
By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions.
By default, apps can access limited system resources. However, to provide extended features, an app may need to access excess data (including personal data) and functions of the system or another app. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions.
App permissions are used to protect the following objects:
- Data: personal data (such as photos, contacts, calendar, and location), device data (such as device ID, camera, and microphone), and app data.
- Functions: device functions (such as making calls, sending SMS messages, and connecting to the Internet) and app functions (such as displaying windows and creating shortcuts).
Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions.
Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize app behavior and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions.
Currently, ATM verifies app permissions based on the token identity (token ID). A token ID identifies an app. ATM manages app permissions based on the app's token ID.
......@@ -17,13 +17,13 @@ Currently, ATM verifies app permissions based on the token identity (token ID).
Observe the following principles for permission management:
- Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app.
- Provide clear description about the functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are needed. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app.
- Use the principle of least authority for user permissions. Allow only necessary permissions for service functions.
- When an app is started for the first time, avoid frequently displaying dialog boxes to request multiple permissions. Allow the app to apply for the permission only when it needs to use the corresponding service function.
- If a user rejects to grant a permission, the user can still use functions irrelevant to this permission and can register and access the app.
- Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function.
- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed for apps currently.
- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed currently.
## Permission Workflows
......@@ -50,7 +50,9 @@ The figure below illustrates the process.
3. A low-APL app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl).
### Permission Verification
To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. The API can be called only after the permission verification is successful.
To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect an API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission.
The API can be called only after the permission verification is successful.
The figure below shows the permission verification process.
......@@ -58,7 +60,7 @@ The figure below shows the permission verification process.
1: An app permission can be used to control the access to an API that has sensitive data involved or security threats on the core abilities.
2: Select the permission from the [App Permission List](permission-list.md). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API.
2: The API can be protected by a permission in the [ACL](#acl). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API.
3: Use **verifyAccessToken()** to check whether the caller has the required permission. For details, see [Permission Verification Guide](permission-verify-guidelines.md).
......@@ -88,7 +90,7 @@ Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificat
The following is an example.
This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md).
This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](app-provision-structure.md).
```json
{
......@@ -123,7 +125,7 @@ The permissions open to apps vary with the permission level. The permission leve
The system_core permission allows access to core resources of the OS. These resources are underlying core services of the system. If these resources are corrupted, the OS cannot run properly.
The system_core permissions are not open to third-party apps currently.
The system_core permissions are not open to third-party apps.
## Permission Types
......@@ -131,19 +133,19 @@ Permissions can be classified into the following types based on the authorizatio
- **system_grant**
The app permissions are authorized by the system. This type of apps cannot access user or device sensitive information. The allowed operations have minor impact on the system or other apps.
The app permissions are authorized by the system. Apps granted with this type of permission cannot access user or device sensitive information, and the operations allowed for them have minor impact on the system or other apps.
For a system_grant app, the system automatically grants the required permissions to the app when the app is installed. The system_grant permission list must be presented to users on the details page of the app in the app store.
For a system_grant app, the system automatically grants the required permissions to the app when the app is installed. The system_grant permission list must be presented to users on the details page of the app in the app market.
- **user_grant**
The app permissions must be authorized by users. This type of apps may access user or device sensitive information. The allowed operations may have a critical impact on the system or other apps.
The app permissions must be authorized by users. Apps granted with this type of permissions may access user or device sensitive information, and the operations allowed for them may have a critical impact on the system or other apps.
This type of permissions must be declared in the app installation package and authorized by users dynamically during the running of the app. The app has the permission only after user authorization.
For example, in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions.
For example, as described in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions.
The user_grant permission list must also be presented on the details page of the app in the app store.
The user_grant permission list must also be presented on the details page of the app in the app market.
### Authorization Processes
......@@ -173,7 +175,7 @@ The procedure is as follows:
**Precautions**
- Check the app's permission each time before the operation requiring the permission is performed.
- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md).
- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) API. This API returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md).
- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call an API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the permission. The user will determine whether to grant the permission based on the running context of the app.
- The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission.
......@@ -190,15 +192,15 @@ The APL of app A is **normal**. App A needs to have permission B (system_basic l
In this case, you can use the ACL to grant permission B to app A.
For details, see [Using the ACL](#using-the-acl).
For details about whether a permission can be enabled through the ACL, see the [App Permission List](permission-list.md).
For details about whether a permission can be enabled through the ACL, see [App Permission List](permission-list.md).
### Using the ACL
If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permission required.
If the permission required by an app has a higher level than the app's APL, you can use the ACL to grant the permission required.
In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL.
That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same.
That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-permissions-in-the-acl) in the app's profile. The subsequent steps of authorization are the same.
**NOTICE**
......@@ -216,4 +218,4 @@ When developing an app installation package, you must declare the ACL in the **a
}
```
For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md).
For details about the fields in the profile, see [HarmonyAppProvision Configuration File](app-provision-structure.md).
......@@ -4,19 +4,19 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file
## Configuration File Internal Structure
The **HarmonyAppProvision** file consists of several parts, which are described in the table below.
**Table 1** Internal structure of the HarmonyAppProvision file
| Name | Description | Data Type| Mandatory| Initial Value Allowed|
| Name | Description | Data Type| Yes | 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|
| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No|
| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No|
| issuer | Issuer of the **HarmonyAppProvision** file. | 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 information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No| 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 | Yes |
| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | Yes |
| debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | Yes |
| app-privilege-capabilities | Privilege information required by the application bundle. For details, see the [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md). | String array| No | Yes |
An example of the **HarmonyAppProvision** file is as follows:
```json
......@@ -47,6 +47,7 @@ An example of the **HarmonyAppProvision** file is as follows:
"device-id-type": "udid",
"device-ids": ["string"]
},
"app-privilege-capabilities":["AllowAppUsePrivilegeExtension"],
"issuer": "OpenHarmony"
}
......@@ -54,46 +55,57 @@ An example of the **HarmonyAppProvision** file is as follows:
### Internal Structure of the validity Object
| Name | Description | Data Type| Mandatory| Initial Value Allowed|
| 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|
| 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 |
| developer-id | Unique ID of the developer.| String | Yes | No |
| development-certificate | Information about the [debug certificate](hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No |
| distribution-certificate | Information about the [release certificate](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)](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** (normal application). Only system applications are allowed to call system APIs. If a normal application calls a system API, the call cannot be successful or the application may run abnormally.| 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
The **acls** object contains the [ACL](accesstoken-overview.md) configured for your application. It should be noted that you still need to add the ACL information to the **requestPermissions** attribute in the application configuration file.
| Name | Description | Data Type| Mandatory| Initial Value Allowed|
| 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.
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 add the ACL information to the **requestPermissions** attribute in the application configuration file.
**Table 5** Internal structure of the permissions object
| Name | Description | Data Type| Mandatory| Initial Value Allowed|
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- |
| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No| No |
| restricted-permissions | [Restricted permissions](accesstoken-overview.md) required for your application.| String array | No | No |
### Internal Structure of the debug-info Object
The **debug-info** object contains debugging 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|
| 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 |
| 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 | Optional| No |
## Modifying the HarmonyAppProvision Configuration File
When a development project is created, the default application type is **hos_normal_app** and the default APL level is **normal**.
To enable the application to use system APIs, you need to change the **app-feature** field to **hos_system_app** (system application). To apply for high-level permissions, you need to modify fields such as **apl** and **acl**. For details, see [Access Control Overview](accesstoken-overview.md).
To modify the HarmonyAppProvision configuration file, perform the following steps:
1. Open the directory where the OpenHarmony SDK is located. (You can choose **File** > **Settings** > **OpenHarmony SDK** on the menu bar of DevEco Studio to query the directory.)
2. In the SDK directory, go to the **Toolchains** > {Version} > **lib** directory and open the **UnsgnedReleasedProfileTemplate.json** file.
3. Modify the related fields as required.
After modifying the configuration file, [sign the application](hapsigntool-guidelines.md).
......@@ -45,10 +45,10 @@ You can use the $r syntax in the application development files .hml and .js to f
Example of res-defaults.json:<br/>
```
```json
{
strings: {
hello: 'hello world'
"strings": {
"hello": "hello world"
}
}
```
......@@ -57,7 +57,7 @@ Example of res-defaults.json:<br/>
resources/res-dark.json:
```
```json
{
"image": {
"clockFace": "common/dark_face.png"
......@@ -70,7 +70,7 @@ resources/res-dark.json:
resources/res-defaults.json:
```
```json
{
"image": {
"clockFace": "common/face.png"
......@@ -81,7 +81,7 @@ resources/res-defaults.json:
}
```
```
```html
<!-- xxx.hml -->
<div style="background-color: {{ $r('colors.background') }}">
<image src="{{ $r('image.clockFace') }}"></image>
......
......@@ -13,7 +13,7 @@ The ES6 syntax is supported.
Import functionality modules.
```js
import router from '@system.router';
import router from '@ohos.router';
```
- Code reference
......
......@@ -62,7 +62,7 @@ In the [animateMotion](../reference/arkui-js/js-components-svg-animatemotion.md)
## animateTransform Animation
In the [animateMotion](../reference/arkui-js/js-components-svg-animatetransform.md) child component of the **\<svg>** component, set attributeName to bind the corresponding attribute to the **transform** attribute, and set **type** to the animation type, **from** to the start value, and **to** to the end value.
In the [animateTransform](../reference/arkui-js/js-components-svg-animatetransform.md) child component of the **\<svg>** component, set attributeName to bind the corresponding attribute to the **transform** attribute, and set **type** to the animation type, **from** to the start value, and **to** to the end value.
```html
......
......@@ -6,7 +6,7 @@ Set the transform attribute for component rotation, scaling, translation, and sk
## Designing Static Animation
Create a square and rotate it by 90 degrees to form a rhombus. Cover the lower part of the rhombus with a rectangle to form a roof. Set the translate attribute of the rectangle to the coordinate (150px, -150px) to form a door, use the position attribute to translate the horizontal and vertical axes to the specified coordinates of the parent component (square), set the scale attribute to scale up the parent and child components together to determine the window size, and use the skewX attribute to skew the component and set the coordinate translate(200px,-830px) to form a chimney.
Create a square and rotate it by 90 degrees to form a rhombus. Cover the lower part of the rhombus with a rectangle to form a roof. Set the **translate** attribute of the rectangle to the coordinate (150px, -150px) to form a door, use the **position** attribute to translate the horizontal and vertical axes to the specified coordinates of the parent component (square), set the **scale** attribute to scale up the parent and child components together to determine the window size, and use the **skewX** attribute to skew the component and set the coordinate translate(200px,-830px) to form a chimney.
```html
<!-- xxx.hml -->
......@@ -174,7 +174,7 @@ Decrease the y-coordinate over a time frame to make the ball bounce back. Gradua
## Designing Rotation Animation
Set the rotation center around an element in different transform-origin positions. Of the rotate3d values, the first three values are the rotation vectors of the x-axis, y-axis, and z-axis, respectively; the fourth value is the rotation angle, which can be a negative value to indicate that the rotation is performed counterclockwise.
Set the rotation center around an element in different transform-origin positions. Of the **rotate3d** values, the first three values are the rotation vectors of the x-axis, y-axis, and z-axis, respectively; the fourth value is the rotation angle, which can be a negative value to indicate that the rotation is performed counterclockwise.
```html
<!-- xxx.hml -->
......@@ -222,7 +222,7 @@ Set the rotation center around an element in different transform-origin position
}
.rect3 {
background-color: #6081f7;
/* Chhange the origin position.*/
/* Change the origin position.*/
transform-origin: right bottom;
}
@keyframes rotate {
......@@ -304,15 +304,16 @@ Set the rotation center around an element in different transform-origin position
![en-us_image_0000001222807776](figures/en-us_image_0000001222807776.gif)
> **NOTE**<br/>
> transform-origin specifies the origin of an element's transformation. If only one value is set, the other value is 50%. If both values are set, the first value indicates the position on the x-axis, and the second value indicates the position on the y-axis.
> **NOTE**
>
> **transform-origin** specifies the origin of an element's transformation. If only one value is set, the other value is 50%. If both values are set, the first value indicates the position on the x-axis, and the second value indicates the position on the y-axis.
## Designing Scaling Animation
This example implements a ripple animation with the scale attribute. Here is the overall procedure: First, use the positioning function to determine the coordinates of the element's position. Then, create multiple components to achieve the overlapping effect. After that, set the opacity attribute to hide or display the components. To scale and hide/display a component at the same time, set both the scale and opacity attributes. Finally, set different animation durations for different components to achieve the diffusion effect.
Set the scaling values for the x-axis, y-axis, and z-axis in scale3d to implement the animation.
Set the scaling values for the x-axis, y-axis, and z-axis in **scale3d** to implement the animation.
```html
<!-- xxx.hml -->
......@@ -419,7 +420,7 @@ text{
> **NOTE**
>
> After the transform attributes are set, the child element changes with the parent element. Value changing of other attributes (such as height and width) of the parent element will not affect the child element.
> After the **transform** attributes are set, the child element changes with the parent element. Value changing of other attributes (such as height and width) of the parent element will not affect the child element.
## Setting matrix
......@@ -467,9 +468,9 @@ The matrix attribute defines a transformation matrix with six input parameters:
![en-us_image_0000001267767853](figures/en-us_image_0000001267767853.gif)
## Integrating Transform Attributes
## Integrating transform Attributes
You can set multiple transform attributes at the same time to apply different transformations to a component. The following example applies the scale, translate, and rotate attributes simultaneously.
You can set multiple **transform** attributes at the same time to apply different transformations to a component. The following example applies the **scale**, **translate**, and **rotate** attributes simultaneously.
```html
<!-- xxx.hml -->
......@@ -578,8 +579,8 @@ You can set multiple transform attributes at the same time to apply different tr
> **NOTE**
>
> - When multiple transform attributes are set, the later one overwrites the previous one. To apply multiple transform styles at the same time, use the shorthand notation; that is, write multiple style values in one transform, for example, transform: scale(1) rotate(0) translate(0,0).
> - When multiple **transform** attributes are set, the later one overwrites the previous one. To apply multiple transform styles at the same time, use the shorthand notation; that is, write multiple style values in one transform, for example, transform: scale(1) rotate(0) translate(0,0).
>
> - When using the shorthand notion, note that the animation effect varies according to the sequence of the style values.
> - When using the shorthand notation, note that the animation effect varies according to the sequence of the style values.
>
> - The style values in the transform attribute used when the animation starts and ends must be in one-to-one mapping. Only the styles that have value mappings are played.
\ No newline at end of file
> - The style values in the **transform** attribute used when the animation starts and ends must be in one-to-one mapping. Only the styles that have value mappings are played.
\ No newline at end of file
......@@ -16,7 +16,7 @@ Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
<text>item1</text>
<text>item2</text>
</tab-bar>
<tab-content>
<tab-content class="tabContent">
<div class="text">
<text>content1</text>
</div>
......@@ -36,6 +36,10 @@ Create a **&lt;tabs&gt;** component in the .hml file under **pages/index**.
align-items: center;
background-color: #F1F3F5;
}
.tabContent{
width: 100%;
height: 100%;
}
.text{
width: 100%;
height: 100%;
......@@ -179,10 +183,10 @@ Add the **change** event for the **&lt;tabs&gt;** component to display the index
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
tabChange(e){
prompt.showToast({
promptAction.showToast({
message: "Tab index: " + e.index
})
}
......@@ -269,7 +273,7 @@ background-color:#F1F3F5;
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data() {
return {
......
......@@ -121,7 +121,7 @@ Add the **progress** method to the **\<button>** component to display the downlo
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
percent: 0,
......@@ -135,7 +135,7 @@ export default {
this.percent += 1;
this.downloadText = this.percent+ "%";
} else{
prompt.showToast({
promptAction.showToast({
message: "Download succeeded."
})
this.paused()
......@@ -151,13 +151,13 @@ export default {
},
setProgress(e) {
if(this.isPaused){
prompt.showToast({
promptAction.showToast({
message: "Started Downloading"
})
this.start();
this.isPaused = false;
}else{
prompt.showToast({
promptAction.showToast({
message: "Paused."
})
this.paused();
......
......@@ -20,6 +20,8 @@ Create a **&lt;canvas&gt;** component in the .hml file under **pages/index**.
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
......
......@@ -27,6 +27,8 @@ Use **moveTo** and **lineTo** to draw a line segment. Use the **closePath** meth
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
......@@ -49,7 +51,6 @@ select{
```js
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
......@@ -324,6 +325,8 @@ Add the **createLinearGradient** and **createRadialGradient** attributes to crea
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
......@@ -346,7 +349,6 @@ select{
```js
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
......@@ -448,6 +450,8 @@ Create a text and use the **fillText** method to write the text on the canvas. U
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
......@@ -470,7 +474,6 @@ select{
```js
// xxx.js
import prompt from '@system.prompt';
export default {
data:{
el: null,
......@@ -592,6 +595,8 @@ After creating an image object, use the **drawImage** attribute to draw the imag
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
......@@ -626,7 +631,7 @@ text{
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data:{
compositeOperation: 'source-over'
......@@ -669,7 +674,7 @@ export default {
};
// A method is triggered when the image fails to be obtained.
img1.onerror = function() {
prompt.showToast({message:"error",duration:2000})
promptAction.showToast({message:"error",duration:2000})
};
},
rotate(){
......@@ -761,6 +766,8 @@ Use the **save** method to save the brush style, and use the **restore** method
```css
/* xxx.css */
.container{
width: 100%;
height: 100%;
flex-direction: column;
background-color: #F1F3F5;
align-items: center;
......@@ -794,7 +801,7 @@ text{
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data:{
ctx: '',
......@@ -807,7 +814,7 @@ export default {
save(){
// Save the brush setting.
this.ctx.save();
prompt.showToast({message:"save succeed"});
promptAction.showToast({message:"save succeed"});
},
clear(){
this.ctx.clearRect(0,0,600,500);
......
......@@ -121,22 +121,22 @@ button{
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
canceldialog(e){
prompt.showToast({
promptAction.showToast({
message: 'dialogCancel'
})
},
opendialog(){
this.$element('dialogId').show()
prompt.showToast({
promptAction.showToast({
message: 'dialogShow'
})
},
confirmClick(e) {
this.$element('dialogId').close()
prompt.showToast({
promptAction.showToast({
message: 'dialogClose'
})
},
......
......@@ -121,15 +121,15 @@ To submit or reset a form, add the **submit** and **reset** events.
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default{
onSubmit(result) {
prompt.showToast({
promptAction.showToast({
message: result.value.radioGroup
})
},
onReset() {
prompt.showToast({
promptAction.showToast({
message: 'Reset All'
})
}
......@@ -184,6 +184,8 @@ Create two [\<Input>](../reference/arkui-js/js-components-basic-input.md) compon
```css
/* index.css */
.container {
width: 100%;
height: 100%;
flex-direction:column;
align-items:center;
background-color:#F1F3F5;
......@@ -200,15 +202,15 @@ label{
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
formSubmit() {
prompt.showToast({
promptAction.showToast({
message: 'Submitted.'
})
},
formReset() {
prompt.showToast({
promptAction.showToast({
message: 'Reset.'
})
}
......
......@@ -28,6 +28,7 @@ Create a **\<grid-container>** component in the .hml file under **pages/index**
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
}
......@@ -68,6 +69,7 @@ Touch the **\<grid-container>** component to call the **getColumns**, **getColum
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
}
......@@ -76,7 +78,7 @@ Touch the **\<grid-container>** component to call the **getColumns**, **getColum
```js
// index.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data:{
gutterWidth:'',
......@@ -94,13 +96,13 @@ export default {
this.columns= result;
})
setTimeout(()=>{
prompt.showToast({duration:5000,message:'columnWidth:'+this.columnWidth+',gutterWidth:'+
promptAction.showToast({duration:5000,message:'columnWidth:'+this.columnWidth+',gutterWidth:'+
this.gutterWidth+',getColumns:'+this.columns})
})
},
getSizeType(){
this.$element('mygrid').getSizeType((result)=>{
prompt.showToast({duration:2000,message:'get size type:'+result})
promptAction.showToast({duration:2000,message:'get size type:'+result})
})
},
}
......@@ -155,6 +157,7 @@ After adding a **\<grid-row>** child component to **\<grid-container>**, add a *
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
}
......@@ -205,6 +208,7 @@ In this example, the content in the list is output cyclically to create a grid l
flex-direction: column;
background-color: #F1F3F5;
width: 100%;
height: 100%;
}
text{
color: #0a0aef;
......
......@@ -177,7 +177,7 @@ Add the start, pause, stop, and resume events to the **&lt;image-animator&gt;**
```js
// index.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
imginfo: [
......@@ -201,22 +201,22 @@ export default {
this.$element('img').resume()
},
popstart(e) {
prompt.showToast({
promptAction.showToast({
message: 'Started.'
})
},
poppause(e) {
prompt.showToast({
promptAction.showToast({
message: 'Paused.'
})
},
popstop(e) {
prompt.showToast({
promptAction.showToast({
message: 'Stopped.'
})
},
popresume(e) {
prompt.showToast({
promptAction.showToast({
message: 'Resumed.'
})
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册