提交 1dcefb86 编写于 作者: J jiaoyanlin3

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

...@@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\<Text>** component. - In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\<Text>** component.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
@Entry(storage) @Entry(storage)
...@@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- In the widget page code file (generally the .ets file in the **pages** folder under the widget directory of the project), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\<Text>** component. - In the [widget page code file](arkts-ui-widget-creation.md), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\<Text>** component.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
@Entry(storage) @Entry(storage)
...@@ -215,4 +215,4 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -215,4 +215,4 @@ The update-through-proxy configuration varies by the type of shared data.
## Data Provider Development ## Data Provider Development
For details, see [Data Management](../database/data-mgmt-overview.md). For details, see [Data Management](../database/share-data-by-silent-access.md).
...@@ -15,10 +15,11 @@ ...@@ -15,10 +15,11 @@
- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host. - Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host.
**Figure 2** Working principles of the ArkTS widget rendering service **Figure 2** Working principles of the ArkTS widget rendering service
![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers. ![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
## Advantages of ArkTS Widgets ## Advantages of ArkTS Widgets
...@@ -57,6 +58,8 @@ In addition, ArkTS widgets do not support the following features: ...@@ -57,6 +58,8 @@ In addition, ArkTS widgets do not support the following features:
- Instant preview - Instant preview
- Breakpoint debugging. - Breakpoint debugging
- Hot reload - Hot reload
- **setTimeOut**
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
- Cross-Application Data Sharing - Cross-Application Data Sharing
- [Data Sharing Overview](data-share-overview.md) - [Data Sharing Overview](data-share-overview.md)
- [Unified Data Definition](unified-data-definition.md) - [Unified Data Definition](unified-data-definition.md)
- One-to-Many Data Sharing (Only for System Applications) - One-to-Many Data Sharing (for System Applications Only)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md) - [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Silent Access via the DatamgrService](share-data-by-silent-access.md) - [Silent Access via the DatamgrService](share-data-by-silent-access.md)
- Many-to-Many Data Sharing - Many-to-Many Data Sharing
- [Sharing Data Using Unified Data Channels](unified-data-channels.md) - [Sharing Data Using Unified Data Channels](unified-data-channels.md)
\ No newline at end of file
...@@ -760,147 +760,6 @@ Text in the **\<Text>** component is centered by default. You do not need to set ...@@ -760,147 +760,6 @@ Text in the **\<Text>** component is centered by default. You do not need to set
[Text](../reference/arkui-ts/ts-basic-components-text.md#example-1) [Text](../reference/arkui-ts/ts-basic-components-text.md#example-1)
## How do I set the controlButton attribute for the \<SideBarContainer> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
The sample code is as follows:
```
@Entry
@Component
struct SideBarContainerExample {
normalIcon : Resource = $r("app.media.icon")
selectedIcon: Resource = $r("app.media.icon")
@State arr: number[] = [1, 2, 3]
@State current: number = 1
build() {
SideBarContainer(SideBarContainerType.Embed)
{
Column() {
ForEach(this.arr, (item, index) => {
Column({ space: 5 }) {
Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64)
Text("Index0" + item)
.fontSize(25)
.fontColor(this.current === item ? '#0A59F7' : '#999')
.fontFamily('source-sans-pro,cursive,sans-serif')
}
.onClick(() => {
this.current = item
})
}, item => item)
}.width('100%')
.justifyContent(FlexAlign.SpaceEvenly)
.backgroundColor('#19000000')
Column() {
Text('SideBarContainer content text1').fontSize(25)
Text('SideBarContainer content text2').fontSize(25)
}
.margin({ top: 50, left: 20, right: 30 })
}
.sideBarWidth(150)
.minSideBarWidth(50)
.controlButton({left:32,
top:32,
width:32,
height:32,
icons:{shown: $r("app.media.icon"),
hidden: $r("app.media.icon"),
switching: $r("app.media.icon")}})
.maxSideBarWidth(300)
.onChange((value: boolean) => {
console.info('status:' + value)
})
}
}
```
## How do I implement the dragging feature for the \<Grid> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
1. Set the **editMode\(true\)** attribute of the **\<Grid>** component to specify whether the component enters the editing mode. In the editing mode, you can drag grid items.
2. Set the image displayed during dragging in the [onItemDragStart](../reference/arkui-ts/ts-container-grid.md#events) callback.
3. Obtain the drag start position and drag insertion position from the [onItemDrop](../reference/arkui-ts/ts-container-grid.md#events) callback, and complete the array position exchange logic in the [onDrag](../reference/arkui-ts/ts-universal-events-drag-drop.md#events) callback. The sample code is as follows:
```
@Entry
@Component
struct GridExample {
@State numbers: String[] = []
scroller: Scroller = new Scroller()
@State text: string = 'drag'
@Builder pixelMapBuilder () { // Drag style
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 15; i++) {
this.numbers.push(i + '')
}
}
changeIndex(index1: number, index2: number) {// Exchange the array item position.
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Up) {
this.text = day
}
})
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height(300)
.editMode(true) // Set whether the grid enters the editing mode. In the editing mode, you can drag grid items.
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
return this.pixelMapBuilder() // Set the image displayed during dragging.
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item; insertIndex indicates the index of the position to which the dragged item will be dropped.
this.changeIndex(itemIndex, insertIndex)
})
}.width('100%').margin({ top: 5 })
}
}
```
## Which API is used for URL encoding? ## Which API is used for URL encoding?
......
# ArkUI Component Development (ArkTS) # ArkUI Component Development (ArkTS)
## Can custom dialog boxes be defined or used in .ts files? ## Can custom dialog boxes be defined and used in .ts files?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9) Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Unfortunately, no. ArkTS syntax is required for defining and initializing custom dialog boxes. Therefore, they can be defined and used only in .ets files. Unfortunately not. Custom dialog boxes require ArkTS syntax for definition and initialization. Therefore, they can be defined and used only in .ets files.
**Reference** **Reference**
...@@ -245,8 +245,8 @@ When a custom dialog box contains a child component whose area size can be chang ...@@ -245,8 +245,8 @@ When a custom dialog box contains a child component whose area size can be chang
**Solution** **Solution**
- Method 1: Use the default style of the custom dialog box. In this case, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height. - Method 1: Set the custom dialog box to the default style. In this style, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height.
- Method 2: Use a custom style of the custom dialog box. In this case, the dialog box automatically adapts its width and height to the child components. - Method 2: Set the custom dialog box to a custom style. In this style, the dialog box automatically adapts its width and height to the child components.
**Reference** **Reference**
...@@ -685,3 +685,64 @@ You can use **focusControl.requestFocus** to control the focus of the text input ...@@ -685,3 +685,64 @@ You can use **focusControl.requestFocus** to control the focus of the text input
**Reference** **Reference**
[Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md) [Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md)
## How do I set the controlButton attribute for the \<SideBarContainer> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
Refer to the following sample code:
```
@Entry
@Component
struct SideBarContainerExample {
normalIcon : Resource = $r("app.media.icon")
selectedIcon: Resource = $r("app.media.icon")
@State arr: number[] = [1, 2, 3]
@State current: number = 1
build() {
SideBarContainer(SideBarContainerType.Embed)
{
Column() {
ForEach(this.arr, (item, index) => {
Column({ space: 5 }) {
Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64)
Text("Index0" + item)
.fontSize(25)
.fontColor(this.current === item ? '#0A59F7' : '#999')
.fontFamily('source-sans-pro,cursive,sans-serif')
}
.onClick(() => {
this.current = item
})
}, item => item)
}.width('100%')
.justifyContent(FlexAlign.SpaceEvenly)
.backgroundColor('#19000000')
Column() {
Text('SideBarContainer content text1').fontSize(25)
Text('SideBarContainer content text2').fontSize(25)
}
.margin({ top: 50, left: 20, right: 30 })
}
.sideBarWidth(150)
.minSideBarWidth(50)
.controlButton({left:32,
top:32,
width:32,
height:32,
icons:{shown: $r("app.media.icon"),
hidden: $r("app.media.icon"),
switching: $r("app.media.icon")}})
.maxSideBarWidth(300)
.onChange((value: boolean) => {
console.info('status:' + value)
})
}
}
```
# Best Practices for Application Performance
This topic outlines some best practices for improving your application performance to live up to user expectations for quick startup, timely response, and no frame freezing.
Following these practices, you can reduce your application's startup time, response time, and frame loss.
- Improving application startup and response time
- [Speeding Up Application Cold Start](../performance/improve-application-startup-and-response/improve-application-cold-start-speed.md)
Application startup latency is a key factor that affects user experience. To speed up the application cold start, you are advised to perform optimization in the following four phases:
​ 1. Application process creation and initialization
​ 2. Application and ability initialization
​ 3. Ability lifecycle
​ 4. Home page loading and drawing
- [Speeding Up Application Response](../performance/improve-application-startup-and-response/improve-application-response.md)
A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of component to be refreshed.
- Reducing frame loss
- [Reducing Nesting](../performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md)
The smoothness of rendering the layout to the screen affects the user perceived quality. It is recommended that you minimize nesting in your code to shorten the render time.
- [Reducing Frame Loss](../performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md)
Whether animations in your application run smoothly is a key factor that affects user experience. You are advised to use the system-provided animation APIs to reduce frame loss.
# Speeding Up Application Cold Start
Application startup latency is a key factor that affects user experience. When an application is started, the background does not have a process of the application, and therefore the system creates a new process and allocates it to the application. This startup mode is called cold start.
## Analyzing the Time Required for Application Cold Start
The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown in the following figure.
![application-cold-start](../figure/application-cold-start.png)
## 1. Shortening Time Required for Application Process Creation And Initialization
In the phase of application process creation and initialization, the system creates and initializes an application process, including decoding the icon of the startup page (specified by **startWindowIcon**).
### Using startWindowIcon of Appropriate Resolution
With regard to the icon of the startup page, the recommended maximum resolution is 256 x 256 pixels. Larger resolutions may result in slow startup.
```json
"abilities": [
{
"name": "EntryAbility",
"srcEntrance": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 pixels x 256 pixels.
"startWindowBackground": "$color:start_window_background",
"visible": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
]
```
## 2. Shortening Time Required for Application and Ability Initialization
In this phase of application and ability initialization, resources are loaded, VMs are created, application and ability related objects are created and initialized, and dependent modules are loaded.
### Minimizing the Number of Imported Modules
Before the application code is executed, the application must find and load all imported modules. Each additional third-party framework or module to be loaded by the application increases the startup time. The time required depends on the number and size of loaded third-party frameworks or modules. To speed up startup, use system-provided modules when possible and load the modules as required.
## 3. Shortening Time Required for Ability Lifecycle
In this phase of ability lifecycle, the ability lifecycle callbacks are executed.
### Avoiding Time-Consuming Operations in Ability Lifecycle Callbacks
In the application startup process, the system executes the ability lifecycle callbacks. Whenever possible, avoid performing time-consuming operations in these callbacks. You are advised to perform time-consuming operations through asynchronous tasks or execute them in other threads.
In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](https://gitee.com/openharmony/docs/blob/master/en/application-dev/application-models/uiability-lifecycle.md).
## 4. Shortening Time Required for Home Page Loading and Drawing
In this phase of home page loading and drawing, the home page content is loaded, the layout is measured, and components are refreshed and drawn.
### Avoid time-consuming operations in the custom component lifecycle callbacks.
When the lifecycle of a custom component changes, the corresponding callback is called.
The **aboutToAppear** function is executed after the custom component instance is created and before the page is drawn. The following code asynchronously processes the time-consuming computing task in **aboutToAppear** to avoid executing the operation in this function and blocking the page drawing.
```javascript
@Entry
@Component
struct Index {
@State private text: string = undefined;
private count: number = undefined;
aboutToAppear() {
this.computeTaskAsync(); // Asynchronous task
this.text = "hello world";
}
build() {
Column({space: 10}) {
Text(this.text).fontSize(50)
}
.width('100%')
.height('100%')
.padding(10)
}
computeTask() {
this.count = 0;
while (this.count < 10000000) {
this.count++;
}
this.text = 'task complete';
}
// Asynchronous processing of the computing task
private computeTaskAsync() {
new Promise((resolved, rejected) => {
setTimeout(() => {// setTimeout is used to implement asynchronous processing.
this.computeTask();
}, 1000)
})
}
}
```
# Speeding Up Application Response
This topic provides the following tips for improving your application's response to user input.
- Prevent the main thread from being blocked by non-UI tasks.
- Reduce the number of components to be refreshed.
## Preventing Main Thread from Being Blocked by Non-UI Tasks
When the application responds to user input, its main thread should execute only UI tasks (such as preparation of data to be displayed and update of visible components). It is recommended that non-UI, time-consuming tasks (such as long-time content loading) be executed through asynchronous tasks or allocated to other threads.
### Using Asynchronous Component Loading
The **\<Image>** component has the asynchronous loading feature enabled by default. When an application loads a batch of local images to be displayed on the page, blank placeholder icons are displayed first, and then replaced by the images when these images have finished loading in other threads. In this way, image loading does not block page display. The following code is recommended only when the image loading takes a short time.
```javascript
@Entry
@Component
struct ImageExample1 {
build() {
Column() {
Row() {
Image('resources/base/media/sss001.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss002.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss003.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss004.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
}
// Several <Row> containers are omitted here. Each container contains the preceding <Image> components.
}
}
}
```
Recommendation: If it takes a short time to load an image, the benefits of asynchronous loading will be greatly undermined. In this case, change the value of the syncLoad attribute.
```javascript
@Entry
@Component
struct ImageExample1 {
build() {
Column() {
Row() {
Image('resources/base/media/sss001.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss002.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss003.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss004.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
}
// Several <Row> containers are omitted here. Each container contains the preceding <Image> components.
}
}
}
```
### Using TaskPool for Asynchronous Processing
Compared with the worker thread, [TaskPool](https://gitee.com/sqsyqqy/docs/blob/master/en/application-dev/reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example:
```javascript
import taskpool from '@ohos.taskpool';
@Concurrent
function computeTask(arr: string[]): string[] {
// Simulate a compute-intensive task.
let count = 0;
while (count < 100000000) {
count++;
}
return arr.reverse();
}
@Entry
@Component
struct AspectRatioExample {
@State children: string[] = ['1', '2', '3', '4', '5', '6'];
aboutToAppear() {
this.computeTaskInTaskPool();
}
async computeTaskInTaskPool() {
const param = this.children.slice();
let task = new taskpool.Task(computeTask, param);
// @ts-ignore
this.children = await taskpool.execute(task);
}
build() {
// Component layout
}
}
```
### Creating Asynchronous Tasks
The following code shows how to declare a long-running non-UI task as an asynchronous task through **Promise**. This allows the main thread to first focus on providing user feedback and completing the initial render, and then execute the asynchronous task when it is idle. After the asynchronous task is complete, related components are redrawn to refresh the page.
```javascript
@Entry
@Component
struct AspectRatioExample {
@State private children: string[] = ['1', '2', '3', '4', '5', '6'];
private count: number = undefined;
aboutToAppear() {
this.computeTaskAsync(); // Invoke the asynchronous compute function.
}
// Simulate a compute-intensive task.
computeTask() {
this.count = 0;
while (this.count < 100000000) {
this.count++;
}
this.children = this.children.reverse();
}
computeTaskAsync() {
new Promise((resolved, rejected) => {
setTimeout(() => {// setTimeout is used to implement asynchronous processing.
this.computeTask();
}, 1000)
})
}
build() {
// Component layout
}
}
```
## Reducing the Number of Components to Be Refreshed
When an application refreshes a page, the number of components to be refreshed must be reduced as much as possible. If this number is too large, the main thread will take a long time to perform measurement and layout. In addition, the **aboutToAppear()** and **aboutToDisappear()** APIs will be called multiple times during the creation and destruction of custom components, increasing the load of the main thread.
### Limiting the Refresh Scope with Containers
Negative example: If a component in a container is included in the **if** condition, changes in the **if** condition result will trigger the creation and destruction of the component. If the container layout is affected in this case, all components in the container are refreshed. As a result, the UI refresh of the main thread takes a long time.
In the following example, the **Text('New Page')** component is controlled by the state variable **isVisible**. When **isVisible** is set to **true**, the component is created. When **isVisible** is set to **false**, the component is destroyed. This means that, when the value of **isVisible** changes, all components in the **\<Stack>** container are refreshed.
```javascript
@Entry
@Component
struct StackExample {
@State isVisible : boolean = false;
build() {
Column() {
Stack({alignContent: Alignment.Top}) {
Text().width('100%').height('70%').backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
// 100 identical <Text> components are omitted here.
if (this.isVisible) {
Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
}
}
Button("press").onClick(() => {
this.isVisible = !(this.isVisible);
})
}
}
}
```
Recommendation: For the component controlled by the state variable, add a container to the **if** statement to reduce the refresh scope.
```javascript
@Entry
@Component
struct StackExample {
@State isVisible : boolean = false;
build() {
Column() {
Stack({alignContent: Alignment.Top}) {
Text().width('100%').height('70%').backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
// 100 identical <Text> components are omitted here.
Stack() {
if (this.isVisible) {
Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
}
}.width('100%').height('70%')
}
Button("press").onClick(() => {
this.isVisible = !(this.isVisible);
})
}
}
}
```
### Implementing On-Demand Loading of List Items
Negative example: Each of the 10000 elements in **this.arr** is initialized and loaded. As a result, the execution of the main thread takes a long time.
```javascript
@Entry
@Component
struct MyComponent {
@State arr: number[] = Array.from(Array(10000), (v,k) =>k);
build() {
List() {
ForEach(this.arr, (item: number) => {
ListItem() {
Text(`item value: ${item}`)
}
}, (item: number) => item.toString())
}
}
}
```
Recommendation: In similar cases, replace **ForEach** with **LazyForEach** so that only visible elements are loaded.
```javascript
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString());
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List() {
LazyForEach(this.data, (item: string) => {
ListItem() {
Text(item).fontSize(20).margin({ left: 10 })
}
}, item => item)
}
}
}
```
# Reducing Frame Loss
Frame loss in the animation arena is a phenomenon where the frame rate of an animation drops when it is running or being created.
When playing an animation, the system needs to calculate the animation curve and draw the component layout within a refresh period. You are advised to use the system-provided animation APIs. With these APIs, setting the curve type, end point position, and duration is enough for meeting common animation needs, thereby reducing the load of the UI main thread.
Negative example: The application uses a custom animation, which involves animation curve calculation. This calculation process may cause high load of the UI thread and frame loss.
```javascript
@Entry
@Component
struct AttrAnimationExample {
@State widthSize: number = 200
@State heightSize: number = 100
@State flag: boolean = true
computeSize() {
let duration = 2000
let period = 16
let widthSizeEnd = undefined
let heightSizeEnd = undefined
if (this.flag) {
widthSizeEnd = 100
heightSizeEnd = 50
} else {
widthSizeEnd = 200
heightSizeEnd = 100
}
let doTimes = duration / period
let deltaHeight = (heightSizeEnd - this.heightSize) / doTimes
let deltaWeight = (widthSizeEnd - this.widthSize) / doTimes
for (let i = 1; i <= doTimes; i++) {
let t = period * (i);
setTimeout(() => {
this.heightSize = this.heightSize + deltaHeight
this.widthSize = this.widthSize + deltaWeight
}, t)
}
this.flag = !this.flag
}
build() {
Column() {
Button('click me')
.onClick(() => {
let delay = 500
setTimeout(() => { this.computeSize() }, delay)
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
}.width('100%').margin({ top: 5 })
}
}
```
## Using System-Provided Attribute Animation APIs
The following uses the system-provided attribute animation APIs to implement the preceding animation features:
```javascript
@Entry
@Component
struct AttrAnimationExample {
@State widthSize: number = 200
@State heightSize: number = 100
@State flag: boolean = true
build() {
Column() {
Button('click me')
.onClick((event: ClickEvent) => {
if (this.flag) {
this.widthSize = 100
this.heightSize = 50
} else {
this.widthSize = 200
this.heightSize = 100
}
this.flag = !this.flag
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
.animation({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}) // Animation configuration for the width and height attributes of the <Button> component.
}.width('100%').margin({ top: 5 })
}
}
```
For more details, see [Property Animator](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-animatorproperty.md).
## Using System-Provided Explicit Animation APIs
The following uses the system-provided explicit animation APIs to implement the preceding animation features:
```javascript
@Entry
@Component
struct AnimateToExample {
@State widthSize: number = 200;
@State heightSize: number = 100;
@State flag: boolean = true;
build() {
Column() {
Button('click me')
.onClick((event: ClickEvent) => {
if (this.flag) {
animateTo({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}, () => {
this.widthSize = 100;
this.heightSize = 50;
})
} else {
animateTo({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}, () => {
this.widthSize = 200;
this.heightSize = 100;
})
}
this.flag = !this.flag;
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
}.width('100%').margin({ top: 5 })
}
}
```
For more details, see [Explicit Animation](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-explicit-animation.md).
# Reducing Nesting
The view hierarchy can significantly affect application performance. For example, at the 120 Hz refresh rate, a device screen refreshes frames every 8.3 ms. If there are many levels of nested views, the frames may fail to be refreshed within 8.3 ms. As a result, frame loss and frame freezing occur, detracting from user experience. Therefore, it is recommended that you minimize nesting in your code to shorten the refresh time.
## Removing Redundant Levels of Nesting
In the following negative example, the **\<Grid>** component is used to implement a grid, but it is nested inside three levels of **\<Stack>** containers. As a result, the refresh and rendering process takes a long time to complete.
```javascript
@Entry
@Component
struct AspectRatioExample {
@State children: Number[] = Array.from(Array(900), (v, k) => k);
build() {
Scroll() {
Grid() {
ForEach(this.children, (item) => {
GridItem() {
Stack() {
Stack() {
Stack() {
Text(item.toString())
}
}
}
}
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.columnsGap(0)
.rowsGap(0)
.size({ width: "100%", height: "100%" })
}
}
}
```
Recommendation: Reduce the redundant nesting of **\<Stack>** containers. In this way, the number of components that each grid item needs to pass is three less, shortening the refresh and rendering time.
```javascript
// xxx.ets
@Entry
@Component
struct AspectRatioExample {
@State children: Number[] = Array.from(Array(900), (v, k) => k);
build() {
Scroll() {
Grid() {
ForEach(this.children, (item) => {
GridItem() {
Text(item.toString())
}
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.columnsGap(0)
.rowsGap(0)
.size({ width: "100%", height: "100%" })
}
}
}
```
...@@ -152,7 +152,7 @@ struct Parent { ...@@ -152,7 +152,7 @@ struct Parent {
``` ```
### Example of Component Initialization Through Trailing Closure ### Component Initialization Through Trailing Closure
In a custom component, the \@BuilderParam decorated attribute can be initialized using a trailing closure. During initialization, the component name is followed by a pair of braces ({}) to form a trailing closure. In a custom component, the \@BuilderParam decorated attribute can be initialized using a trailing closure. During initialization, the component name is followed by a pair of braces ({}) to form a trailing closure.
......
...@@ -37,6 +37,8 @@ What the internal state is depends on the component. For example, for the [bindP ...@@ -37,6 +37,8 @@ What the internal state is depends on the component. For example, for the [bindP
| [Toggle](../reference/arkui-ts/ts-basic-components-toggle.md) | isOn | 10 | | [Toggle](../reference/arkui-ts/ts-basic-components-toggle.md) | isOn | 10 |
| [AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md) | selected | 10 | | [AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md) | selected | 10 |
| [Select](../reference/arkui-ts/ts-basic-components-select.md) | selected, value| 10 | | [Select](../reference/arkui-ts/ts-basic-components-select.md) | selected, value| 10 |
| [BindSheet](../reference/arkui-ts/ts-universal-attributes-sheet-transition.md) | isShow | 10 |
| [BindContentCover](../reference/arkui-ts/ts-universal-attributes-modal-transition.md) | isShow | 10 |
- When the variable bound to $$ changes, the UI is re-rendered synchronously. - When the variable bound to $$ changes, the UI is re-rendered synchronously.
......
...@@ -227,9 +227,9 @@ ...@@ -227,9 +227,9 @@
- [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- application - application
- [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md) - [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md)
......
# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks) # @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks. The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs. When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
...@@ -28,7 +28,7 @@ import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility' ...@@ -28,7 +28,7 @@ import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
onWorkStart(work: workScheduler.WorkInfo): void onWorkStart(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task starts. Called when the system starts scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -52,7 +52,7 @@ Triggered when the Work Scheduler task starts. ...@@ -52,7 +52,7 @@ Triggered when the Work Scheduler task starts.
onWorkStop(work: workScheduler.WorkInfo): void onWorkStop(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task stops. Called when the system stops scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
# WorkSchedulerExtensionContext # WorkSchedulerExtensionContext
The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility. The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), provides a context environment for the WorkSchedulerExtensionAbility.
This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility. This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility.
......
...@@ -3,9 +3,7 @@ ...@@ -3,9 +3,7 @@
> **NOTE** > **NOTE**
> >
> - The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module are deprecated since API version 9 and will be retained until API version 13. > - The APIs of this module are deprecated since API version 9. For details about the substitute APIs, see the API description.
> - Some APIs are changed as system APIs and can be used only by system applications. Use [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md) instead.
> - The APIs for selecting and storing media assets are still open to common applications. Use [@ohos.file.picker](js-apis-file-picker.md) instead.
## Modules to Import ## Modules to Import
...@@ -21,6 +19,9 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal ...@@ -21,6 +19,9 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal
This API can be used only in the stage model. This API can be used only in the stage model.
> **NOTE**
> This API is deprecated since API Version 9. Use [getPhotoAccessHelper](js-apis-photoAccessHelper.md#photoaccesshelpergetphotoaccesshelper) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -33,7 +34,7 @@ This API can be used only in the stage model. ...@@ -33,7 +34,7 @@ This API can be used only in the stage model.
| Type | Description | | Type | Description |
| ----------------------------- | :---- | | ----------------------------- | :---- |
| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| | [MediaLibrary](#medialibrary) | **MediaLibrary** instance obtained.|
**Example (from API version 9)** **Example (from API version 9)**
...@@ -60,13 +61,16 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal ...@@ -60,13 +61,16 @@ Obtains a **MediaLibrary** instance, which is used to access and modify personal
This API can be used only in the FA model. This API can be used only in the FA model.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | :--------- | | ----------------------------- | :--------- |
| [MediaLibrary](#medialibrary) | **MediaLibrary** instance.| | [MediaLibrary](#medialibrary) | **MediaLibrary** instance obtained.|
**Example** **Example**
...@@ -83,7 +87,9 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileRe ...@@ -83,7 +87,9 @@ getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileRe
Obtains file assets (also called files). This API uses an asynchronous callback to return the result. Obtains file assets (also called files). This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -154,7 +160,9 @@ getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt; ...@@ -154,7 +160,9 @@ getFileAssets(options: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
Obtains file assets. This API uses a promise to return the result. Obtains file assets. This API uses a promise to return the result.
> **NOTE** > **NOTE**
> From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
> - From API version 10, the albums represented by physical directories are replaced by logical albums, which allows multiple files in an album and presence of a file in multiple albums. This design, however, makes **parent**, **albumId**, **albumUri**, and **albumName** incompatible. They cannot be used as parameters of **MediaFetchOptions** in **getFileAssets()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -225,6 +233,9 @@ on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange' ...@@ -225,6 +233,9 @@ on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'
Subscribes to the media library changes. This API uses a callback to return the result. Subscribes to the media library changes. This API uses a callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [registerChange](js-apis-photoAccessHelper.md#registerchange) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -248,6 +259,9 @@ off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange ...@@ -248,6 +259,9 @@ off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange
Unsubscribes from the media library changes. This API uses a callback to return the result. Unsubscribes from the media library changes. This API uses a callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [unRegisterChange](js-apis-photoAccessHelper.md#unregisterchange) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -272,7 +286,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string, cal ...@@ -272,7 +286,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string, cal
Creates a media asset. This API uses an asynchronous callback to return the result. Creates a media asset. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -312,7 +328,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr ...@@ -312,7 +328,9 @@ createAsset(mediaType: MediaType, displayName: string, relativePath: string): Pr
Creates a media asset. This API uses a promise to return the result. Creates a media asset. This API uses a promise to return the result.
> **NOTE** > **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [createAsset](js-apis-photoAccessHelper.md#createasset-1) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. After a file is created, the last-level directory of **relativePath** is not displayed. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -354,6 +372,11 @@ deleteAsset(uri: string): Promise\<void> ...@@ -354,6 +372,11 @@ deleteAsset(uri: string): Promise\<void>
Deletes a file asset. This API uses a promise to return the result. Deletes a file asset. This API uses a promise to return the result.
Before calling this API, call [FileAsset.trash](#trash8) to move the file to the trash. Otherwise, the file fails to be deleted.
> **NOTE**
> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-3) instead.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -403,6 +426,11 @@ deleteAsset(uri: string, callback: AsyncCallback\<void>): void ...@@ -403,6 +426,11 @@ deleteAsset(uri: string, callback: AsyncCallback\<void>): void
Deletes a file asset. This API uses an asynchronous callback to return the result. Deletes a file asset. This API uses an asynchronous callback to return the result.
Before calling this API, call [FileAsset.trash](#trash8) to move the file to the trash. Otherwise, the file fails to be deleted.
> **NOTE**
> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteassets-2) instead.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -449,6 +477,9 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;): ...@@ -449,6 +477,9 @@ getPublicDirectory(type: DirectoryType, callback: AsyncCallback&lt;string&gt;):
Obtains a user directory. This API uses an asynchronous callback to return the result. Obtains a user directory. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -477,6 +508,9 @@ getPublicDirectory(type: DirectoryType): Promise&lt;string&gt; ...@@ -477,6 +508,9 @@ getPublicDirectory(type: DirectoryType): Promise&lt;string&gt;
Obtains a user directory. This API uses a promise to return the result. Obtains a user directory. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -515,7 +549,9 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback&lt;Array&lt;Album& ...@@ -515,7 +549,9 @@ getAlbums(options: MediaFetchOptions, callback: AsyncCallback&lt;Array&lt;Album&
Obtains albums. This API uses an asynchronous callback to return the result. Obtains albums. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -553,7 +589,9 @@ getAlbums(options: MediaFetchOptions): Promise&lt;Array&lt;Album&gt;&gt; ...@@ -553,7 +589,9 @@ getAlbums(options: MediaFetchOptions): Promise&lt;Array&lt;Album&gt;&gt;
Obtains albums. This API uses a promise to return the result. Obtains albums. This API uses a promise to return the result.
> **NOTE** > **NOTE**
> From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [getAlbums](js-apis-photoAccessHelper.md#getalbums-2) instead.
> - From the SDK of API version 10, **relativePath** is no longer associated with an album. Therefore, **relativePath** cannot be used as a search criterion in **getAlbums**. Currently, only **Camera** and **ScreenShots** albums are supported. For more details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -594,6 +632,9 @@ release(callback: AsyncCallback&lt;void&gt;): void ...@@ -594,6 +632,9 @@ release(callback: AsyncCallback&lt;void&gt;): void
Releases this **MediaLibrary** instance. Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance. Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
> **NOTE**
> This API is deprecated since API Version 9. Use [release](js-apis-photoAccessHelper.md#release) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -617,6 +658,9 @@ release(): Promise&lt;void&gt; ...@@ -617,6 +658,9 @@ release(): Promise&lt;void&gt;
Releases this **MediaLibrary** instance. Releases this **MediaLibrary** instance.
Call this API when you no longer need to use the APIs in the **MediaLibrary** instance. Call this API when you no longer need to use the APIs in the **MediaLibrary** instance.
> **NOTE**
> This API is deprecated since API Version 9. Use [release](js-apis-photoAccessHelper.md#release-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -637,7 +681,10 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;) ...@@ -637,7 +681,10 @@ storeMediaAsset(option: MediaAssetOption, callback: AsyncCallback&lt;string&gt;)
Stores a media asset. This API uses an asynchronous callback to return the URI of the media asset. Stores a media asset. This API uses an asynchronous callback to return the URI of the media asset.
> **NOTE**<br>This API is supported since API version 6 and can be used only in the FA model. > **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. Use [save](js-apis-file-picker.md#save-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -672,7 +719,10 @@ storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt; ...@@ -672,7 +719,10 @@ storeMediaAsset(option: MediaAssetOption): Promise&lt;string&gt;
Stores a media asset. This API uses a promise to return the URI of the media asset. Stores a media asset. This API uses a promise to return the URI of the media asset.
> **NOTE**<br>This API is supported since API version 6 and can be used only in the FA model. > **NOTE**
>
> - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. Use [save](js-apis-file-picker.md#save) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -711,8 +761,9 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal ...@@ -711,8 +761,9 @@ startImagePreview(images: Array&lt;string&gt;, index: number, callback: AsyncCal
Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result. Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> This API is supported since API version 6 and can be used only in the FA model. >
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images. > - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. <br>The **\<Image>** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -754,8 +805,9 @@ startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&g ...@@ -754,8 +805,9 @@ startImagePreview(images: Array&lt;string&gt;, callback: AsyncCallback&lt;void&g
Starts image preview. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result. Starts image preview. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> This API is supported since API version 6 and can be used only in the FA model. >
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images. > - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. <br>The **\<Image>** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -795,8 +847,9 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void& ...@@ -795,8 +847,9 @@ startImagePreview(images: Array&lt;string&gt;, index?: number): Promise&lt;void&
Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses a promise to return the execution result. Starts image preview, with the first image to preview specified. This API can be used to preview local images whose URIs start with **datashare://** or online images whose URIs start with **https://**. It uses a promise to return the execution result.
> **NOTE** > **NOTE**
> This API is supported since API version 6 and can be used only in the FA model. >
> You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead.<br>The **\<Image>** component can be used to render and display local and online images. > - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. You are advised to use the **\<[Image](../arkui-ts/ts-basic-components-image.md)>** component instead. <br>The **\<Image>** component can be used to render and display local and online images.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -841,8 +894,9 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt; ...@@ -841,8 +894,9 @@ startMediaSelect(option: MediaSelectOption, callback: AsyncCallback&lt;Array&lt;
Starts media selection. This API uses an asynchronous callback to return the URIs of the selected media assets. Starts media selection. This API uses an asynchronous callback to return the URIs of the selected media assets.
> **NOTE** > **NOTE**
> This API is supported since API version 6 and can be used only in the FA model. >
> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, see [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). > - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. Use [select](js-apis-file-picker.md#select-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -877,8 +931,9 @@ startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt; ...@@ -877,8 +931,9 @@ startMediaSelect(option: MediaSelectOption): Promise&lt;Array&lt;string&gt;&gt;
Starts media selection. This API uses a promise to return the URIs of the selected media assets. Starts media selection. This API uses a promise to return the URIs of the selected media assets.
> **NOTE** > **NOTE**
> This API is supported since API version 6 and can be used only in the FA model. >
> You are advised to use the system app Gallery instead. Gallery is a built-in visual resource access application that provides features such as image and video management and browsing. For details about how to use Gallery, see [OpenHarmony/applications_photos](https://gitee.com/openharmony/applications_photos). > - This API is supported since API version 6 and can be used only in the FA model.
> - This API is deprecated since API Version 9. Use [select](js-apis-file-picker.md#select) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -915,6 +970,9 @@ getActivePeers(): Promise\<Array\<PeerInfo>>; ...@@ -915,6 +970,9 @@ getActivePeers(): Promise\<Array\<PeerInfo>>;
Obtains information about online peer devices. This API uses a promise to return the result. Obtains information about online peer devices. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -949,6 +1007,9 @@ getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void; ...@@ -949,6 +1007,9 @@ getActivePeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
Obtains information about online peer devices. This API uses an asynchronous callback to return the result. Obtains information about online peer devices. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -981,6 +1042,9 @@ getAllPeers(): Promise\<Array\<PeerInfo>>; ...@@ -981,6 +1042,9 @@ getAllPeers(): Promise\<Array\<PeerInfo>>;
Obtains information about all peer devices. This API uses a promise to return the result. Obtains information about all peer devices. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -1015,6 +1079,9 @@ getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void; ...@@ -1015,6 +1079,9 @@ getAllPeers(callback: AsyncCallback\<Array\<PeerInfo>>): void;
Obtains information about all peer devices. This API uses an asynchronous callback to return the result. Obtains information about all peer devices. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -1047,8 +1114,9 @@ Provides APIs for encapsulating file asset attributes. ...@@ -1047,8 +1114,9 @@ Provides APIs for encapsulating file asset attributes.
> **NOTE** > **NOTE**
> >
> 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices. > - The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices.
> 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module. > - Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module.
> - This API is deprecated since API Version 9. Use [PhotoAsset](js-apis-photoAccessHelper.md#photoasset) instead.
### Attributes ### Attributes
...@@ -1084,6 +1152,9 @@ isDirectory(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1084,6 +1152,9 @@ isDirectory(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1124,6 +1195,9 @@ isDirectory():Promise&lt;boolean&gt; ...@@ -1124,6 +1195,9 @@ isDirectory():Promise&lt;boolean&gt;
Checks whether this file asset is a directory. This API uses a promise to return the result. Checks whether this file asset is a directory. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1163,7 +1237,9 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void ...@@ -1163,7 +1237,9 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void
Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). >
> - This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify) instead.
> - Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -1203,6 +1279,8 @@ commitModify(): Promise&lt;void&gt; ...@@ -1203,6 +1279,8 @@ commitModify(): Promise&lt;void&gt;
Commits the modification on the file asset to the database. This API uses a promise to return the result. Commits the modification on the file asset to the database. This API uses a promise to return the result.
> **NOTE** > **NOTE**
>
> - This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-1) instead.
> Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md). > Since the SDK of API version 10, **audio** does not have the **orientation** attribute. Therefore, the **orientation** attribute of the audio resource cannot be modified by **commitModify()**. For details, see [changelogs-mediaLibrary.md](../../../release-notes/changelogs/OpenHarmony_4.0.8.2/changelogs-mediaLibrary.md).
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
...@@ -1240,6 +1318,9 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void ...@@ -1240,6 +1318,9 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void
Opens this file asset. This API uses an asynchronous callback to return the result. Opens this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [open](js-apis-photoAccessHelper.md#open) instead.
**NOTE**<br>If a file is opened in 'w' mode, the returned file descriptor (FD) cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file. **NOTE**<br>If a file is opened in 'w' mode, the returned file descriptor (FD) cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
...@@ -1277,6 +1358,9 @@ open(mode: string): Promise&lt;number&gt; ...@@ -1277,6 +1358,9 @@ open(mode: string): Promise&lt;number&gt;
Opens this file asset. This API uses a promise to return the result. Opens this file asset. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [open](js-apis-photoAccessHelper.md#open-1) instead.
**NOTE**<br>If a file is opened in 'w' mode, the returned FD cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file. **NOTE**<br>If a file is opened in 'w' mode, the returned FD cannot be used to read the file. However, due to the implementation differences of file systems, some user-mode files opened in 'w' mode can be read by using FD. To perform the read or write operation on a file by using FD, you are advised to open the file in 'rw' mode. The write operations are mutually exclusive. After a write operation is complete, you must call **close** to close the file.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
...@@ -1317,6 +1401,9 @@ close(fd: number, callback: AsyncCallback&lt;void&gt;): void ...@@ -1317,6 +1401,9 @@ close(fd: number, callback: AsyncCallback&lt;void&gt;): void
Closes a file. This API uses an asynchronous callback to return the result. Closes a file. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1363,6 +1450,9 @@ close(fd: number): Promise&lt;void&gt; ...@@ -1363,6 +1450,9 @@ close(fd: number): Promise&lt;void&gt;
Closes a file. This API uses a promise to return the result. Closes a file. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1412,6 +1502,9 @@ getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void ...@@ -1412,6 +1502,9 @@ getThumbnail(callback: AsyncCallback&lt;image.PixelMap&gt;): void
Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result. Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1452,6 +1545,9 @@ getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void ...@@ -1452,6 +1545,9 @@ getThumbnail(size: Size, callback: AsyncCallback&lt;image.PixelMap&gt;): void
Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1494,6 +1590,9 @@ getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt; ...@@ -1494,6 +1590,9 @@ getThumbnail(size?: Size): Promise&lt;image.PixelMap&gt;
Obtains the file thumbnail of the given size. This API uses a promise to return the result. Obtains the file thumbnail of the given size. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#getThumbnail-2) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1539,6 +1638,9 @@ favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void ...@@ -1539,6 +1638,9 @@ favorite(isFavorite: boolean, callback: AsyncCallback&lt;void&gt;): void
Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result. Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1580,6 +1682,9 @@ favorite(isFavorite: boolean): Promise&lt;void&gt; ...@@ -1580,6 +1682,9 @@ favorite(isFavorite: boolean): Promise&lt;void&gt;
Favorites or unfavorites this file asset. This API uses a promise to return the result. Favorites or unfavorites this file asset. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [setFavorite](js-apis-photoAccessHelper.md#setfavorite-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1624,6 +1729,9 @@ isFavorite(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1624,6 +1729,9 @@ isFavorite(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result. Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1664,6 +1772,9 @@ isFavorite():Promise&lt;boolean&gt; ...@@ -1664,6 +1772,9 @@ isFavorite():Promise&lt;boolean&gt;
Checks whether this file asset is favorited. This API uses a promise to return the result. Checks whether this file asset is favorited. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1704,6 +1815,9 @@ Moves this file asset to the trash. This API uses an asynchronous callback to re ...@@ -1704,6 +1815,9 @@ Moves this file asset to the trash. This API uses an asynchronous callback to re
Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
> **NOTE**
> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1747,6 +1861,9 @@ Moves this file asset to the trash. This API uses a promise to return the result ...@@ -1747,6 +1861,9 @@ Moves this file asset to the trash. This API uses a promise to return the result
Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash.
> **NOTE**
> This API is deprecated since API Version 9. Use [deleteAssets](js-apis-photoAccessHelper.md#deleteAssets-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1791,6 +1908,9 @@ isTrash(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1791,6 +1908,9 @@ isTrash(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result. Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1831,6 +1951,9 @@ isTrash():Promise&lt;boolean&gt; ...@@ -1831,6 +1951,9 @@ isTrash():Promise&lt;boolean&gt;
Checks whether this file asset is in the trash. This API uses a promise to return the result. Checks whether this file asset is in the trash. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1867,12 +1990,18 @@ async function example() { ...@@ -1867,12 +1990,18 @@ async function example() {
Provides APIs to manage the file retrieval result. Provides APIs to manage the file retrieval result.
> **NOTE**
> This API is deprecated since API Version 9. Use [FetchResult](js-apis-photoAccessHelper.md#fetchresult) instead.
### getCount<sup>7+</sup> ### getCount<sup>7+</sup>
getCount(): number getCount(): number
Obtains the total number of files in the result set. Obtains the total number of files in the result set.
> **NOTE**
> This API is deprecated since API Version 9. Use [getCount](js-apis-photoAccessHelper.md#getcount) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -1905,6 +2034,9 @@ isAfterLast(): boolean ...@@ -1905,6 +2034,9 @@ isAfterLast(): boolean
Checks whether the cursor is in the last row of the result set. Checks whether the cursor is in the last row of the result set.
> **NOTE**
> This API is deprecated since API Version 9. Use [isAfterLast](js-apis-photoAccessHelper.md#isafterlast) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -1945,6 +2077,9 @@ close(): void ...@@ -1945,6 +2077,9 @@ close(): void
Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked. Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked.
> **NOTE**
> This API is deprecated since API Version 9. Use [close](js-apis-photoAccessHelper.md#close) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Example** **Example**
...@@ -1969,6 +2104,9 @@ getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void ...@@ -1969,6 +2104,9 @@ getFirstObject(callback: AsyncCallback&lt;FileAsset&gt;): void
Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -2006,6 +2144,9 @@ getFirstObject(): Promise&lt;FileAsset&gt; ...@@ -2006,6 +2144,9 @@ getFirstObject(): Promise&lt;FileAsset&gt;
Obtains the first file asset in the result set. This API uses a promise to return the result. Obtains the first file asset in the result set. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getFirstObject](js-apis-photoAccessHelper.md#getfirstobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -2041,7 +2182,10 @@ getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void ...@@ -2041,7 +2182,10 @@ getNextObject(callback: AsyncCallback&lt;FileAsset&gt;): void
Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**<br>Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set. > **NOTE**
>
> - Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to check that the cursor does not point to the last file asset in the result set.
> - This API is deprecated since API Version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2085,7 +2229,10 @@ getNextObject(): Promise&lt;FileAsset&gt; ...@@ -2085,7 +2229,10 @@ getNextObject(): Promise&lt;FileAsset&gt;
Obtains the next file asset in the result set. This API uses a promise to return the result. Obtains the next file asset in the result set. This API uses a promise to return the result.
> **NOTE**<br>Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to ensure that the cursor does not point to the last file asset in the result set. > **NOTE**
>
> - Before using this API, you must use [getFirstObject](#getfirstobject7) to obtain the first file asset and then use [isAfterLast](#isafterlast7) to check that the cursor does not point to the last file asset in the result set.
> - This API is deprecated since API Version 9. Use [getNextObject](js-apis-photoAccessHelper.md#getnextobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2126,6 +2273,9 @@ getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void ...@@ -2126,6 +2273,9 @@ getLastObject(callback: AsyncCallback&lt;FileAsset&gt;): void
Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -2163,6 +2313,9 @@ getLastObject(): Promise&lt;FileAsset&gt; ...@@ -2163,6 +2313,9 @@ getLastObject(): Promise&lt;FileAsset&gt;
Obtains the last file asset in the result set. This API uses a promise to return the result. Obtains the last file asset in the result set. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getLastObject](js-apis-photoAccessHelper.md#getlastobject-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -2198,6 +2351,9 @@ getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void ...@@ -2198,6 +2351,9 @@ getPositionObject(index: number, callback: AsyncCallback&lt;FileAsset&gt;): void
Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -2236,6 +2392,9 @@ getPositionObject(index: number): Promise&lt;FileAsset&gt; ...@@ -2236,6 +2392,9 @@ getPositionObject(index: number): Promise&lt;FileAsset&gt;
Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getObjectByPosition](js-apis-photoAccessHelper.md#getobjectbyposition-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -2277,6 +2436,9 @@ getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void ...@@ -2277,6 +2436,9 @@ getAllObject(callback: AsyncCallback&lt;Array&lt;FileAsset&gt;&gt;): void
Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result. Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Parameters** **Parameters**
...@@ -2316,6 +2478,9 @@ getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt; ...@@ -2316,6 +2478,9 @@ getAllObject(): Promise&lt;Array&lt;FileAsset&gt;&gt;
Obtains all the file assets in the result set. This API uses a promise to return the result. Obtains all the file assets in the result set. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getAllObjects](js-apis-photoAccessHelper.md#getallobjects-1) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
**Return value** **Return value**
...@@ -2351,6 +2516,9 @@ async function example() { ...@@ -2351,6 +2516,9 @@ async function example() {
Provides APIs to manage albums. Provides APIs to manage albums.
> **NOTE**
> This API is deprecated since API Version 9. Use [Album](js-apis-photoAccessHelper.md#album) instead.
### Attributes ### Attributes
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2371,6 +2539,9 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void ...@@ -2371,6 +2539,9 @@ commitModify(callback: AsyncCallback&lt;void&gt;): void
Commits the modification on the album attributes to the database. Commits the modification on the album attributes to the database.
> **NOTE**
> This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-2) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2409,6 +2580,9 @@ commitModify(): Promise&lt;void&gt; ...@@ -2409,6 +2580,9 @@ commitModify(): Promise&lt;void&gt;
Commits the modification on the album attributes to the database. Commits the modification on the album attributes to the database.
> **NOTE**
> This API is deprecated since API Version 9. Use [commitModify](js-apis-photoAccessHelper.md#commitmodify-3) instead.
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA **Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.WRITE_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2445,6 +2619,9 @@ getFileAssets(callback: AsyncCallback&lt;FetchFileResult&gt;): void ...@@ -2445,6 +2619,9 @@ getFileAssets(callback: AsyncCallback&lt;FetchFileResult&gt;): void
Obtains the file assets in this album. This API uses an asynchronous callback to return the result. Obtains the file assets in this album. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2484,7 +2661,10 @@ async function example() { ...@@ -2484,7 +2661,10 @@ async function example() {
getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void getFileAssets(options: MediaFetchOptions, callback: AsyncCallback&lt;FetchFileResult&gt;): void
Obtains the file assets in this album. This API uses an asynchronous callback to return the result. Obtains the file assets in this album based on specified conditions. This API uses an asynchronous callback to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -2530,7 +2710,10 @@ async function example() { ...@@ -2530,7 +2710,10 @@ async function example() {
getFileAssets(options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt; getFileAssets(options?: MediaFetchOptions): Promise&lt;FetchFileResult&gt;
Obtains the file assets in this album. This API uses a promise to return the result. Obtains the file assets in this album based on specified conditions. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API Version 9. Use [getAssets](js-apis-photoAccessHelper.md#getassets-1) instead.
**Required permissions**: ohos.permission.READ_MEDIA **Required permissions**: ohos.permission.READ_MEDIA
...@@ -2579,6 +2762,9 @@ async function example() { ...@@ -2579,6 +2762,9 @@ async function example() {
Defines information about a registered device. Defines information about a registered device.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
...@@ -2594,6 +2780,9 @@ Defines information about a registered device. ...@@ -2594,6 +2780,9 @@ Defines information about a registered device.
Enumerates media types. Enumerates media types.
> **NOTE**
> This API is deprecated since API Version 9. Use [PhotoType](js-apis-photoAccessHelper.md#phototype) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Value| Description| | Name | Value| Description|
...@@ -2608,7 +2797,9 @@ Enumerates media types. ...@@ -2608,7 +2797,9 @@ Enumerates media types.
Enumerates key file information. Enumerates key file information.
> **NOTE** > **NOTE**
> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it. >
> - The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
> - This API is deprecated since API Version 9. Use [PhotoKeys](js-apis-photoAccessHelper.md#photokeys) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2638,6 +2829,9 @@ Enumerates key file information. ...@@ -2638,6 +2829,9 @@ Enumerates key file information.
Enumerates directory types. Enumerates directory types.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Value| Description | | Name | Value| Description |
...@@ -2653,6 +2847,9 @@ Enumerates directory types. ...@@ -2653,6 +2847,9 @@ Enumerates directory types.
Enumerates the device types. Enumerates the device types.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System API**: This is a system API. **System API**: This is a system API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore **System capability**: SystemCapability.Multimedia.MediaLibrary.DistributedCore
...@@ -2671,6 +2868,9 @@ Enumerates the device types. ...@@ -2671,6 +2868,9 @@ Enumerates the device types.
Defines the options for fetching media files. Defines the options for fetching media files.
> **NOTE**
> This API is deprecated since API Version 9. Use [FetchOptions](js-apis-photoAccessHelper.md#fetchoptions) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
...@@ -2686,6 +2886,9 @@ Defines the options for fetching media files. ...@@ -2686,6 +2886,9 @@ Defines the options for fetching media files.
Defines the image size. Defines the image size.
> **NOTE**
> This API is deprecated since API Version 9. Use [image.Size](js-apis-image.md#size) instead.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
...@@ -2697,6 +2900,9 @@ Defines the image size. ...@@ -2697,6 +2900,9 @@ Defines the image size.
Defines the media asset option. Defines the media asset option.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
...@@ -2707,7 +2913,10 @@ Defines the media asset option. ...@@ -2707,7 +2913,10 @@ Defines the media asset option.
## MediaSelectOption ## MediaSelectOption
Defines media selection option. Defines the media selection option.
> **NOTE**
> This API is deprecated since API Version 9. There is no substitute API.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
......
# @ohos.resourceschedule.workScheduler (Work Scheduler) # @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks.
The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more. The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module can be used only in the stage model. > - The APIs of this module can be used only in the stage model.
> - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
## Modules to Import ## Modules to Import
...@@ -20,7 +19,7 @@ import workScheduler from '@ohos.resourceschedule.workScheduler'; ...@@ -20,7 +19,7 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
## workScheduler.startWork ## workScheduler.startWork
startWork(work: WorkInfo): void startWork(work: WorkInfo): void
Instructs the **WorkSchedulerService** to add the specified task to the execution queue. Instructs the WorkSchedulerService to add a task to the execution queue.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -71,7 +70,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -71,7 +70,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopWork ## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void stopWork(work: WorkInfo, needCancel?: boolean): void
Instructs the **WorkSchedulerService** to stop the specified task. Instructs the WorkSchedulerService to stop a task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -130,7 +129,7 @@ Obtains the latest task status. This API uses an asynchronous callback to return ...@@ -130,7 +129,7 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | Task ID. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.| | callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes** **Error codes**
...@@ -178,7 +177,7 @@ Obtains the latest task status. This API uses a promise to return the result. ...@@ -178,7 +177,7 @@ Obtains the latest task status. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ------------------------------- | ---------------------------------------- | | ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.| | Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes** **Error codes**
...@@ -210,7 +209,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -210,7 +209,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo> obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result. Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -218,13 +217,13 @@ Obtains all tasks associated with this application. This API uses an asynchronou ...@@ -218,13 +217,13 @@ Obtains all tasks associated with this application. This API uses an asynchronou
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- | | -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. All tasks associated with the current application.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | --------------- | | ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.| | Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.|
**Error codes** **Error codes**
...@@ -255,7 +254,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -255,7 +254,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(): Promise\<Array\<WorkInfo>> obtainAllWorks(): Promise\<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result. Obtains all tasks associated with the application. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -263,7 +262,7 @@ Obtains all tasks associated with this application. This API uses a promise to r ...@@ -263,7 +262,7 @@ Obtains all tasks associated with this application. This API uses a promise to r
| Type | Description | | Type | Description |
| -------------------------------------- | ------------------------------ | | -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return the result. All tasks associated with the current application.| | Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the application.|
**Error codes** **Error codes**
...@@ -292,7 +291,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -292,7 +291,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopAndClearWorks ## workScheduler.stopAndClearWorks
stopAndClearWorks(): void stopAndClearWorks(): void
Stops and cancels all tasks associated with the current application. Stops and cancels all tasks associated with the application.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -320,7 +319,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -320,7 +319,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result. Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -329,13 +328,13 @@ Checks whether the last execution of the specified task timed out. This API uses ...@@ -329,13 +328,13 @@ Checks whether the last execution of the specified task timed out. This API uses
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- | | -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| | callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ---------------------------------------- | | ------- | ---------------------------------------- |
| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| | boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.|
**Error codes** **Error codes**
...@@ -367,7 +366,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -367,7 +366,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean> isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result. Checks whether the last execution of a task timed out. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -381,7 +380,7 @@ Checks whether the last execution of the specified task timed out. This API uses ...@@ -381,7 +380,7 @@ Checks whether the last execution of the specified task timed out. This API uses
| Type | Description | | Type | Description |
| ----------------- | ---------------------------------------- | | ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.| | Promise\<boolean> | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.|
**Error codes** **Error codes**
...@@ -411,15 +410,15 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -411,15 +410,15 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## WorkInfo ## WorkInfo
Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks). Provides detailed information about the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- | | --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | Task ID. |
| bundleName | string | Yes | Name of the Work Scheduler task bundle. | | bundleName | string | Yes | Bundle name of the application that requests the task. |
| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.| | abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback. |
| networkType | [NetworkType](#networktype) | No | Network type. | | networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. | | isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. | | chargerType | [ChargingType](#chargingtype) | No | Charging type. |
...@@ -435,7 +434,7 @@ Provides detailed information about the task. For details about the constraints ...@@ -435,7 +434,7 @@ Provides detailed information about the task. For details about the constraints
| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | | parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
## NetworkType ## NetworkType
Enumerates the network types that can trigger the task. Enumerates the network types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -449,7 +448,7 @@ Enumerates the network types that can trigger the task. ...@@ -449,7 +448,7 @@ Enumerates the network types that can trigger the task.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | | NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType ## ChargingType
Enumerates the charging types that can trigger the task. Enumerates the charging types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -461,7 +460,7 @@ Enumerates the charging types that can trigger the task. ...@@ -461,7 +460,7 @@ Enumerates the charging types that can trigger the task.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | | CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus ## BatteryStatus
Enumerates the battery states that can trigger the task. Enumerates the battery states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -472,7 +471,7 @@ Enumerates the battery states that can trigger the task. ...@@ -472,7 +471,7 @@ Enumerates the battery states that can trigger the task.
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| | BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest ## StorageRequest
Enumerates the storage states that can trigger the task. Enumerates the storage states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
...@@ -27,9 +27,9 @@ Enables WLAN. ...@@ -27,9 +27,9 @@ Enables WLAN.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
...@@ -57,9 +57,9 @@ Disables WLAN. ...@@ -57,9 +57,9 @@ Disables WLAN.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
...@@ -86,9 +86,9 @@ Checks whether WLAN is enabled. ...@@ -86,9 +86,9 @@ Checks whether WLAN is enabled.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.|
**Example** **Example**
...@@ -96,8 +96,8 @@ Checks whether WLAN is enabled. ...@@ -96,8 +96,8 @@ Checks whether WLAN is enabled.
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
try { try {
let isActivate = wifi.isActivate(); let isWifiActive = wifi.isWifiActive();
console.info("isActivate:" + isActivate); console.info("isWifiActive:" + isWifiActive);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
...@@ -115,9 +115,9 @@ Starts a scan for WLAN. ...@@ -115,9 +115,9 @@ Starts a scan for WLAN.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
...@@ -143,9 +143,9 @@ Obtains the scan result. This API uses a promise to return the result. ...@@ -143,9 +143,9 @@ Obtains the scan result. This API uses a promise to return the result.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| Promise&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&nbsp;&gt; | Promise used to return the detected hotspots.| | Promise&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&nbsp;&gt; | Promise used to return the detected hotspots.|
## wifi.getScanInfos ## wifi.getScanInfos
...@@ -160,9 +160,9 @@ Obtains the scan result. This API uses an asynchronous callback to return the re ...@@ -160,9 +160,9 @@ Obtains the scan result. This API uses an asynchronous callback to return the re
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| | callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.|
**Example** **Example**
...@@ -258,15 +258,15 @@ Adds network configuration. This API uses a promise to return the result. ...@@ -258,15 +258,15 @@ Adds network configuration. This API uses a promise to return the result.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| | Promise&lt;number&gt; | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.|
**Example** **Example**
...@@ -356,10 +356,10 @@ Adds network configuration. This API uses an asynchronous callback to return the ...@@ -356,10 +356,10 @@ Adds network configuration. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.|
**Example** **Example**
...@@ -391,15 +391,15 @@ Adds the configuration of an untrusted network. This API uses a promise to retur ...@@ -391,15 +391,15 @@ Adds the configuration of an untrusted network. This API uses a promise to retur
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.|
**Example** **Example**
```js ```js
...@@ -431,10 +431,10 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca ...@@ -431,10 +431,10 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -466,15 +466,15 @@ Removes the configuration of an untrusted network. This API uses a promise to re ...@@ -466,15 +466,15 @@ Removes the configuration of an untrusted network. This API uses a promise to re
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.|
**Example** **Example**
...@@ -504,10 +504,10 @@ Removes the configuration of an untrusted network. This API uses an asynchronous ...@@ -504,10 +504,10 @@ Removes the configuration of an untrusted network. This API uses an asynchronous
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -537,15 +537,15 @@ Connects to the specified network. ...@@ -537,15 +537,15 @@ Connects to the specified network.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| networkId | number | Yes| Network configuration ID.| | networkId | number | Yes| Network configuration ID.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
...@@ -569,21 +569,21 @@ Connects to the specified network. ...@@ -569,21 +569,21 @@ Connects to the specified network.
**System API**: This is a system API. **System API**: This is a system API.
**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) **Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications)
**System capability**: **System capability**:
SystemCapability.Communication.WiFi.STA SystemCapability.Communication.WiFi.STA
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -617,9 +617,9 @@ Disconnects the network. ...@@ -617,9 +617,9 @@ Disconnects the network.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -644,16 +644,16 @@ Obtains the WLAN signal level. ...@@ -644,16 +644,16 @@ Obtains the WLAN signal level.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| rssi | number | Yes| RSSI of the hotspot, in dBm.| | rssi | number | Yes| RSSI of the hotspot, in dBm.|
| band | number | Yes| Frequency band of the WLAN AP.| | band | number | Yes| Frequency band of the WLAN AP.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| number | Signal level obtained. The value range is [0, 4].| | number | Signal level obtained. The value range is [0, 4].|
**Example** **Example**
```js ```js
...@@ -682,9 +682,9 @@ Obtains WLAN connection information. This API uses a promise to return the resul ...@@ -682,9 +682,9 @@ Obtains WLAN connection information. This API uses a promise to return the resul
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Promise used to return the WLAN connection information.| | Promise&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Promise used to return the WLAN connection information.|
## wifi.getLinkedInfo ## wifi.getLinkedInfo
...@@ -699,9 +699,9 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r ...@@ -699,9 +699,9 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[WifiLinkedInfo](#wifilinkedinfo)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -802,9 +802,9 @@ Checks whether the WLAN is connected. ...@@ -802,9 +802,9 @@ Checks whether the WLAN is connected.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.|
## wifi.getSupportedFeatures<sup>7+</sup> ## wifi.getSupportedFeatures<sup>7+</sup>
...@@ -821,9 +821,9 @@ Obtains the features supported by this device. ...@@ -821,9 +821,9 @@ Obtains the features supported by this device.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| number | Feature value. | | number | Feature value. |
**Feature IDs** **Feature IDs**
...@@ -854,15 +854,15 @@ Checks whether the device supports the specified WLAN feature. ...@@ -854,15 +854,15 @@ Checks whether the device supports the specified WLAN feature.
**Parameters** **Parameters**
| **Name**| **Type**| Mandatory| **Description**| | **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| featureId | number | Yes| Feature ID.| | featureId | number | Yes| Feature ID.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| | boolean | Returns **true** if the feature is supported; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -892,9 +892,9 @@ Obtains the device MAC address. ...@@ -892,9 +892,9 @@ Obtains the device MAC address.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| string[] | MAC address obtained.| | string[] | MAC address obtained.|
**Example** **Example**
```js ```js
...@@ -921,9 +921,9 @@ Obtains IP information. ...@@ -921,9 +921,9 @@ Obtains IP information.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| [IpInfo](#ipinfo7) | IP information obtained.| | [IpInfo](#ipinfo7) | IP information obtained.|
**Example** **Example**
```js ```js
...@@ -966,9 +966,9 @@ Obtains the country code. ...@@ -966,9 +966,9 @@ Obtains the country code.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| string | Country code obtained.| | string | Country code obtained.|
**Example** **Example**
```js ```js
...@@ -996,9 +996,9 @@ Re-associates with the network. ...@@ -996,9 +996,9 @@ Re-associates with the network.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1025,9 +1025,9 @@ Reconnects to the network. ...@@ -1025,9 +1025,9 @@ Reconnects to the network.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1054,9 +1054,9 @@ Obtains network configuration. ...@@ -1054,9 +1054,9 @@ Obtains network configuration.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | Array of network configuration obtained.| | &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; | Array of network configuration obtained.|
**Example** **Example**
```js ```js
...@@ -1084,15 +1084,15 @@ Updates network configuration. ...@@ -1084,15 +1084,15 @@ Updates network configuration.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.|
**Example** **Example**
```js ```js
...@@ -1125,15 +1125,15 @@ Disables network configuration. ...@@ -1125,15 +1125,15 @@ Disables network configuration.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netId | number | Yes| ID of the network configuration to disable.| | netId | number | Yes| ID of the network configuration to disable.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1161,9 +1161,9 @@ Removes the configuration of all networks. ...@@ -1161,9 +1161,9 @@ Removes the configuration of all networks.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1190,15 +1190,15 @@ Removes the specified network configuration. ...@@ -1190,15 +1190,15 @@ Removes the specified network configuration.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| id | number | Yes| ID of the network configuration to remove.| | id | number | Yes| ID of the network configuration to remove.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1226,9 +1226,9 @@ Enables this hotspot. ...@@ -1226,9 +1226,9 @@ Enables this hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1255,9 +1255,9 @@ Disables this hotspot. ...@@ -1255,9 +1255,9 @@ Disables this hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1284,9 +1284,9 @@ Checks whether the hotspot supports dual band. ...@@ -1284,9 +1284,9 @@ Checks whether the hotspot supports dual band.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| | boolean | Returns **true** if the feature is supported; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1314,9 +1314,9 @@ Checks whether this hotspot is active. ...@@ -1314,9 +1314,9 @@ Checks whether this hotspot is active.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1344,15 +1344,15 @@ Sets hotspot configuration. ...@@ -1344,15 +1344,15 @@ Sets hotspot configuration.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| | config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1405,9 +1405,9 @@ obtains hotspot configuration. ...@@ -1405,9 +1405,9 @@ obtains hotspot configuration.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.|
**Example** **Example**
```js ```js
...@@ -1435,9 +1435,9 @@ Obtains information about the connected stations. ...@@ -1435,9 +1435,9 @@ Obtains information about the connected stations.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt; | Connected stations obtained.| | &nbsp;Array&lt;[StationInfo](#stationinfo7)&gt; | Connected stations obtained.|
**Example** **Example**
```js ```js
...@@ -1478,9 +1478,9 @@ Obtains P2P link information. This API uses a promise to return the result. ...@@ -1478,9 +1478,9 @@ Obtains P2P link information. This API uses a promise to return the result.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Promise used to return the P2P link information obtained.| | Promise&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Promise used to return the P2P link information obtained.|
...@@ -1521,9 +1521,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t ...@@ -1521,9 +1521,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -1554,9 +1554,9 @@ Obtains the current P2P group information. This API uses a promise to return the ...@@ -1554,9 +1554,9 @@ Obtains the current P2P group information. This API uses a promise to return the
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Promise used to return the P2P group information obtained.| | Promise&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Promise used to return the P2P group information obtained.|
## wifi.getCurrentGroup<sup>8+</sup> ## wifi.getCurrentGroup<sup>8+</sup>
...@@ -1571,9 +1571,9 @@ Obtains the current P2P group information. This API uses an asynchronous callbac ...@@ -1571,9 +1571,9 @@ Obtains the current P2P group information. This API uses an asynchronous callbac
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[WifiP2pGroupInfo](#wifip2pgroupinfo8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -1604,9 +1604,9 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r ...@@ -1604,9 +1604,9 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Promise used to return the peer device list.| | Promise&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Promise used to return the peer device list.|
## wifi.getP2pPeerDevices<sup>8+</sup> ## wifi.getP2pPeerDevices<sup>8+</sup>
...@@ -1621,9 +1621,9 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou ...@@ -1621,9 +1621,9 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.|
**Example** **Example**
```js ```js
...@@ -1684,15 +1684,15 @@ Creates a P2P group. ...@@ -1684,15 +1684,15 @@ Creates a P2P group.
**Parameters** **Parameters**
| **Name**| **Type**| Mandatory| **Description**| | **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1753,9 +1753,9 @@ Removes this P2P group. ...@@ -1753,9 +1753,9 @@ Removes this P2P group.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1781,15 +1781,15 @@ Sets up a P2P connection. ...@@ -1781,15 +1781,15 @@ Sets up a P2P connection.
**Parameters** **Parameters**
| **Name**| **Type**| Mandatory| **Description**| | **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
...@@ -1871,9 +1871,9 @@ Cancels this P2P connection. ...@@ -1871,9 +1871,9 @@ Cancels this P2P connection.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1898,9 +1898,9 @@ Starts to discover devices. ...@@ -1898,9 +1898,9 @@ Starts to discover devices.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1925,9 +1925,9 @@ Stops discovering devices. ...@@ -1925,9 +1925,9 @@ Stops discovering devices.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -1955,15 +1955,15 @@ Deletes a persistent group. ...@@ -1955,15 +1955,15 @@ Deletes a persistent group.
**Parameters** **Parameters**
| **Name**| **Type**| Mandatory| **Description**| | **Name**| **Type**| Mandatory| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| netId | number | Yes| ID of the group to delete.| | netId | number | Yes| ID of the group to delete.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -2010,15 +2010,15 @@ Sets the device name. ...@@ -2010,15 +2010,15 @@ Sets the device name.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| devName | string | Yes| Device name to set.| | devName | string | Yes| Device name to set.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
```js ```js
...@@ -2044,10 +2044,10 @@ Registers the WLAN state change events. ...@@ -2044,10 +2044,10 @@ Registers the WLAN state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiStateChange**.| | type | string | Yes| Event type. The value is **wifiStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN state.|
**WLAN states** **WLAN states**
...@@ -2071,10 +2071,10 @@ Unregisters the WLAN state change events. ...@@ -2071,10 +2071,10 @@ Unregisters the WLAN state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiStateChange**.| | type | string | Yes| Event type. The value is **wifiStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
```js ```js
...@@ -2104,10 +2104,10 @@ Registers the WLAN connection state change events. ...@@ -2104,10 +2104,10 @@ Registers the WLAN connection state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiConnectionChange**.| | type | string | Yes| Event type. The value is **wifiConnectionChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN connection state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN connection state.|
**WLAN connection states** **WLAN connection states**
...@@ -2129,10 +2129,10 @@ Unregisters the WLAN connection state change events. ...@@ -2129,10 +2129,10 @@ Unregisters the WLAN connection state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiConnectionChange**.| | type | string | Yes| Event type. The value is **wifiConnectionChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
```js ```js
...@@ -2161,10 +2161,10 @@ Registers the WLAN scan state change events. ...@@ -2161,10 +2161,10 @@ Registers the WLAN scan state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiScanStateChange**.| | type | string | Yes| Event type. The value is **wifiScanStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN scan state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the WLAN scan state.|
**WLAN scan states** **WLAN scan states**
...@@ -2218,10 +2218,10 @@ Registers the RSSI change events. ...@@ -2218,10 +2218,10 @@ Registers the RSSI change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiRssiChange**.| | type | string | Yes| Event type. The value is **wifiRssiChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the RSSI, in dBm.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the RSSI, in dBm.|
## wifi.off('wifiRssiChange')<sup>7+</sup> ## wifi.off('wifiRssiChange')<sup>7+</sup>
...@@ -2236,9 +2236,9 @@ Unregisters the RSSI change events. ...@@ -2236,9 +2236,9 @@ Unregisters the RSSI change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **wifiRssiChange**.| | type | string | Yes| Event type. The value is **wifiRssiChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2254,7 +2254,58 @@ wifi.on("wifiRssiChange", recvWifiRssiChangeFunc); ...@@ -2254,7 +2254,58 @@ wifi.on("wifiRssiChange", recvWifiRssiChangeFunc);
// Unregister an event. // Unregister an event.
wifi.off("wifiRssiChange", recvWifiRssiChangeFunc); wifi.off("wifiRssiChange", recvWifiRssiChangeFunc);
```
## wifi.on('streamChange')<sup>7+</sup>
on(type: "streamChange", callback: Callback&lt;number&gt;): void
Registers Wi-Fi stream changes.
**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **streamChange**. |
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the Wi-Fi stream change, which can be any of the following values:<br>- **0**: No change.<br>- **1**: Downward.<br>- **2**: Upward.<br>- **3**: Bidirectional. |
## wifi.off('streamChange')<sup>7+</sup>
off(type: "streamChange", callback: Callback&lt;number&gt;): void
Unregisters Wi-Fi stream changes.
**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **streamChange**. |
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the Wi-Fi stream change, which can be any of the following values:<br>- **0**: No change.<br>- **1**: Downward.<br>- **2**: Upward.<br>- **3**: Bidirectional. |
**Example**
```js
import wifi from '@ohos.wifi';
var recvStreamChangeFunc = result => {
console.info("Receive stream change event: " + result);
}
// Register an event.
wifi.on("streamChange", recvStreamChangeFunc);
// Unregister an event.
wifi.off("streamChange", recvStreamChangeFunc);
``` ```
## wifi.on('hotspotStateChange')<sup>7+</sup> ## wifi.on('hotspotStateChange')<sup>7+</sup>
on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void
...@@ -2267,10 +2318,10 @@ Registers the hotspot state change events. ...@@ -2267,10 +2318,10 @@ Registers the hotspot state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStateChange**.| | type | string | Yes| Event type. The value is **hotspotStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the hotspot state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the hotspot state.|
**Hotspot states** **Hotspot states**
...@@ -2308,11 +2359,110 @@ Unregisters the hotspot state change events. ...@@ -2308,11 +2359,110 @@ Unregisters the hotspot state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStateChange**.| | type | string | Yes| Event type. The value is **hotspotStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
## wifi.on('hotspotStaJoin')<sup>7+</sup>
on(type: "hotspotStaJoin", callback: Callback&lt;StationInfo&gt;): void
Registers the connection of an STA to a Wi-Fi hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStaJoin**. |
| callback | Callback&lt;StationInfo&gt; | Yes| Callback invoked when an STA is connected to a Wi-Fi hotspot. |
## wifi.off('hotspotStaJoin')<sup>7+</sup>
off(type: "hotspotStaJoin", callback: Callback&lt;StationInfo&gt;): void
Unregisters the connection of an STA to a Wi-Fi hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStaJoin**. |
| callback | Callback&lt;StationInfo&gt; | Yes| Callback for the connection of an STA to a Wi-Fi hotspot. |
**Example**
```js
import wifi from '@ohos.wifi';
var recvHotspotStaJoinFunc = result => {
console.info("Receive hotspot sta join event: " + result);
}
// Register an event.
wifi.on("hotspotStaJoin", recvHotspotStaJoinFunc);
// Unregister an event.
wifi.off("hotspotStaJoin", recvHotspotStaJoinFunc);
```
## wifi.on('hotspotStaLeave')<sup>7+</sup>
on(type: "hotspotStaLeave", callback: Callback&lt;StationInfo&gt;): void
Registers the disconnection of an STA from a Wi-Fi hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStaLeave**. |
| callback | Callback&lt;StationInf]&gt; | Yes| Callback invoked when an STA is disconnected from a Wi-Fi hotspot. |
## wifi.off('hotspotStaLeave')<sup>7+</sup>
off(type: "hotspotStaLeave", callback: Callback&lt;StationInfo&gt;): void
Unregisters the disconnection of an STA from a Wi-Fi hotspot.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT
**System capability**: SystemCapability.Communication.WiFi.AP.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **hotspotStaLeave**. |
| callback | Callback&lt;StationInf]&gt; | Yes| Callback for the disconnection of an STA from a Wi-Fi hotspot. |
**Example**
```js
import wifi from '@ohos.wifi';
var recvHotspotStaLeaveFunc = result => {
console.info("Receive hotspot sta leave event: " + result);
}
// Register an event.
wifi.on("hotspotStaLeave", recvHotspotStaLeaveFunc);
// Unregister an event.
wifi.off("hotspotStaLeave", recvHotspotStaLeaveFunc);
```
## wifi.on('p2pStateChange')<sup>8+</sup> ## wifi.on('p2pStateChange')<sup>8+</sup>
...@@ -2326,10 +2476,10 @@ Registers the P2P state change events. ...@@ -2326,10 +2476,10 @@ Registers the P2P state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pStateChange**.| | type | string | Yes| Event type. The value is **p2pStateChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P state.|
**P2P states** **P2P states**
...@@ -2353,9 +2503,9 @@ Unregisters the P2P state change events. ...@@ -2353,9 +2503,9 @@ Unregisters the P2P state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pStateChange**.| | type | string | Yes| Event type. The value is **p2pStateChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2373,7 +2523,7 @@ wifi.on("p2pStateChange", recvP2pStateChangeFunc); ...@@ -2373,7 +2523,7 @@ wifi.on("p2pStateChange", recvP2pStateChangeFunc);
wifi.off("p2pStateChange", recvP2pStateChangeFunc); wifi.off("p2pStateChange", recvP2pStateChangeFunc);
``` ```
## wifi.on('p2pConnectionChange')<sup>8+</sup> ## wifi.on('p2pConnectionChange')<sup>8+</sup>
on(type: "p2pConnectionChange", callback: Callback&lt;WifiP2pLinkedInfo&gt;): void on(type: "p2pConnectionChange", callback: Callback&lt;WifiP2pLinkedInfo&gt;): void
...@@ -2385,10 +2535,10 @@ Registers the P2P connection state change events. ...@@ -2385,10 +2535,10 @@ Registers the P2P connection state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pConnectionChange**.| | type | string | Yes| Event type. The value is **p2pConnectionChange**.|
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Yes| Callback invoked to return the P2P connection state.| | callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | Yes| Callback invoked to return the P2P connection state.|
## wifi.off('p2pConnectionChange')<sup>8+</sup> ## wifi.off('p2pConnectionChange')<sup>8+</sup>
...@@ -2403,9 +2553,9 @@ Unregisters the P2P connection state change events. ...@@ -2403,9 +2553,9 @@ Unregisters the P2P connection state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pConnectionChange**.| | type | string | Yes| Event type. The value is **p2pConnectionChange**.|
| callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo8)&gt; | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2435,10 +2585,10 @@ Registers the P2P device state change events. ...@@ -2435,10 +2585,10 @@ Registers the P2P device state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDeviceChange**.| | type | string | Yes| Event type. The value is **p2pDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the P2P device state.| | callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the P2P device state.|
## wifi.off('p2pDeviceChange')<sup>8+</sup> ## wifi.off('p2pDeviceChange')<sup>8+</sup>
...@@ -2453,9 +2603,9 @@ Unregisters the P2P device state change events. ...@@ -2453,9 +2603,9 @@ Unregisters the P2P device state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDeviceChange**.| | type | string | Yes| Event type. The value is **p2pDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pDevice](#wifip2pdevice8)&gt; | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2463,7 +2613,7 @@ Unregisters the P2P device state change events. ...@@ -2463,7 +2613,7 @@ Unregisters the P2P device state change events.
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pDeviceChangeFunc = result => { var recvP2pDeviceChangeFunc = result => {
console.info("Receive recv p2p device change event: " + result); console.info("Receive p2p device change event: " + result);
} }
// Register an event. // Register an event.
...@@ -2485,9 +2635,9 @@ Registers the P2P peer device state change events. ...@@ -2485,9 +2635,9 @@ Registers the P2P peer device state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the P2P peer device state.| | callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | Yes| Callback invoked to return the P2P peer device state.|
...@@ -2503,9 +2653,9 @@ Unregisters the P2P peer device state change events. ...@@ -2503,9 +2653,9 @@ Unregisters the P2P peer device state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.|
| callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;[WifiP2pDevice[]](#wifip2pdevice8)&gt; | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2513,7 +2663,7 @@ Unregisters the P2P peer device state change events. ...@@ -2513,7 +2663,7 @@ Unregisters the P2P peer device state change events.
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pPeerDeviceChangeFunc = result => { var recvP2pPeerDeviceChangeFunc = result => {
console.info("Receive recv p2p peer device change event: " + result); console.info("Receive p2p peer device change event: " + result);
} }
// Register an event. // Register an event.
...@@ -2535,10 +2685,10 @@ Registers the P2P persistent group state change events. ...@@ -2535,10 +2685,10 @@ Registers the P2P persistent group state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.|
| callback | Callback&lt;void&gt; | Yes| Callback invoked to return the P2P persistent group state.| | callback | Callback&lt;void&gt; | Yes| Callback invoked to return the P2P persistent group state.|
## wifi.off('p2pPersistentGroupChange')<sup>8+</sup> ## wifi.off('p2pPersistentGroupChange')<sup>8+</sup>
...@@ -2553,9 +2703,9 @@ Unregisters the P2P persistent group state change events. ...@@ -2553,9 +2703,9 @@ Unregisters the P2P persistent group state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.|
| callback | Callback&lt;void&gt; | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;void&gt; | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2563,7 +2713,7 @@ Unregisters the P2P persistent group state change events. ...@@ -2563,7 +2713,7 @@ Unregisters the P2P persistent group state change events.
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pPersistentGroupChangeFunc = result => { var recvP2pPersistentGroupChangeFunc = result => {
console.info("Receive recv p2p persistent group change event: " + result); console.info("Receive p2p persistent group change event: " + result);
} }
// Register an event. // Register an event.
...@@ -2586,10 +2736,10 @@ Registers the P2P device discovery state change events. ...@@ -2586,10 +2736,10 @@ Registers the P2P device discovery state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.|
| callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P device discovery state.| | callback | Callback&lt;number&gt; | Yes| Callback invoked to return the P2P device discovery state.|
**P2P discovered device states** **P2P discovered device states**
...@@ -2611,9 +2761,9 @@ Unregisters the P2P device discovery state change events. ...@@ -2611,9 +2761,9 @@ Unregisters the P2P device discovery state change events.
**Parameters** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.|
| callback | Callback&lt;number&gt; | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| | callback | Callback&lt;number&gt; | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.|
**Example** **Example**
...@@ -2621,7 +2771,7 @@ Unregisters the P2P device discovery state change events. ...@@ -2621,7 +2771,7 @@ Unregisters the P2P device discovery state change events.
import wifi from '@ohos.wifi'; import wifi from '@ohos.wifi';
var recvP2pDiscoveryChangeFunc = result => { var recvP2pDiscoveryChangeFunc = result => {
console.info("Receive recv p2p discovery change event: " + result); console.info("Receive p2p discovery change event: " + result);
} }
// Register an event. // Register an event.
......
...@@ -11,7 +11,7 @@ The **WLAN** module provides basic wireless local area network (WLAN) functions, ...@@ -11,7 +11,7 @@ The **WLAN** module provides basic wireless local area network (WLAN) functions,
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
``` ```
## wifi.enableWifi<sup>9+</sup> ## wifiManager.enableWifi<sup>9+</sup>
enableWifi(): void enableWifi(): void
...@@ -23,12 +23,6 @@ Enables WLAN. ...@@ -23,12 +23,6 @@ Enables WLAN.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Error codes** **Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
...@@ -49,7 +43,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -49,7 +43,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.disableWifi<sup>9+</sup> ## wifiManager.disableWifi<sup>9+</sup>
disableWifi(): void disableWifi(): void
...@@ -61,12 +55,6 @@ Disables WLAN. ...@@ -61,12 +55,6 @@ Disables WLAN.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Error codes** **Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
...@@ -87,7 +75,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -87,7 +75,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.isWifiActive<sup>9+</sup> ## wifiManager.isWifiActive<sup>9+</sup>
isWifiActive(): boolean isWifiActive(): boolean
...@@ -117,14 +105,14 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -117,14 +105,14 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
let isActivate = wifiManager.isActivate(); let isWifiActive = wifiManager.isWifiActive();
console.info("isActivate:" + isActivate); console.info("isWifiActive:" + isWifiActive);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.scan<sup>9+</sup> ## wifiManager.scan<sup>9+</sup>
scan(): void scan(): void
...@@ -134,11 +122,37 @@ Starts a scan for WLAN. ...@@ -134,11 +122,37 @@ Starts a scan for WLAN.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
**Return value** **Error codes**
| **Type**| **Description**| For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | 2501000 | Operation failed.|
**Example**
```js
import wifiManager from '@ohos.wifiManager';
try {
wifiManager.scan();
}catch(error){
console.error("failed:" + JSON.stringify(error));
}
```
## wifiManager.startScan<sup>10+</sup>
startScan(): void
**System API**: This is a system API.
Starts a scan for WLAN.
**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION
**System capability**: SystemCapability.Communication.WiFi.STA
**Error codes** **Error codes**
...@@ -154,22 +168,164 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -154,22 +168,164 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
wifiManager.scan(); wifiManager.startScan();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifiManager.getScanResults<sup>10+</sup>
## wifi.getScanInfoList<sup>9+</sup> getScanResults(): Promise&lt;Array&lt;WifiScanInfo&gt;&gt;
getScanInfoList(): Array&lt;WifiScanInfo&gt;; Obtains the scan result. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Promise&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&nbsp;&gt; | Promise used to return the Returns the hotspots detected.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
## wifiManager.getScanResults<sup>10+</sup>
getScanResults(callback: AsyncCallback&lt;Array&lt;WifiScanInfo&gt;&gt;): void
Obtains the scan result. Obtains the scan result. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION)) **Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;&nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.|
| Array&lt;[WifiScanInfo](#wifiscaninfo)&gt; | Returns the hotspots detected.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
**Example**
```js
import wifiManager from '@ohos.wifiManager';
wifiManager.getScanResults((err, result) => {
if (err) {
console.error("get scan info error");
return;
}
var len = Object.keys(result).length;
console.log("wifi received scan info: " + len);
for (var i = 0; i < len; ++i) {
console.info("ssid: " + result[i].ssid);
console.info("bssid: " + result[i].bssid);
console.info("capabilities: " + result[i].capabilities);
console.info("securityType: " + result[i].securityType);
console.info("rssi: " + result[i].rssi);
console.info("band: " + result[i].band);
console.info("frequency: " + result[i].frequency);
console.info("channelWidth: " + result[i].channelWidth);
console.info("timestamp: " + result[i].timestamp);
}
});
wifiManager.getScanResults().then(result => {
var len = Object.keys(result).length;
console.log("wifi received scan info: " + len);
for (var i = 0; i < len; ++i) {
console.info("ssid: " + result[i].ssid);
console.info("bssid: " + result[i].bssid);
console.info("capabilities: " + result[i].capabilities);
console.info("securityType: " + result[i].securityType);
console.info("rssi: " + result[i].rssi);
console.info("band: " + result[i].band);
console.info("frequency: " + result[i].frequency);
console.info("channelWidth: " + result[i].channelWidth);
console.info("timestamp: " + result[i].timestamp);
}
});
```
## wifiManager.getScanResultsSync<sup>10+</sup>
getScanResultsSync(): &nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt;
Obtains the scan result. This API returns the result synchronously.
**Required permissions**: ohos.permission.GET_WIFI_INFO and (ohos.permission.GET_WIFI_PEERS_MAC or (ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION))
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;[WifiScanInfo](#wifiscaninfo)&gt; | Scan result obtained.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
**Example**
```js
import wifiManager from '@ohos.wifiManager';
try {
let scanInfoList = wifiManager.getScanResultsSync();
console.info("scanInfoList:" + JSON.stringify(scanInfoList));
let len = Object.keys(scanInfoList).length;
console.log("wifi received scan info: " + len);
if(len > 0){
for (var i = 0; i < len; ++i) {
console.info("ssid: " + scanInfoList[i].ssid);
console.info("bssid: " + scanInfoList[i].bssid);
console.info("capabilities: " + scanInfoList[i].capabilities);
console.info("securityType: " + scanInfoList[i].securityType);
console.info("rssi: " + scanInfoList[i].rssi);
console.info("band: " + scanInfoList[i].band);
console.info("frequency: " + scanInfoList[i].frequency);
console.info("channelWidth: " + scanInfoList[i].channelWidth);
console.info("timestamp: " + scanInfoList[i].timestamp);
}
}
}catch(error){
console.error("failed:" + JSON.stringify(error));
}
```
## wifiManager.getScanInfoList<sup>10+</sup>
getScanInfoList(): Array&lt;WifiScanInfo&gt;;
Obtains the scanning result.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
...@@ -224,6 +380,7 @@ Represents WLAN hotspot information. ...@@ -224,6 +380,7 @@ Represents WLAN hotspot information.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.|
| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| | bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.|
| bssidType<sup>10+</sup>| DeviceAddressType | Yes| No| BSSID type of the hotspot.|
| capabilities | string | Yes| No| Hotspot capabilities.| | capabilities | string | Yes| No| Hotspot capabilities.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.|
| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| | rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.|
...@@ -235,6 +392,16 @@ Represents WLAN hotspot information. ...@@ -235,6 +392,16 @@ Represents WLAN hotspot information.
| infoElems | Array&lt;[WifiInfoElem](#wifiinfoelem9)&gt; | Yes| No| Information elements.| | infoElems | Array&lt;[WifiInfoElem](#wifiinfoelem9)&gt; | Yes| No| Information elements.|
| timestamp | number | Yes| No| Timestamp.| | timestamp | number | Yes| No| Timestamp.|
## DeviceAddressType <sup>10+</sup>
Enumerates the Wi-Fi device address (MAC/BISSID) types.
**System capability**: SystemCapability.Communication.WiFi.Core
| **Name**| **Value**| **Description**|
| -------- | -------- | -------- |
| RANDOM_DEVICE_ADDRESS | 0 | Random device address.|
| REAL_DEVICE_ADDRESS | 1 | Read device address.|
## WifiSecurityType<sup>9+</sup> ## WifiSecurityType<sup>9+</sup>
...@@ -317,7 +484,84 @@ Enumerates the WLAN channel widths. ...@@ -317,7 +484,84 @@ Enumerates the WLAN channel widths.
| WIDTH_80MHZ_PLUS | 4 | 80 MHz<sup>+</sup>| | WIDTH_80MHZ_PLUS | 4 | 80 MHz<sup>+</sup>|
| WIDTH_INVALID | 5 | Invalid value| | WIDTH_INVALID | 5 | Invalid value|
## wifi.addDeviceConfig<sup>9+</sup> ## wifiManager.setScanAlwaysAllowed<sup>10+</sup>
setScanAlwaysAllowed(isScanAlwaysAllowed: boolean): void
Sets whether scan is always allowed.
**System API**: This is a system API.
**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG
**System capability**: SystemCapability.Communication.WiFi.STA
**Parameters**
| **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- |
| isScanAlwaysAllowed | boolean | Yes| Whether scan is always allowed.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
```js
import wifiManager from '@ohos.wifiManager';
try {
let isScanAlwaysAllowed = true;
wifiManager.setScanAlwaysAllowed(isScanAlwaysAllowed);
});
}catch(error){
console.error("failed:" + JSON.stringify(error));
}
```
## wifiManager.getScanAlwaysAllowed<sup>10+</sup>
getScanAlwaysAllowed(): boolean
Obtains whether scan is always allowed.
**System API**: This is a system API.
**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean| Whether scan is always allowed. The value **true** means scan is allowed; the value **false** means the opposite.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
**Example**
```js
import wifiManager from '@ohos.wifiManager';
try {
let isScanAlwaysAllowed = wifiManager.getScanAlwaysAllowed();
console.info("isScanAlwaysAllowed:" + ret);
}catch(error){
console.error("failed:" + JSON.stringify(error));
}
```
## wifiManager.addDeviceConfig<sup>9+</sup>
addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt; addDeviceConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
...@@ -379,6 +623,7 @@ Represents the WLAN configuration. ...@@ -379,6 +623,7 @@ Represents the WLAN configuration.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| | ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.|
| bssid | string | Yes| No| BSSID of the hotspot.| | bssid | string | Yes| No| BSSID of the hotspot.|
| bssidType<sup>10+</sup> | DeviceAddressType | Yes| No| BSSID type of the hotspot.|
| preSharedKey | string | Yes| No| PSK of the hotspot.| | preSharedKey | string | Yes| No| PSK of the hotspot.|
| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| | isHiddenSsid | boolean | Yes| No| Whether the network is hidden.|
| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| | securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.|
...@@ -389,8 +634,8 @@ Represents the WLAN configuration. ...@@ -389,8 +634,8 @@ Represents the WLAN configuration.
| randomMacAddr | string | Yes| No| Random MAC address.<br>**System API**: This is a system API.| | randomMacAddr | string | Yes| No| Random MAC address.<br>**System API**: This is a system API.|
| ipType | [IpType](#iptype9) | Yes| No| IP address type.<br>**System API**: This is a system API.| | ipType | [IpType](#iptype9) | Yes| No| IP address type.<br>**System API**: This is a system API.|
| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.<br>**System API**: This is a system API.| | staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.<br>**System API**: This is a system API.|
| eapConfig<sup>9+</sup> | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.<br>**System API**: This is a system API.| | eapConfig<sup>10+</sup> | [WifiEapConfig](#wifieapconfig10) | Yes| No| EAP configuration.|
| proxyConfig<sup>10+</sup> | WifiProxyConfig | Yes| No| Proxy configuration.<br>**System API**: This is a system API.|
## IpType<sup>9+</sup> ## IpType<sup>9+</sup>
...@@ -425,18 +670,16 @@ Represents IP configuration information. ...@@ -425,18 +670,16 @@ Represents IP configuration information.
| domains | Array&lt;string&gt; | Yes| No| Domain information.| | domains | Array&lt;string&gt; | Yes| No| Domain information.|
## WifiEapConfig<sup>9+</sup> ## WifiEapConfig<sup>10+</sup>
Represents EAP configuration information. Represents EAP configuration information.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.| | eapMethod | [EapMethod](#eapmethod10) | Yes| No| EAP authentication method.|
| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.| | phase2Method | [Phase2Method](#phase2method10) | Yes| No| Phase 2 authentication method.|
| identity | string | Yes| No| Identity Information.| | identity | string | Yes| No| Identity Information.|
| anonymousIdentity | string | Yes| No| Anonymous identity.| | anonymousIdentity | string | Yes| No| Anonymous identity.|
| password | string | Yes| No| Password.| | password | string | Yes| No| Password.|
...@@ -452,12 +695,10 @@ Represents EAP configuration information. ...@@ -452,12 +695,10 @@ Represents EAP configuration information.
| eapSubId | number | Yes| No| Sub-ID of the SIM card.| | eapSubId | number | Yes| No| Sub-ID of the SIM card.|
## EapMethod<sup>9+</sup> ## EapMethod<sup>10+</sup>
Enumerates the EAP authentication methods. Enumerates the EAP authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description| | Name| Value| Description|
...@@ -473,12 +714,10 @@ Enumerates the EAP authentication methods. ...@@ -473,12 +714,10 @@ Enumerates the EAP authentication methods.
| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| | EAP_UNAUTH_TLS | 8 | UNAUTH TLS.|
## Phase2Method<sup>9+</sup> ## Phase2Method<sup>10+</sup>
Enumerates the Phase 2 authentication methods. Enumerates the Phase 2 authentication methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description| | Name| Value| Description|
...@@ -493,7 +732,37 @@ Enumerates the Phase 2 authentication methods. ...@@ -493,7 +732,37 @@ Enumerates the Phase 2 authentication methods.
| PHASE2_AKA_PRIME | 7 | AKA Prime.| | PHASE2_AKA_PRIME | 7 | AKA Prime.|
## wifi.addDeviceConfig<sup>9+</sup> ## WifiProxyConfig <sup>10+</sup>
Represents the Wi-Fi proxy configuration.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| proxyMethod | ProxyMethod | Yes| No| Proxy method.|
| pacWebAddress | string | Yes| No| PAC web address of the proxy automatically configured.|
| serverHostName | string | Yes| No| Server host name of the proxy manually configured.|
| serverPort | string | Yes| No| Server port of the proxy manually configured.|
| exclusionObjects | string | Yes| No| Excluded objects of the manually configured proxy. Multiple objects are separated by commas (,).|
## ProxyMethod<sup>10+</sup>
Enumerates the Wi-Fi proxy methods.
**System API**: This is a system API.
**System capability**: SystemCapability.Communication.WiFi.STA
| Name| Value| Description|
| -------- | -------- | -------- |
| METHOD_NONE | 0 | No proxy.|
| METHOD_AUTO | 1 | Use an automatically configured proxy.|
| METHOD_MANUAL | 2 | Use a manually configured proxy.|
## wifiManager.addDeviceConfig<sup>9+</sup>
addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): void addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): void
...@@ -539,7 +808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -539,7 +808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.addCandidateConfig<sup>9+</sup> ## wifiManager.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig): Promise&lt;number&gt; addCandidateConfig(config: WifiDeviceConfig): Promise&lt;number&gt;
...@@ -587,7 +856,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -587,7 +856,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
````` `````
## wifi.addCandidateConfig<sup>9+</sup> ## wifiManager.addCandidateConfig<sup>9+</sup>
addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): void addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback&lt;number&gt;): void
...@@ -630,7 +899,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -630,7 +899,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
````` `````
## wifi.removeCandidateConfig<sup>9+</sup> ## wifiManager.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number): Promise&lt;void&gt; removeCandidateConfig(networkId: number): Promise&lt;void&gt;
...@@ -675,7 +944,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -675,7 +944,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.removeCandidateConfig<sup>9+</sup> ## wifiManager.removeCandidateConfig<sup>9+</sup>
removeCandidateConfig(networkId: number, callback: AsyncCallback&lt;void&gt;): void removeCandidateConfig(networkId: number, callback: AsyncCallback&lt;void&gt;): void
...@@ -714,7 +983,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -714,7 +983,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.getCandidateConfigs<sup>9+</sup> ## wifiManager.getCandidateConfigs<sup>9+</sup>
getCandidateConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; getCandidateConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
...@@ -760,7 +1029,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -760,7 +1029,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
````` `````
## wifi.connectToCandidateConfig<sup>9+</sup> ## wifiManager.connectToCandidateConfig<sup>9+</sup>
connectToCandidateConfig(networkId: number): void connectToCandidateConfig(networkId: number): void
...@@ -799,7 +1068,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -799,7 +1068,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.connectToNetwork<sup>9+</sup> ## wifiManager.connectToNetwork<sup>9+</sup>
connectToNetwork(networkId: number): void connectToNetwork(networkId: number): void
...@@ -839,7 +1108,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -839,7 +1108,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.connectToDevice<sup>9+</sup> ## wifiManager.connectToDevice<sup>9+</sup>
connectToDevice(config: WifiDeviceConfig): void connectToDevice(config: WifiDeviceConfig): void
...@@ -884,7 +1153,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -884,7 +1153,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.disconnect<sup>9+</sup> ## wifiManager.disconnect<sup>9+</sup>
disconnect(): void disconnect(): void
...@@ -916,7 +1185,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -916,7 +1185,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.getSignalLevel<sup>9+</sup> ## wifiManager.getSignalLevel<sup>9+</sup>
getSignalLevel(rssi: number, band: number): number getSignalLevel(rssi: number, band: number): number
...@@ -962,7 +1231,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -962,7 +1231,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.getLinkedInfo<sup>9+</sup> ## wifiManager.getLinkedInfo<sup>9+</sup>
getLinkedInfo(): Promise&lt;WifiLinkedInfo&gt; getLinkedInfo(): Promise&lt;WifiLinkedInfo&gt;
...@@ -987,7 +1256,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -987,7 +1256,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| 2501000 | Operation failed.| | 2501000 | Operation failed.|
| 2501001 | Wifi is closed.| | 2501001 | Wifi is closed.|
## wifi.getLinkedInfo<sup>9+</sup> ## wifiManager.getLinkedInfo<sup>9+</sup>
getLinkedInfo(callback: AsyncCallback&lt;WifiLinkedInfo&gt;): void getLinkedInfo(callback: AsyncCallback&lt;WifiLinkedInfo&gt;): void
...@@ -1103,7 +1372,7 @@ Enumerates the supplicant states. ...@@ -1103,7 +1372,7 @@ Enumerates the supplicant states.
| UNINITIALIZED | 10 | The supplicant failed to set up the connection.| | UNINITIALIZED | 10 | The supplicant failed to set up the connection.|
| INVALID | 11 | Invalid value.| | INVALID | 11 | Invalid value.|
## wifi.isConnected<sup>9+</sup> ## wifiManager.isConnected<sup>9+</sup>
isConnected(): boolean isConnected(): boolean
...@@ -1140,7 +1409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1140,7 +1409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.getSupportedFeatures<sup>9+</sup> ## wifiManager.getSupportedFeatures<sup>9+</sup>
getSupportedFeatures(): number getSupportedFeatures(): number
...@@ -1194,7 +1463,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1194,7 +1463,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.isFeatureSupported<sup>9+</sup> ## wifiManager.isFeatureSupported<sup>9+</sup>
isFeatureSupported(featureId: number): boolean isFeatureSupported(featureId: number): boolean
...@@ -1239,7 +1508,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1239,7 +1508,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.getDeviceMacAddress<sup>9+</sup> ## wifiManager.getDeviceMacAddress<sup>9+</sup>
getDeviceMacAddress(): string[] getDeviceMacAddress(): string[]
...@@ -1278,7 +1547,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1278,7 +1547,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.getIpInfo<sup>9+</sup> ## wifiManager.getIpInfo<sup>9+</sup>
getIpInfo(): IpInfo getIpInfo(): IpInfo
...@@ -1331,7 +1600,59 @@ Represents IP information. ...@@ -1331,7 +1600,59 @@ Represents IP information.
| leaseDuration | number | Yes| No| Lease duration of the IP address.| | leaseDuration | number | Yes| No| Lease duration of the IP address.|
## wifi.getCountryCode<sup>9+</sup> ## wifiManager.getIpv6Info<sup>10+</sup>
getIpv6Info(): Ipv6Info
Obtains IP information.
**Required permissions**: ohos.permission.GET_WIFI_INFO
**System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| Ipv6Info | IPv6 information obtained.|
**Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
| **ID**| **Error Message**|
| -------- | -------- |
| 2501000 | Operation failed.|
**Example**
```js
import wifiManager from '@ohos.wifiManager';
try {
let info = wifiManager.getIpv6Info();
console.info("info:" + JSON.stringify(info));
}catch(error){
console.error("failed:" + JSON.stringify(error));
}
```
## Ipv6Info <sup>10+</sup>
Represents the IPv6 information.
**System capability**: SystemCapability.Communication.WiFi.STA
| **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- |
| linkIpv6Address | string | Yes| No| IPv6 address of the link.|
| globalIpv6Address | string | Yes| No| Global IPv6 address.|
| randomGlobalIpv6Address | number | Yes| No| Random global IPv6 address.|
| gateway | string | Yes| No| Gateway IP address.|
| netmask | string | Yes| No| Subnet mask.|
| primaryDNS | string | Yes| No| IPv6 address of the preferred DNS server.|
| secondDNS | string | Yes| No| IPv6 address of the alternate DNS server.|
## wifiManager.getCountryCode<sup>9+</sup>
getCountryCode(): string getCountryCode(): string
...@@ -1367,7 +1688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1367,7 +1688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.reassociate<sup>9+</sup> ## wifiManager.reassociate<sup>9+</sup>
reassociate(): void reassociate(): void
...@@ -1399,7 +1720,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1399,7 +1720,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.reconnect<sup>9+</sup> ## wifiManager.reconnect<sup>9+</sup>
reconnect(): void reconnect(): void
...@@ -1431,7 +1752,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1431,7 +1752,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.getDeviceConfigs<sup>9+</sup> ## wifiManager.getDeviceConfigs<sup>9+</sup>
getDeviceConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt; getDeviceConfigs(): &nbsp;Array&lt;[WifiDeviceConfig](#wifideviceconfig)&gt;
...@@ -1469,9 +1790,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1469,9 +1790,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.updateDeviceConfig<sup>9+</sup> ## wifiManager.updateNetwork<sup>9+</sup>
updateDeviceConfig(config: WifiDeviceConfig): number updateNetwork(config: WifiDeviceConfig): number
Updates network configuration. Updates network configuration.
...@@ -1511,16 +1832,16 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1511,16 +1832,16 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
preSharedKey : "****", preSharedKey : "****",
securityType : 3 securityType : 3
} }
let ret = wifiManager.updateDeviceConfig(config); let ret = wifiManager.updateNetwork(config);
console.error("ret:" + ret); console.error("ret:" + ret);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.disableDeviceConfig<sup>9+</sup> ## wifiManager.disableNetwork<sup>9+</sup>
disableDeviceConfig(networkId: number): void disableNetwork(networkId: number): void
Disables network configuration. Disables network configuration.
...@@ -1550,15 +1871,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1550,15 +1871,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
try { try {
let netId = 0; let netId = 0;
wifiManager.disableDeviceConfig(netId); wifiManager.disableNetwork(netId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.removeAllDeviceConfigs<sup>9+</sup> ## wifiManager.removeAllNetwork<sup>9+</sup>
removeAllDeviceConfigs(): void removeAllNetwork(): void
Removes the configuration of all networks. Removes the configuration of all networks.
...@@ -1581,15 +1902,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1581,15 +1902,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
wifiManager.removeAllDeviceConfigs(); wifiManager.removeAllNetwork();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.removeDeviceConfig<sup>9+</sup> ## wifiManager.removeDevice<sup>9+</sup>
removeDeviceConfig(networkId: number): void removeDevice(networkId: number): void
Removes the specified network configuration. Removes the specified network configuration.
...@@ -1619,13 +1940,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1619,13 +1940,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
try { try {
let id = 0; let id = 0;
wifiManager.removeDeviceConfig(id); wifiManager.removeDevice(id);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.isBandTypeSupported<sup>10+</sup> ## wifiManager.isBandTypeSupported<sup>10+</sup>
isBandTypeSupported(bandType: WifiBandType): boolean isBandTypeSupported(bandType: WifiBandType): boolean
...@@ -1641,6 +1962,12 @@ Checks whether the current frequency band is supported. ...@@ -1641,6 +1962,12 @@ Checks whether the current frequency band is supported.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bandType | WifiBandType | Yes| Wi-Fi band type.| | bandType | WifiBandType | Yes| Wi-Fi band type.|
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the feature is supported; returns **false** otherwise.|
**Error codes** **Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
...@@ -1662,7 +1989,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1662,7 +1989,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.get5GChannelList<sup>10+</sup> ## wifiManager.get5GChannelList<sup>10+</sup>
get5GChannelList(): Array&lt;number&gt; get5GChannelList(): Array&lt;number&gt;
...@@ -1674,6 +2001,12 @@ Obtains the list of 5 GHz channels supported by this device. ...@@ -1674,6 +2001,12 @@ Obtains the list of 5 GHz channels supported by this device.
**System capability**: SystemCapability.Communication.WiFi.STA **System capability**: SystemCapability.Communication.WiFi.STA
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| &nbsp;Array&lt;number&gt; | List of 5 GHz channels supported by the device.|
**Error codes** **Error codes**
For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md). For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorcode-wifi.md).
...@@ -1693,7 +2026,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1693,7 +2026,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getDisconnectedReason<sup>10+</sup> ## wifiManager.getDisconnectedReason<sup>10+</sup>
getDisconnectedReason(): DisconnectedReason getDisconnectedReason(): DisconnectedReason
...@@ -1745,7 +2078,7 @@ Enumerates the Wi-Fi disconnection reasons. ...@@ -1745,7 +2078,7 @@ Enumerates the Wi-Fi disconnection reasons.
| DISC_REASON_WRONG_PWD | 1 | Incorrect password.| | DISC_REASON_WRONG_PWD | 1 | Incorrect password.|
| DISC_REASON_CONNECTION_FULL | 2 | The number of connections to the router has reached the limit.| | DISC_REASON_CONNECTION_FULL | 2 | The number of connections to the router has reached the limit.|
## wifi.enableHotspot<sup>9+</sup> ## wifiManager.enableHotspot<sup>9+</sup>
enableHotspot(): void enableHotspot(): void
...@@ -1776,7 +2109,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1776,7 +2109,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.disableHotspot<sup>9+</sup> ## wifiManager.disableHotspot<sup>9+</sup>
disableHotspot(): void disableHotspot(): void
...@@ -1807,7 +2140,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1807,7 +2140,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.isHotspotDualBandSupported<sup>9+</sup> ## wifiManager.isHotspotDualBandSupported<sup>9+</sup>
isHotspotDualBandSupported(): boolean isHotspotDualBandSupported(): boolean
...@@ -1845,7 +2178,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1845,7 +2178,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.isHotspotActive<sup>9+</sup> ## wifiManager.isHotspotActive<sup>9+</sup>
isHotspotActive(): boolean isHotspotActive(): boolean
...@@ -1883,7 +2216,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1883,7 +2216,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.setHotspotConfig<sup>9+</sup> ## wifiManager.setHotspotConfig<sup>9+</sup>
setHotspotConfig(config: HotspotConfig): void setHotspotConfig(config: HotspotConfig): void
...@@ -1946,7 +2279,7 @@ Represents the hotspot configuration. ...@@ -1946,7 +2279,7 @@ Represents the hotspot configuration.
| preSharedKey | string | Yes| Yes| PSK of the hotspot.| | preSharedKey | string | Yes| Yes| PSK of the hotspot.|
| maxConn | number | Yes| Yes| Maximum number of connections allowed.| | maxConn | number | Yes| Yes| Maximum number of connections allowed.|
## wifi.getHotspotConfig<sup>9+</sup> ## wifiManager.getHotspotConfig<sup>9+</sup>
getHotspotConfig(): HotspotConfig getHotspotConfig(): HotspotConfig
...@@ -1984,9 +2317,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -1984,9 +2317,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.getHotspotStations<sup>9+</sup> ## wifiManager.getStations<sup>9+</sup>
getHotspotStations(): &nbsp;Array&lt;[StationInfo](#stationinfo9)&gt; getStations(): &nbsp;Array&lt;[StationInfo](#stationinfo9)&gt;
Obtains information about the connected stations. Obtains information about the connected stations.
...@@ -2015,7 +2348,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2015,7 +2348,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
let stations = wifiManager.getHotspotStations(); let stations = wifiManager.getStations();
console.info("result:" + JSON.stringify(stations)); console.info("result:" + JSON.stringify(stations));
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
...@@ -2034,10 +2367,11 @@ Represents the station information. ...@@ -2034,10 +2367,11 @@ Represents the station information.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| name | string | Yes| No| Device name.| | name | string | Yes| No| Device name.|
| macAddress | string | Yes| No| MAC address.| | macAddress | string | Yes| No| MAC address.|
| macAddressType<sup>10+</sup> | DeviceAddressType | Yes| No| MAC address type.|
| ipAddress | string | Yes| No| IP address.| | ipAddress | string | Yes| No| IP address.|
## wifi.getP2pLinkedInfo<sup>9+</sup> ## wifiManager.getP2pLinkedInfo<sup>9+</sup>
getP2pLinkedInfo(): Promise&lt;WifiP2pLinkedInfo&gt; getP2pLinkedInfo(): Promise&lt;WifiP2pLinkedInfo&gt;
...@@ -2104,7 +2438,7 @@ Enumerates the P2P connection states. ...@@ -2104,7 +2438,7 @@ Enumerates the P2P connection states.
| CONNECTED | 1 | Connected.| | CONNECTED | 1 | Connected.|
## wifi.getP2pLinkedInfo<sup>9+</sup> ## wifiManager.getP2pLinkedInfo<sup>9+</sup>
getP2pLinkedInfo(callback: AsyncCallback&lt;WifiP2pLinkedInfo&gt;): void getP2pLinkedInfo(callback: AsyncCallback&lt;WifiP2pLinkedInfo&gt;): void
...@@ -2121,7 +2455,7 @@ Obtains P2P link information. This API uses an asynchronous callback to return t ...@@ -2121,7 +2455,7 @@ Obtains P2P link information. This API uses an asynchronous callback to return t
| callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[WifiP2pLinkedInfo](#wifip2plinkedinfo9)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.|
## wifi.getCurrentP2pGroup<sup>9+</sup> ## wifiManager.getCurrentP2pGroup<sup>9+</sup>
getCurrentP2pGroup(): Promise&lt;WifiP2pGroupInfo&gt; getCurrentP2pGroup(): Promise&lt;WifiP2pGroupInfo&gt;
...@@ -2145,7 +2479,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2145,7 +2479,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.getCurrentP2pGroup<sup>9+</sup> ## wifiManager.getCurrentP2pGroup<sup>9+</sup>
getCurrentP2pGroup(callback: AsyncCallback&lt;WifiP2pGroupInfo&gt;): void getCurrentP2pGroup(callback: AsyncCallback&lt;WifiP2pGroupInfo&gt;): void
...@@ -2186,7 +2520,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2186,7 +2520,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
}); });
``` ```
## wifi.getP2pPeerDevices<sup>9+</sup> ## wifiManager.getP2pPeerDevices<sup>9+</sup>
getP2pPeerDevices(): Promise&lt;WifiP2pDevice[]&gt; getP2pPeerDevices(): Promise&lt;WifiP2pDevice[]&gt;
...@@ -2210,7 +2544,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2210,7 +2544,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.getP2pPeerDevices<sup>9+</sup> ## wifiManager.getP2pPeerDevices<sup>9+</sup>
getP2pPeerDevices(callback: AsyncCallback&lt;WifiP2pDevice[]&gt;): void getP2pPeerDevices(callback: AsyncCallback&lt;WifiP2pDevice[]&gt;): void
...@@ -2261,6 +2595,7 @@ Represents the P2P device information. ...@@ -2261,6 +2595,7 @@ Represents the P2P device information.
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| deviceName | string | Yes| No| Device name.| | deviceName | string | Yes| No| Device name.|
| deviceAddress | string | Yes| No| MAC address of the device.| | deviceAddress | string | Yes| No| MAC address of the device.|
| deviceAddressType<sup>10+</sup> | DeviceAddressType | Yes| No| MAC address type of the device.|
| primaryDeviceType | string | Yes| No| Type of the primary device.| | primaryDeviceType | string | Yes| No| Type of the primary device.|
| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.| | deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.|
| groupCapabilities | number | Yes| No| Group capabilities.| | groupCapabilities | number | Yes| No| Group capabilities.|
...@@ -2281,7 +2616,7 @@ Enumerates the P2P device states. ...@@ -2281,7 +2616,7 @@ Enumerates the P2P device states.
| UNAVAILABLE | 4 | Unavailable.| | UNAVAILABLE | 4 | Unavailable.|
## wifi.getP2pLocalDevice<sup>9+</sup> ## wifiManager.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(): Promise&lt;WifiP2pDevice&gt; getP2pLocalDevice(): Promise&lt;WifiP2pDevice&gt;
...@@ -2305,7 +2640,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2305,7 +2640,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.getP2pLocalDevice<sup>9+</sup> ## wifiManager.getP2pLocalDevice<sup>9+</sup>
getP2pLocalDevice(callback: AsyncCallback&lt;WifiP2pDevice&gt;): void getP2pLocalDevice(callback: AsyncCallback&lt;WifiP2pDevice&gt;): void
...@@ -2344,9 +2679,9 @@ Obtains the local device information in the P2P connection. This API uses an asy ...@@ -2344,9 +2679,9 @@ Obtains the local device information in the P2P connection. This API uses an asy
}); });
``` ```
## wifi.createP2pGroup<sup>9+</sup> ## wifiManager.createGroup<sup>9+</sup>
createP2pGroup(config: WifiP2PConfig): void createGroup(config: WifiP2PConfig): void
Creates a P2P group. Creates a P2P group.
...@@ -2380,7 +2715,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2380,7 +2715,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
groupName: "****", groupName: "****",
goBand: 0 goBand: 0
} }
wifiManager.createP2pGroup(config); wifiManager.createGroup(config);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
...@@ -2396,6 +2731,7 @@ Represents P2P group configuration. ...@@ -2396,6 +2731,7 @@ Represents P2P group configuration.
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| deviceAddress | string | Yes| No| Device address.| | deviceAddress | string | Yes| No| Device address.|
| deviceAddressType<sup>10+</sup>| DeviceAddressType | Yes| No| Device address type.|
| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| | netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.|
| passphrase | string | Yes| No| Passphrase of the group.| | passphrase | string | Yes| No| Passphrase of the group.|
| groupName | string | Yes| No| Name of the group.| | groupName | string | Yes| No| Name of the group.|
...@@ -2415,9 +2751,9 @@ Enumerates the P2P group frequency bands. ...@@ -2415,9 +2751,9 @@ Enumerates the P2P group frequency bands.
| GO_BAND_5GHZ | 2 | 5 GHz.| | GO_BAND_5GHZ | 2 | 5 GHz.|
## wifi.removeP2pGroup<sup>9+</sup> ## wifiManager.removeGroup<sup>9+</sup>
removeP2pGroup(): void removeGroup(): void
Removes this P2P group. Removes this P2P group.
...@@ -2438,13 +2774,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2438,13 +2774,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
wifiManager.removeP2pGroup(); wifiManager.removeGroup();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.p2pConnect<sup>9+</sup> ## wifiManager.p2pConnect<sup>9+</sup>
p2pConnect(config: WifiP2PConfig): void p2pConnect(config: WifiP2PConfig): void
...@@ -2535,7 +2871,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2535,7 +2871,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices()); console.info("start discover devices -> " + wifiManager.startDiscoverP2pDevices());
``` ```
## wifi.p2pCancelConnect<sup>9+</sup> ## wifiManager.p2pCancelConnect<sup>9+</sup>
p2pCancelConnect(): void p2pCancelConnect(): void
...@@ -2564,9 +2900,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2564,9 +2900,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
} }
``` ```
## wifi.startDiscoverP2pDevices<sup>9+</sup> ## wifiManager.startDiscoverDevices<sup>10+</sup>
startDiscoverP2pDevices(): void startDiscoverDevices(): void
Starts to discover devices. Starts to discover devices.
...@@ -2587,15 +2923,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2587,15 +2923,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
wifiManager.startDiscoverP2pDevices(); wifiManager.startDiscoverDevices();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.stopDiscoverP2pDevices<sup>9+</sup> ## wifiManager.stopDiscoverDevices<sup>10+</sup>
stopDiscoverP2pDevices(): void stopDiscoverDevices(): void
Stops discovering devices. Stops discovering devices.
...@@ -2616,15 +2952,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2616,15 +2952,15 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
try { try {
wifiManager.stopDiscoverP2pDevices(); wifiManager.stopDiscoverDevices();
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.deletePersistentP2pGroup<sup>9+</sup> ## wifiManager.deletePersistentGroup<sup>9+</sup>
deletePersistentP2pGroup(netId: number): void deletePersistentGroup(netId: number): void
Deletes a persistent group. Deletes a persistent group.
...@@ -2655,13 +2991,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2655,13 +2991,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
try { try {
let netId = 0; let netId = 0;
wifiManager.deletePersistentP2pGroup(netId); wifiManager.deletePersistentGroup(netId);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.getP2pGroups<sup>9+</sup> ## wifiManager.getP2pGroups<sup>9+</sup>
getP2pGroups(): Promise&lt;Array&lt;WifiP2pGroupInfo&gt;&gt; getP2pGroups(): Promise&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;
...@@ -2724,7 +3060,7 @@ Represents the P2P group information. ...@@ -2724,7 +3060,7 @@ Represents the P2P group information.
| goIpAddress | string | Yes| No| IP address of the group.| | goIpAddress | string | Yes| No| IP address of the group.|
## wifi.getP2pGroups<sup>9+</sup> ## wifiManager.getP2pGroups<sup>9+</sup>
getP2pGroups(callback: AsyncCallback&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;): void getP2pGroups(callback: AsyncCallback&lt;Array&lt;WifiP2pGroupInfo&gt;&gt;): void
...@@ -2750,9 +3086,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2750,9 +3086,9 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.setP2pDeviceName<sup>9+</sup> ## wifiManager.setDeviceName<sup>9+</sup>
setP2pDeviceName(devName: string): void setDeviceName(devName: string): void
Sets the device name. Sets the device name.
...@@ -2782,13 +3118,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2782,13 +3118,13 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
try { try {
let name = "****"; let name = "****";
wifiManager.setP2pDeviceName(name); wifiManager.setDeviceName(name);
}catch(error){ }catch(error){
console.error("failed:" + JSON.stringify(error)); console.error("failed:" + JSON.stringify(error));
} }
``` ```
## wifi.on('wifiStateChange')<sup>9+</sup> ## wifiManager.on('wifiStateChange')<sup>9+</sup>
on(type: "wifiStateChange", callback: Callback&lt;number&gt;): void on(type: "wifiStateChange", callback: Callback&lt;number&gt;): void
...@@ -2823,7 +3159,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2823,7 +3159,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| 3 | Deactivating| | 3 | Deactivating|
## wifi.off('wifiStateChange')<sup>9+</sup> ## wifiManager.off('wifiStateChange')<sup>9+</sup>
off(type: "wifiStateChange", callback?: Callback&lt;number&gt;): void off(type: "wifiStateChange", callback?: Callback&lt;number&gt;): void
...@@ -2864,7 +3200,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2864,7 +3200,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
``` ```
## wifi.on('wifiConnectionChange')<sup>9+</sup> ## wifiManager.on('wifiConnectionChange')<sup>9+</sup>
on(type: "wifiConnectionChange", callback: Callback&lt;number&gt;): void on(type: "wifiConnectionChange", callback: Callback&lt;number&gt;): void
...@@ -2896,7 +3232,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2896,7 +3232,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2501000 | Operation failed.| | 2501000 | Operation failed.|
## wifi.off('wifiConnectionChange')<sup>9+</sup> ## wifiManager.off('wifiConnectionChange')<sup>9+</sup>
off(type: "wifiConnectionChange", callback?: Callback&lt;number&gt;): void off(type: "wifiConnectionChange", callback?: Callback&lt;number&gt;): void
...@@ -2936,7 +3272,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2936,7 +3272,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc); wifiManager.off("wifiConnectionChange", recvWifiConnectionChangeFunc);
``` ```
## wifi.on('wifiScanStateChange')<sup>9+</sup> ## wifiManager.on('wifiScanStateChange')<sup>9+</sup>
on(type: "wifiScanStateChange", callback: Callback&lt;number&gt;): void on(type: "wifiScanStateChange", callback: Callback&lt;number&gt;): void
...@@ -2968,7 +3304,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -2968,7 +3304,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2501000 | Operation failed.| | 2501000 | Operation failed.|
## wifi.off('wifiScanStateChange')<sup>9+</sup> ## wifiManager.off('wifiScanStateChange')<sup>9+</sup>
off(type: "wifiScanStateChange", callback?: Callback&lt;number&gt;): void off(type: "wifiScanStateChange", callback?: Callback&lt;number&gt;): void
...@@ -3008,7 +3344,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3008,7 +3344,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc); wifiManager.off("wifiScanStateChange", recvWifiScanStateChangeFunc);
``` ```
## wifi.on('wifiRssiChange')<sup>9+</sup> ## wifiManager.on('wifiRssiChange')<sup>9+</sup>
on(type: "wifiRssiChange", callback: Callback&lt;number&gt;): void on(type: "wifiRssiChange", callback: Callback&lt;number&gt;): void
...@@ -3033,7 +3369,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3033,7 +3369,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2501000 | Operation failed.| | 2501000 | Operation failed.|
## wifi.off('wifiRssiChange')<sup>9+</sup> ## wifiManager.off('wifiRssiChange')<sup>9+</sup>
off(type: "wifiRssiChange", callback?: Callback&lt;number&gt;): void off(type: "wifiRssiChange", callback?: Callback&lt;number&gt;): void
...@@ -3073,7 +3409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3073,7 +3409,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc); wifiManager.off("wifiRssiChange", recvWifiRssiChangeFunc);
``` ```
## wifi.on('hotspotStateChange')<sup>9+</sup> ## wifiManager.on('hotspotStateChange')<sup>9+</sup>
on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void on(type: "hotspotStateChange", callback: Callback&lt;number&gt;): void
...@@ -3107,7 +3443,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3107,7 +3443,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2601000 | Operation failed.| | 2601000 | Operation failed.|
## wifi.off('hotspotStateChange')<sup>9+</sup> ## wifiManager.off('hotspotStateChange')<sup>9+</sup>
off(type: "hotspotStateChange", callback?: Callback&lt;number&gt;): void off(type: "hotspotStateChange", callback?: Callback&lt;number&gt;): void
...@@ -3147,7 +3483,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3147,7 +3483,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc); wifiManager.off("hotspotStateChange", recvHotspotStateChangeFunc);
``` ```
## wifi.on('p2pStateChange')<sup>9+</sup> ## wifiManager.on('p2pStateChange')<sup>9+</sup>
on(type: "p2pStateChange", callback: Callback&lt;number&gt;): void on(type: "p2pStateChange", callback: Callback&lt;number&gt;): void
...@@ -3182,7 +3518,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3182,7 +3518,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pStateChange')<sup>9+</sup> ## wifiManager.off('p2pStateChange')<sup>9+</sup>
off(type: "p2pStateChange", callback?: Callback&lt;number&gt;): void off(type: "p2pStateChange", callback?: Callback&lt;number&gt;): void
...@@ -3222,7 +3558,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3222,7 +3558,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("p2pStateChange", recvP2pStateChangeFunc); wifiManager.off("p2pStateChange", recvP2pStateChangeFunc);
``` ```
## wifi.on('p2pConnectionChange')<sup>9+</sup> ## wifiManager.on('p2pConnectionChange')<sup>9+</sup>
on(type: "p2pConnectionChange", callback: Callback&lt;WifiP2pLinkedInfo&gt;): void on(type: "p2pConnectionChange", callback: Callback&lt;WifiP2pLinkedInfo&gt;): void
...@@ -3247,7 +3583,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3247,7 +3583,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pConnectionChange')<sup>9+</sup> ## wifiManager.off('p2pConnectionChange')<sup>9+</sup>
off(type: "p2pConnectionChange", callback?: Callback&lt;WifiP2pLinkedInfo&gt;): void off(type: "p2pConnectionChange", callback?: Callback&lt;WifiP2pLinkedInfo&gt;): void
...@@ -3287,7 +3623,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3287,7 +3623,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc); wifiManager.off("p2pConnectionChange", recvP2pConnectionChangeFunc);
``` ```
## wifi.on('p2pDeviceChange')<sup>9+</sup> ## wifiManager.on('p2pDeviceChange')<sup>9+</sup>
on(type: "p2pDeviceChange", callback: Callback&lt;WifiP2pDevice&gt;): void on(type: "p2pDeviceChange", callback: Callback&lt;WifiP2pDevice&gt;): void
...@@ -3312,7 +3648,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3312,7 +3648,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pDeviceChange')<sup>9+</sup> ## wifiManager.off('p2pDeviceChange')<sup>9+</sup>
off(type: "p2pDeviceChange", callback?: Callback&lt;WifiP2pDevice&gt;): void off(type: "p2pDeviceChange", callback?: Callback&lt;WifiP2pDevice&gt;): void
...@@ -3342,7 +3678,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3342,7 +3678,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
var recvP2pDeviceChangeFunc = result => { var recvP2pDeviceChangeFunc = result => {
console.info("Receive recv p2p device change event: " + result); console.info("Receive p2p device change event: " + result);
} }
// Register an event. // Register an event.
...@@ -3352,7 +3688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3352,7 +3688,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc); wifiManager.off("p2pDeviceChange", recvP2pDeviceChangeFunc);
``` ```
## wifi.on('p2pPeerDeviceChange')<sup>9+</sup> ## wifiManager.on('p2pPeerDeviceChange')<sup>9+</sup>
on(type: "p2pPeerDeviceChange", callback: Callback&lt;WifiP2pDevice[]&gt;): void on(type: "p2pPeerDeviceChange", callback: Callback&lt;WifiP2pDevice[]&gt;): void
...@@ -3377,7 +3713,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3377,7 +3713,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pPeerDeviceChange')<sup>9+</sup> ## wifiManager.off('p2pPeerDeviceChange')<sup>9+</sup>
off(type: "p2pPeerDeviceChange", callback?: Callback&lt;WifiP2pDevice[]&gt;): void off(type: "p2pPeerDeviceChange", callback?: Callback&lt;WifiP2pDevice[]&gt;): void
...@@ -3407,7 +3743,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3407,7 +3743,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
var recvP2pPeerDeviceChangeFunc = result => { var recvP2pPeerDeviceChangeFunc = result => {
console.info("Receive recv p2p peer device change event: " + result); console.info("Receive p2p peer device change event: " + result);
} }
// Register an event. // Register an event.
...@@ -3417,7 +3753,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3417,7 +3753,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); wifiManager.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);
``` ```
## wifi.on('p2pPersistentGroupChange')<sup>9+</sup> ## wifiManager.on('p2pPersistentGroupChange')<sup>9</sup>
on(type: "p2pPersistentGroupChange", callback: Callback&lt;void&gt;): void on(type: "p2pPersistentGroupChange", callback: Callback&lt;void&gt;): void
...@@ -3442,7 +3778,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3442,7 +3778,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pPersistentGroupChange')<sup>9+</sup> ## wifiManager.off('p2pPersistentGroupChange')<sup>9</sup>
off(type: "p2pPersistentGroupChange", callback?: Callback&lt;void&gt;): void off(type: "p2pPersistentGroupChange", callback?: Callback&lt;void&gt;): void
...@@ -3472,7 +3808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3472,7 +3808,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
var recvP2pPersistentGroupChangeFunc = result => { var recvP2pPersistentGroupChangeFunc = result => {
console.info("Receive recv p2p persistent group change event: " + result); console.info("Receive p2p persistent group change event: " + result);
} }
// Register an event. // Register an event.
...@@ -3482,7 +3818,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3482,7 +3818,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); wifiManager.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);
``` ```
## wifi.on('p2pDiscoveryChange')<sup>9+</sup> ## wifiManager.on('p2pDiscoveryChange')<sup>9+</sup>
on(type: "p2pDiscoveryChange", callback: Callback&lt;number&gt;): void on(type: "p2pDiscoveryChange", callback: Callback&lt;number&gt;): void
...@@ -3514,7 +3850,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3514,7 +3850,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
| -------- | -------- | | -------- | -------- |
| 2801000 | Operation failed.| | 2801000 | Operation failed.|
## wifi.off('p2pDiscoveryChange')<sup>9+</sup> ## wifiManager.off('p2pDiscoveryChange')<sup>9+</sup>
off(type: "p2pDiscoveryChange", callback?: Callback&lt;number&gt;): void off(type: "p2pDiscoveryChange", callback?: Callback&lt;number&gt;): void
...@@ -3544,7 +3880,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco ...@@ -3544,7 +3880,7 @@ For details about the error codes, see [Wi-Fi Error Codes](../errorcodes/errorco
import wifiManager from '@ohos.wifiManager'; import wifiManager from '@ohos.wifiManager';
var recvP2pDiscoveryChangeFunc = result => { var recvP2pDiscoveryChangeFunc = result => {
console.info("Receive recv p2p discovery change event: " + result); console.info("Receive p2p discovery change event: " + result);
} }
// Register an event. // Register an event.
......
...@@ -67,7 +67,7 @@ struct RichTextExample { ...@@ -67,7 +67,7 @@ struct RichTextExample {
'<h2 style="text-align: center;">h2 heading</h2>' + '<h2 style="text-align: center;">h2 heading</h2>' +
'<h3 style="text-align: center;">h3 heading</h3>' + '<h3 style="text-align: center;">h3 heading</h3>' +
'<p style="text-align: center;">Regular paragraph</p><hr/>' + '<p style="text-align: center;">Regular paragraph</p><hr/>' +
'<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' + '<div style="width: 500px;height: 500px;border: 1px solid;margin: 0 auto;">' +
'<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' + '<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' +
'<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' + '<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
'<p>This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text.</p>'; '<p>This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text.</p>';
......
...@@ -30,15 +30,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -30,15 +30,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description | | Name | Type | Description |
| ----------------------- | ------------------------------------------------ | ---------------------------------------------- | | ----------------------- | ------------------------------------------------ | ---------------------------------------------- |
| searchButton<sup>10+</sup> | value: string,<br>option?: [SearchButtonOptions](#searchbuttonoptions10) | Text on the search button located next to the search text box. By default, there is no search button. | | searchButton<sup>10+</sup> | value: string,<br>option?: [SearchButtonOptions](#searchbuttonoptions10) | Text on the search button located next to the search text box. By default, there is no search button. |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. | | placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.<br>Default value: **'#99182431'** |
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported. | | placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported. |
| textFont | [Font](ts-types.md#font) | Style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. | | textFont | [Font](ts-types.md#font) | Style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode in the search text box.<br>Default value: **TextAlign.Start** | | textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode in the search text box.<br>Default value: **TextAlign.Start** |
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. | | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the text can be pasted, but copy or cut is not allowed. |
| searchIcon<sup>10+</sup> | [IconOptions](#iconoptions10) | Style of the search icon on the left. | | searchIcon<sup>10+</sup> | [IconOptions](#iconoptions10) | Style of the search icon on the left. |
| cancelButton<sup>10+</sup> | {<br>style? : [CancelButtonStyle](#cancelbuttonstyle10)<br>icon?: [IconOptions](#iconoptions10) <br>} | Style of the Cancel button on the right. | | cancelButton<sup>10+</sup> | {<br>style? : [CancelButtonStyle](#cancelbuttonstyle10)<br>icon?: [IconOptions](#iconoptions10) <br>} | Style of the Cancel button on the right.<br>Default value:<br>{<br>style: CancelButtonStyle.INPUT<br>} |
| fontColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text. | | fontColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text.<br>Default value: **'#FF182431'**<br>**NOTE**<br>[Universal text attributes](ts-universal-attributes-text-style.md) **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are set in the **textFont** attribute.|
| caretStyle<sup>10+</sup> | [CaretStyle](#caretstyle10) | Caret style. | | caretStyle<sup>10+</sup> | [CaretStyle](#caretstyle10) | Caret style.<br>Default value:<br>{<br>width: 1.5vp<br>color: '#007DFF'<br>} |
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true** | | enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true** |
| selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**| | selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**|
## IconOptions<sup>10+</sup> ## IconOptions<sup>10+</sup>
......
...@@ -31,7 +31,7 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -31,7 +31,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Description | | Name | Description |
| -------- | ---------------- | | -------- | ---------------- |
| Checkbox | Check box type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 px,<br> right: 12 px,<br> bottom: 12 px,<br> left: 12 px<br> } | | Checkbox | Check box type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 px,<br> right: 14 px,<br> bottom: 14 px,<br> left: 14 px<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. | | Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 6px,<br> right: 14px,<br> bottom: 6 px,<br> left: 14 px<br> } | | Switch | Switch type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 6px,<br> right: 14px,<br> bottom: 6 px,<br> left: 14 px<br> } |
......
...@@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| count | number | Yes| Number of notifications.<br>**NOTE**<br>If the value is less than or equal to 0, no badge is displayed.<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| | count | number | Yes| Number of notifications.<br>**NOTE**<br>If the value is less than or equal to 0, no badge is displayed.<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.|
| position | [BadgePosition](#badgeposition) | No| Position to display the badge relative to the parent component.<br>Default value: **BadgePosition.RightTop**| | position | [BadgePosition](#badgeposition)\|[Position<sup>10+</sup>](ts-types.md#position8) | No| Position to display the badge relative to the parent component.<br>Default value: **BadgePosition.RightTop**<br>**NOTE**<br> This parameter cannot be set in percentage. If it is set to an invalid value, the default value **(0,0)** will be used.|
| maxCount | number | No| Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.<br>Default value: **99**<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.| | maxCount | number | No| Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.<br>Default value: **99**<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.|
| style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.| | style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.|
...@@ -44,7 +44,7 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -44,7 +44,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| value | string | Yes| - | Prompt content.| | value | string | Yes| - | Prompt content.|
| position | [BadgePosition](#badgeposition) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| | position | [BadgePosition](#badgeposition)\|[Position<sup>10+</sup>](ts-types.md#position8) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.| | style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.|
## BadgePosition ## BadgePosition
......
...@@ -23,10 +23,11 @@ The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)> ...@@ -23,10 +23,11 @@ The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)>
> >
> If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated. > If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
> >
> Child components of **\<Grid>** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation. > The child component that has the **visibility** attribute set to **Hidden** or **None** is included in the index calculation.
> >
> Child components of **\<Grid>** whose **visibility** attribute is set to **None** are not displayed, but still take up the corresponding cells. > The child component that has the **visibility** attribute set to **None** is not displayed, but still takes up the corresponding cell.
>
> The child component that has the **position** attribute set takes up the corresponding cell, and is offset by the distance specified by **position** relative to the upper left corner of the grid. This child component does not scroll with the corresponding cell and is not displayed after the corresponding cell extends beyond the display range of the grid.
## APIs ## APIs
...@@ -61,6 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -61,6 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**| | supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
| edgeEffect<sup>10+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.<br>Default value: **EdgeEffect.None**<br>| | edgeEffect<sup>10+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.<br>Default value: **EdgeEffect.None**<br>|
| enableScrollInteraction<sup>10+</sup> | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.<br>Default value: **true** | | enableScrollInteraction<sup>10+</sup> | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.<br>Default value: **true** |
| nestedScroll<sup>10+</sup> | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.|
Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes: Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
...@@ -71,10 +73,6 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib ...@@ -71,10 +73,6 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default. - If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
- The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column. - The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column.
- By default, the grid items fill the entire grid. - By default, the grid items fill the entire grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. If no idle position meets the requirements, the grid item is not laid out.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. If no idle position is available, the grid item is not laid out.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
2. Either **rowsTemplate** or **columnsTemplate** is set 2. Either **rowsTemplate** or **columnsTemplate** is set
...@@ -84,19 +82,14 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib ...@@ -84,19 +82,14 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**. - In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
- The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column. - The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column.
- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid. - The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
3. Neither **rowsTemplate** nor **columnsTemplate** is set 3. Neither **rowsTemplate** nor **columnsTemplate** is set
- The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**. - The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**.
- The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling. - The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**. - In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
- When **layoutDirection** is set to **Row**, elements are arranged from left to right. When a row is full, a new row will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered. - When **layoutDirection** is set to **Row**, elements are arranged row by row from left to right. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
- When **layoutDirection** is set to **Column**, elements are arranged from top to bottom. When a column is full, a new column will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered. - When **layoutDirection** is set to **Column**, elements are arranged column by column from top to bottom. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
- In this mode, **rowStart** and **columnStart** of the grid item do not take effect.
## GridDirection<sup>8+</sup> ## GridDirection<sup>8+</sup>
...@@ -141,6 +134,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi ...@@ -141,6 +134,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
## Example ## Example
### Example 1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -196,12 +191,11 @@ struct GridExample { ...@@ -196,12 +191,11 @@ struct GridExample {
console.info(first.toString()) console.info(first.toString())
}) })
.onScrollBarUpdate((index: number, offset: number) => { .onScrollBarUpdate((index: number, offset: number) => {
return {totalOffset: (index / 5) * (80 + 10) - 10 + offset, totalLength: 80 * 5 + 10 * 4} return {totalOffset: (index / 5) * (80 + 10) - 10 - offset, totalLength: 80 * 5 + 10 * 4}
}) })
.width('90%') .width('90%')
.backgroundColor(0xFAEEE0) .backgroundColor(0xFAEEE0)
.height(300) .height(300)
.scrollBar(BarState.Off)
Button('next page') Button('next page')
.onClick(() => {// Click to go to the next page. .onClick(() => {// Click to go to the next page.
this.scroller.scrollPage({ next: true }) this.scroller.scrollPage({ next: true })
...@@ -212,3 +206,82 @@ struct GridExample { ...@@ -212,3 +206,82 @@ struct GridExample {
``` ```
![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif) ![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
### Example 2
1. Set **editMode\(true\)** to enable the grid to enter editing mode, where the user can drag the grid items.
2. Through [onItemDragStart](#events), set the image to be displayed during dragging.
3. Through [onItemDrop](#events), obtain the initial position of the dragged item and the position to which the dragged item will be dropped. Through [onDrag](#events), complete the array position exchange logic.
```ts
@Entry
@Component
struct GridExample {
@State numbers: String[] = []
scroller: Scroller = new Scroller()
@State text: string = 'drag'
@Builder pixelMapBuilder () { // Style for the drag event.
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 15; i++) {
this.numbers.push(i + '')
}
}
changeIndex(index1: number, index2: number) { // Exchange the array position.
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Up) {
this.text = day
}
})
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height(300)
.editMode(true) // Enable the grid to enter editing mode, where the user can drag the grid items.
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
return this.pixelMapBuilder() // Set the image to be displayed during dragging.
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item. insertIndex indicates the position to which the dragged item will be dropped.
this.changeIndex(itemIndex, insertIndex)
})
}.width('100%').margin({ top: 5 })
}
}
```
<!--no_check-->
\ No newline at end of file
...@@ -40,6 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -40,6 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.<br>Default value: **48**<br>Unit: vp<br>**NOTE**<br>This attribute cannot be set in percentage.| | miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.<br>Default value: **48**<br>Unit: vp<br>**NOTE**<br>This attribute cannot be set in percentage.|
| show | boolean | Whether to show the panel.| | show | boolean | Whether to show the panel.|
| backgroundMask<sup>9+</sup>|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.| | backgroundMask<sup>9+</sup>|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.|
| showCloseIcon<sup>10+</sup> | boolean | Whether to display the close icon. The value **true** means to display the close icon, and **false** means the opposite.<br>Default value: **false**|
## PanelType ## PanelType
...@@ -93,6 +94,7 @@ struct PanelExample { ...@@ -93,6 +94,7 @@ struct PanelExample {
.type(PanelType.Foldable).mode(PanelMode.Half) .type(PanelType.Foldable).mode(PanelMode.Half)
.dragBar(true) // The drag bar is enabled by default. .dragBar(true) // The drag bar is enabled by default.
.halfHeight(500) // The panel height is half of the screen height by default. .halfHeight(500) // The panel height is half of the screen height by default.
.showCloseIcon(true) // Display the close icon.
.onChange((width: number, height: number, mode: PanelMode) => { .onChange((width: number, height: number, mode: PanelMode) => {
console.info(`width:${width},height:${height},mode:${mode}`) console.info(`width:${width},height:${height},mode:${mode}`)
}) })
......
...@@ -8,22 +8,22 @@ You can set the background for a component. ...@@ -8,22 +8,22 @@ You can set the background for a component.
## Attributes ## Attributes
| Name| Type| Description| | Name | Type | Description |
| -------- | -------- | -------- | | -------------------------------- | ---------------------------------------- | ---------------------------------------- |
| background<sup>10+</sup> | builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | Background color of the component.<br>**builder**: custom background.<br>**align**: alignment mode between the custom background and the component.<br>If **background**, **backgroundColor**, and **backgroundImage** are set at the same time, they will all take effect, with **background** at the top layer.| | background<sup>10+</sup> | builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | Background color of the component.<br>**builder**: custom background.<br>**align**: alignment mode between the custom background and the component.<br>If **background**, **backgroundColor**, and **backgroundImage** are set at the same time, they will all take effect, with **background** at the top layer.<br>This attribute cannot be nested.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.<br>Since API version 9, this API is supported in ArkTS widgets.| | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image or a Base64 encoded image. SVG images are not supported.<br>**repeat**: whether the background image is repeated. By default, the background image is not repeated. If the set image has a transparent background and **backgroundColor** is set, the image is overlaid on the background color.<br>Since API version 9, this API is supported in ArkTS widgets.| | backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image or a Base64 encoded image. SVG images are not supported.<br>**repeat**: whether the background image is repeated. By default, the background image is not repeated. If the set image has a transparent background and **backgroundColor** is set, the image is overlaid on the background color.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>The value range of **width** and **height** is [0, +∞).<br>Default value: **ImageSize.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. If **height** is set but **width** is not, the image width is adjusted based on the original aspect ratio of the image.| | backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>The value range of **width** and **height** is [0, +∞).<br>Default value: **ImageSize.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. If **height** is set but **width** is not, the image width is adjusted based on the original aspect ratio of the image.|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.<br>Since API version 9, this API is supported in ArkTS widgets.| | backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundBlurStyle<sup>9+</sup> | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),<br>options<sup>10+</sup>?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10) | Background blur style applied between the content and the background.<br>**value**: settings of the background blur style, including the blur radius, mask color, mask opacity, saturation, and brightness.<br>**options**: background blur options. Optional.<br>This API is supported in ArkTS widgets.| | backgroundBlurStyle<sup>9+</sup> | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),<br>options<sup>10+</sup>?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10) | Background blur style applied between the content and the background.<br>**value**: settings of the background blur style, including the blur radius, mask color, mask opacity, saturation, and brightness.<br>**options**: background blur options. Optional.<br>This API is supported in ArkTS widgets.|
## BackgroundBlurStyleOptions<sup>10+</sup> ## BackgroundBlurStyleOptions<sup>10+</sup>
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| --------------------------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | | ------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| colorMode<sup>10+</sup> | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | No | Color mode used for the background blur.<br>Default value: **ThemeColorMode.System**| | colorMode | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | No | Color mode used for the background blur.<br>Default value: **ThemeColorMode.System**|
| adaptiveColor<sup>10+</sup> | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | No | Adaptive color mode.<br>Default value: **AdaptiveColor.Default**| | adaptiveColor | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | No | Adaptive color mode.<br>Default value: **AdaptiveColor.Default**|
| scale<sup>10+</sup> | number | No | Blurredness of the background material. This API is a system API.<br>Default value: **1.0**<br>Value range: [0.0, 1.0]<br>| | scale | number | No | Blurredness of the background material. This API is a system API.<br>Default value: **1.0**<br>Value range: [0.0, 1.0]<br>|
## Example ## Example
......
...@@ -8,22 +8,22 @@ You can draw an image around a component. ...@@ -8,22 +8,22 @@ You can draw an image around a component.
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- | | ----------- | ---------------------------------------- | -------------------------------------- |
| borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient.<br>This API is supported in ArkTS widgets.| | borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient.<br>This API is supported in ArkTS widgets.|
## BorderImageOption ## BorderImageOption
This API is supported in ArkTS widgets. This API is supported in ArkTS widgets.
| Name | Type | Description | | Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- | | ------ | ---------------------------------------- | ---------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.<br>**NOTE**<br>The border image source applies only to container components, such as **\<Row>**, **\<Column>**, and **\<Flex>**.| | source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.<br>**NOTE**<br>The border image source applies only to container components, such as **\<Row>**, **\<Column>**, and **\<Flex>**.|
| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.<br>Default value: **0** | | slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.<br>Default value: **0** |
| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.<br>Default value: **0** | | width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.<br>Default value: **0** |
| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.<br>Default value: **0** | | outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.<br>Default value: **0** |
| repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**| | repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch** |
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** | | fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** |
## RepeatMode ## RepeatMode
......
...@@ -8,13 +8,13 @@ ...@@ -8,13 +8,13 @@
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ---------- | ------------------------------------------- | ------------------------------------------------------------ | | ------------ | ---------------------------------------- | ---------------------------------------- |
| flexBasis | number \| string | Base size of the component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)<br>This attribute cannot be set in percentage.<br>Since API version 9, this API is supported in ArkTS widgets.| | flexBasis | number \| string | Base size of the component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)<br>This attribute cannot be set in percentage.<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.| | flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**.<br>Since API version 9, this API is supported in ArkTS widgets.| | flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**.<br>Since API version 9, this API is supported in ArkTS widgets.|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container (**\<Flex>**, **\<Column>**, **\<Row>**, or **\<GridRow>**).<br>**\<GridCol>** can have the **alignsSelf** attribute bound to change its own layout along the cross axis.<br>Default value: **ItemAlign.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.| | alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container (**\<Flex>**, **\<Column>**, **\<Row>**, or **\<GridRow>**).<br>**\<GridCol>** can have the **alignsSelf** attribute bound to change its own layout along the cross axis.<br>Default value: **ItemAlign.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.| | layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
## Example ## Example
......
...@@ -9,14 +9,15 @@ Layout constraints refer to constraints on the aspect ratio and display priority ...@@ -9,14 +9,15 @@ Layout constraints refer to constraints on the aspect ratio and display priority
## Attributes ## Attributes
| Name | Type| Description | | Name | Type | Description |
| --------------- | -------- | ------------------------------------------------------------ | | --------------- | ------ | ---------------------------------------- |
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height.<br>Since API version 9, this API is supported in ArkTS widgets.| | aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height.<br>Since API version 9, this API is supported in ArkTS widgets.|
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.| | displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
## Example ## Example
### Example 1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -78,6 +79,8 @@ struct AspectRatioExample { ...@@ -78,6 +79,8 @@ struct AspectRatioExample {
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
### Example 2
```ts ```ts
class ContainerInfo { class ContainerInfo {
label: string = ''; label: string = '';
......
...@@ -12,37 +12,39 @@ A context menu – a vertical list of items – can be bound to a component and ...@@ -12,37 +12,39 @@ A context menu – a vertical list of items – can be bound to a component and
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------------------- | ---------------------------------------- | ---------------------------------------- |
| bindMenu | content: Array<[MenuItem](#menuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8),<br>options: [MenuOptions](#menuoptions10) | Menu bound to the component, which is displayed when you click the component. A menu item can be a combination of text and icons or a custom component.<br>**content**: array of menu item text and icons or custom components.<br>**options**: parameters of the context menu. Optional.| | bindMenu | content: Array<[MenuItem](#menuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8),<br>options?: [MenuOptions](#menuoptions10) | Menu bound to the component, which is displayed when the user clicks the component. A menu item can be a combination of text and icons or a custom component.<br>**content**: array of menu item icons and text, or custom component.<br>**options**: parameters of the context menu.|
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8)<br>options: [ContextMenuOptions](#contextmenuoptions10) | Context menu bound to the component, which is displayed when the user long-presses or right-clicks the component. Only custom menu items are supported.<br>**responseType**: how the context menu triggered, which can be long-press or right-click. Mandatory. <br>**options**: parameters of the context menu. Optional.| | bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8)<br>options?: [ContextMenuOptions](#contextmenuoptions10) | Context menu bound to the component, which is displayed when the user long-presses or right-clicks the component. Only custom menu items are supported.<br>**responseType**: how the context menu is triggered, which can be long-press or right-click.<br>**options**: parameters of the context menu.|
## MenuItem ## MenuItem
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------------------ | -------------------------------------- | ---- | ---------------------- | | ------------------ | -------------------------------------- | ---- | ----------- |
| value | string | Yes | Menu item text. | | value | string | Yes | Menu item text. |
| icon<sup>10+</sup> | [ResourceStr](ts-types.md#resourcestr) | No | Menu item icon. | | icon<sup>10+</sup> | [ResourceStr](ts-types.md#resourcestr) | No | Menu item icon. |
| action | () =&gt; void | Yes | Action triggered when a menu item is clicked.| | action | () =&gt; void | Yes | Action triggered when a menu item is clicked.|
## MenuOptions<sup>10+</sup> ## MenuOptions<sup>10+</sup>
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ------ | -------------------------------- | ---- | ------------------------------------------------------ | | ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string | No | Menu title. | | title | string | No | Menu title.<br>**NOTE**<br>This parameter is available only when **content** is set to Array<[MenuItem](#menuitem)>.|
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen.| | offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No| Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all.| | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>If **placement** is set to **undefined** or **null** or is not set, the default value [BottomLeft](ts-appendix-enums.md#placement8) is used, and the position is relative to the parent component.|
| onAppear | () =&gt; void | No| Callback triggered when the menu is displayed.| | onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. |
| onDisappear | () =&gt; void | No| Callback triggered when the menu is hidden.| | onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. |
## ContextMenuOptions<sup>10+</sup> ## ContextMenuOptions<sup>10+</sup>
| Name | Type | Mandatory| Description | | Name | Type | Mandatory | Description |
| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. | | offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all.| | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all, and the context menu is displayed where the mouse is clicked.|
| onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. | | enableArrow | boolean | No | Whether to display an arrow. If the size and position of the context menu are insufficient for holding an arrow, no arrow is displayed.<br>Default value: **false**, indicating that no arrow is displayed<br>**NOTE**<br>An arrow is displayed in the position specified by **placement**. If **placement** is not set or its value is invalid, the arrow is displayed above the target. If the position is insufficient for holding the arrow, it is automatically adjusted.|
| onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. | | arrowOffset | [Length](ts-types.md#length) | No | Offset of the arrow relative to the context menu. When the arrow is placed in a horizontal position with the context menu: The value indicates the distance from the arrow to the leftmost; the arrow is centered by default. When the arrow is placed in a vertical position with the context menu: The value indicates the distance from the arrow to the top; the arrow is centered by default. The offset settings take effect only when the value is valid, can be converted to a number greater than 0, and does not cause the arrow to extend beyond the safe area of the context menu. The value of **placement** determines whether the offset is horizontal or vertical.|
| onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. |
| onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. |
## Example ## Example
...@@ -133,7 +135,7 @@ struct MenuExample { ...@@ -133,7 +135,7 @@ struct MenuExample {
### Example 3 ### Example 3
Context Menu (Displayed Upon Right-Clicking) Context Menu (Displayed Upon Right-Click)
```ts ```ts
// xxx.ets // xxx.ets
...@@ -166,3 +168,46 @@ struct ContextMenuExample { ...@@ -166,3 +168,46 @@ struct ContextMenuExample {
} }
} }
``` ```
### Example 4
Directive Menu (Displayed Upon Right-Click)
```ts
// xxx.ets
@Entry
@Component
struct DirectiveMenuExample {
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Options')
Divider().strokeWidth(2).margin(5).color('#F0F0F0')
Text('Hide')
Divider().strokeWidth(2).margin(5).color('#F0F0F0')
Text('Exit')
}
.width(200)
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Column() {
Text("DirectiveMenuExample")
.fontSize(20)
.width('100%')
.height("25%")
.backgroundColor('#F0F0F0')
.textAlign(TextAlign.Center)
.bindContextMenu(this.MenuBuilder, ResponseType.RightClick, {
enableArrow: true,
placement: Placement.Bottom
})
}
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001689126950](figures/en-us_image_0000001689126950.png)
...@@ -11,7 +11,14 @@ You can bind a full-screen modal to a component through the **bindContentCover** ...@@ -11,7 +11,14 @@ You can bind a full-screen modal to a component through the **bindContentCover**
| Name | Parameter | Description | | Name | Parameter | Description |
| ---------------- | ---------------------------------------- | ---------------------------------------- | | ---------------- | ---------------------------------------- | ---------------------------------------- |
| bindContentCover | isShow: boolean,<br>builder: [CustomBuilder](ts-types.md#custombuilder8),<br>type?: [ModalTransition](ts-types.md#modaltransition10) | Binds a modal to the component, which can be displayed when the component is touched. The content of the modal is customizable. The transition type can be set to none, slide-up and slide-down animation, and opacity gradient animation.<br>**isShow**: whether to display the modal. Mandatory.<br>**builder**: content of the modal. Mandatory.<br>**type**: transition type of the modal. This parameter is optional. | | bindContentCover | isShow: boolean,<br>builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: [ContentCoverOptions](#contentcoveroptions) | Binds a modal to the component, which can be displayed when the component is touched. The content of the modal is customizable. The transition type can be set to none, slide-up and slide-down animation, and opacity gradient animation.<br> **isShow**: whether to display the modal.<br>Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).<br>**builder**: content of the modal.<br> **options**: optional attributes of the modal.|
## ContentCoverOptions
| Name | Type | Mandatory | Description |
| --------------- | ---------------------------------------- | ---- | ------------- |
| modalTransition | [ModalTransition](ts-types.md#modaltransition10) | No | Transition mode of the modal. |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the modal. |
| onAppear | () => void | No | Callback invoked when the modal appears.|
| onDisappear | () => void | No | Callback invoked when the modal disappears.|
## Example ## Example
...@@ -38,7 +45,6 @@ struct ModalTransitionExample { ...@@ -38,7 +45,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Orange)
} }
@Builder myBuilder() { @Builder myBuilder() {
...@@ -48,7 +54,7 @@ struct ModalTransitionExample { ...@@ -48,7 +54,7 @@ struct ModalTransitionExample {
.fontSize(20) .fontSize(20)
.onClick(()=>{ .onClick(()=>{
this.isShow2 = true; this.isShow2 = true;
}).bindContentCover($$this.isShow2, this.myBuilder2(), ModalTransition.NONE) }).bindContentCover($$this.isShow2, this.myBuilder2(), {modalTransition: ModalTransition.NONE, backgroundColor: Color.Orange, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
Button("close modal 1") Button("close modal 1")
.margin(10) .margin(10)
...@@ -59,7 +65,6 @@ struct ModalTransitionExample { ...@@ -59,7 +65,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Pink)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
} }
...@@ -71,7 +76,7 @@ struct ModalTransitionExample { ...@@ -71,7 +76,7 @@ struct ModalTransitionExample {
}) })
.fontSize(20) .fontSize(20)
.margin(10) .margin(10)
.bindContentCover($$this.isShow, this.myBuilder(), ModalTransition.NONE) .bindContentCover($$this.isShow, this.myBuilder(), {modalTransition: ModalTransition.NONE, backgroundColor: Color.Pink, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
} }
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.backgroundColor("#ff49c8ab") .backgroundColor("#ff49c8ab")
...@@ -117,7 +122,6 @@ struct ModalTransitionExample { ...@@ -117,7 +122,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Orange)
} }
...@@ -128,7 +132,7 @@ struct ModalTransitionExample { ...@@ -128,7 +132,7 @@ struct ModalTransitionExample {
.fontSize(20) .fontSize(20)
.onClick(()=>{ .onClick(()=>{
this.isShow2 = true; this.isShow2 = true;
}).bindContentCover($$this.isShow2, this.myBuilder2(), ModalTransition.NONE) }).bindContentCover($$this.isShow2, this.myBuilder2(), {modalTransition: ModalTransition.NONE, backgroundColor: Color.Orange, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
Button("close modal 1") Button("close modal 1")
.margin(10) .margin(10)
...@@ -139,7 +143,6 @@ struct ModalTransitionExample { ...@@ -139,7 +143,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Pink)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.scale({x: this.isScale2, y: this.isScale2}) .scale({x: this.isScale2, y: this.isScale2})
.animation({curve:curves.springMotion()}) .animation({curve:curves.springMotion()})
...@@ -153,7 +156,7 @@ struct ModalTransitionExample { ...@@ -153,7 +156,7 @@ struct ModalTransitionExample {
}) })
.fontSize(20) .fontSize(20)
.margin(10) .margin(10)
.bindContentCover($$this.isShow, this.myBuilder(), ModalTransition.NONE) .bindContentCover($$this.isShow, this.myBuilder(), {modalTransition: ModalTransition.NONE, backgroundColor: Color.Pink, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
} }
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.backgroundColor("#ff49c8ab") .backgroundColor("#ff49c8ab")
...@@ -190,7 +193,6 @@ struct ModalTransitionExample { ...@@ -190,7 +193,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Gray)
} }
@Builder myBuilder() { @Builder myBuilder() {
...@@ -200,7 +202,7 @@ struct ModalTransitionExample { ...@@ -200,7 +202,7 @@ struct ModalTransitionExample {
.fontSize(20) .fontSize(20)
.onClick(()=>{ .onClick(()=>{
this.isShow2 = true; this.isShow2 = true;
}).bindContentCover(this.isShow2, this.myBuilder2(), ModalTransition.DEFAULT) }).bindContentCover(this.isShow2, this.myBuilder2(), {modalTransition: ModalTransition.DEFAULT, backgroundColor: Color.Gray, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
Button("close modal 1") Button("close modal 1")
.margin(10) .margin(10)
...@@ -211,7 +213,6 @@ struct ModalTransitionExample { ...@@ -211,7 +213,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Pink)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
} }
...@@ -223,7 +224,7 @@ struct ModalTransitionExample { ...@@ -223,7 +224,7 @@ struct ModalTransitionExample {
}) })
.fontSize(20) .fontSize(20)
.margin(10) .margin(10)
.bindContentCover($$this.isShow, this.myBuilder(), ModalTransition.DEFAULT) .bindContentCover($$this.isShow, this.myBuilder(), {modalTransition: ModalTransition.DEFAULT, backgroundColor: Color.Pink, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
} }
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.backgroundColor(Color.White) .backgroundColor(Color.White)
...@@ -258,7 +259,6 @@ struct ModalTransitionExample { ...@@ -258,7 +259,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Gray)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
} }
...@@ -270,7 +270,7 @@ struct ModalTransitionExample { ...@@ -270,7 +270,7 @@ struct ModalTransitionExample {
.fontSize(20) .fontSize(20)
.onClick(()=>{ .onClick(()=>{
this.isShow2 = true; this.isShow2 = true;
}).bindContentCover(this.isShow2, this.myBuilder2(), ModalTransition.ALPHA) }).bindContentCover(this.isShow2, this.myBuilder2(), {modalTransition: ModalTransition.ALPHA, backgroundColor: Color.Gray, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
Button("close modal 1") Button("close modal 1")
.margin(10) .margin(10)
...@@ -281,7 +281,6 @@ struct ModalTransitionExample { ...@@ -281,7 +281,6 @@ struct ModalTransitionExample {
} }
.width('100%') .width('100%')
.height('100%') .height('100%')
.backgroundColor(Color.Pink)
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
} }
...@@ -293,7 +292,7 @@ struct ModalTransitionExample { ...@@ -293,7 +292,7 @@ struct ModalTransitionExample {
}) })
.fontSize(20) .fontSize(20)
.margin(10) .margin(10)
.bindContentCover($$this.isShow, this.myBuilder(), ModalTransition.ALPHA) .bindContentCover($$this.isShow, this.myBuilder(), {modalTransition: ModalTransition.ALPHA, backgroundColor: Color.Pink, onAppear: () => {console.log("BindContentCover onAppear.")}, onDisappear: () => {console.log("BindContentCover onDisappear.")}})
} }
.justifyContent(FlexAlign.Center) .justifyContent(FlexAlign.Center)
.backgroundColor(Color.White) .backgroundColor(Color.White)
......
...@@ -4,16 +4,18 @@ You can set overlay text for a component. ...@@ -4,16 +4,18 @@ You can set overlay text for a component.
> **NOTE** > **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. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name| Type| Default Value| Description| | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | ------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| overlay | value: string,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {x?: number, y?: number}<br>} | {<br>align: Alignment.Center,<br>offset: {0, 0}<br>} | Overlay added to the component.<br> **value**: mask text.<br>**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.<br>If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.<br>Since API version 9, this API is supported in ArkTS widgets.| | overlay | value: string &#124; [CustomBuilder](../arkui-ts/ts-types.md#custombuilder8)<sup>10+</sup>,<br>options?: {<br>align?: [Alignment](ts-appendix-enums.md#alignment), <br>offset?: {x?: number, y?: number}<br>} | {<br>align: Alignment.Center,<br>offset: {0, 0}<br>} | Overlay of mask text or a custom component added to the component.<br> **value**: mask text content or custom component constructor.<br>**options**: position of the overlay. **align** indicates the position of the overlay relative to the component. [offset](ts-universal-attributes-location.md) indicates the offset of the overlay relative to the upper left corner of itself. By default, the overlay is in the upper left corner of the component.<br>If both **align** and **offset** are set, the overlay is first positioned relative to the component, and then offset relative to the upper left corner of itself.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When the overlay is a custom component, it cannot obtain focus through sequential keyboard navigation.|
## Example ## Example
### Example 1
```ts ```ts
// xxx.ets // xxx.ets
@Entry @Entry
...@@ -39,3 +41,29 @@ struct OverlayExample { ...@@ -39,3 +41,29 @@ struct OverlayExample {
``` ```
![en-us_image_0000001212058472](figures/en-us_image_0000001212058472.png) ![en-us_image_0000001212058472](figures/en-us_image_0000001212058472.png)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct OverlayExample {
@Builder OverlayNode() {
Column() {
Image($r('app.media.img1'))
Text("This is overlayNode").fontSize(20).fontColor(Color.White)
}.width(180).height(180).alignItems(HorizontalAlign.Center)
}
build() {
Column() {
Image($r('app.media.img2'))
.overlay(this.OverlayNode(), { align: Alignment.Center })
.objectFit(ImageFit.Contain)
}.width('100%')
.border({ color: Color.Black, width: 2 }).padding(20)
}
}
```
![en-us_image_0000001210111632](figures/en-us_image_0000001210111632.png)
...@@ -4,23 +4,23 @@ The **restoreId** attribute identifies a component in distributed migration scen ...@@ -4,23 +4,23 @@ The **restoreId** attribute identifies a component in distributed migration scen
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Attributes ## Attributes
| Name| Type| Description| | Name | Type | Description |
| -------- | -------- | -------- | | --------- | ------ | ---------------------------------------- |
| restoreId | number | ID of the component used for device matching during distributed migration. This ID must be unique within an application.| | restoreId | number | ID of the component used for device matching during distributed migration. This ID must be unique within an application.|
## Components with Distributed Migration Support ## Components with Distributed Migration Support
| Name| Initial API Version| Migration Status| | Name | Initial API Version| Migration Status |
| -------- | -------- | -------- | | --------- | ---- | ---------------------------------------- |
| List | 8 | The index of the list item displayed at the top of the list on the current device will be migrated to the remote device. After the migration, the list item that matches the index is displayed at the top of the list on the remote device.| | List | 8 | The index of the list item displayed at the top of the list on the current device will be migrated to the remote device. After the migration, the list item that matches the index is displayed at the top of the list on the remote device.|
| Grid | 9 | The index of the grid item displayed at the top of the grid on the current device will be migrated to the remote device. After the migration, the grid item that matches the index is displayed at the top of the grid on the remote device. The position of the scrollbar cannot be migrated.| | Grid | 9 | The index of the grid item displayed at the top of the grid on the current device will be migrated to the remote device. After the migration, the grid item that matches the index is displayed at the top of the grid on the remote device. The position of the scrollbar cannot be migrated.|
| Scroll | 9 | The absolute distance with the top edge for scrolling will be migrated. Due to layout inconsistency resulting from differences in the display specifications between devices, the migration effect may be affected.| | Scroll | 9 | The absolute distance with the top edge for scrolling will be migrated. Due to layout inconsistency resulting from differences in the display specifications between devices, the migration effect may be affected.|
| TextArea | 9 | The text content and the position of the caret will be migrated.| | TextArea | 9 | The text content and the position of the caret will be migrated. |
| TextInput | 9 | The text content and the position of the caret will be migrated.| | TextInput | 9 | The text content and the position of the caret will be migrated. |
## Example ## Example
......
...@@ -4,32 +4,36 @@ You can bind a sheet to a component through the **bindSheet** attribute. You can ...@@ -4,32 +4,36 @@ You can bind a sheet to a component through the **bindSheet** attribute. You can
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 10. Updates will be marked with a superscript to indicate their earliest API version.
> >
> Switching between landscape and portrait modes is not supported. > Switching between landscape and portrait modes is not supported.
## Attributes ## Attributes
| Name| Parameter| Description| | Name | Parameter | Description |
| ----- | ----- | ----- | | --------- | ---------------------------------------- | ---------------------------------------- |
| bindSheet | isShow: boolean,<br>builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: [SheetOptions](#sheetoptions) | Binds a sheet to the component, which can be displayed when the component is touched.<br>**isShow**: whether to display the sheet. Mandatory.<br>**builder**: content of the sheet. Mandatory.<br> **options**: options of the sheet. Optional.| | bindSheet | isShow: boolean,<br>builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: [SheetOptions](#sheetoptions) | Binds a sheet to the component, which can be displayed when the component is touched.<br>**isShow**: whether to display the sheet.<br>Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).<br>**builder**: content of the sheet.<br> **options**: optional attributes of the sheet.|
> **NOTE**
>
> When no two-way binding is set up for the **isShow** parameter, closing the sheet by dragging does not change the parameter value.
>
> To synchronize the value of **isShow** with the actual state of the sheet, it is recommended that you use the [$$](../../quick-start/arkts-two-way-sync.md) to set up two-way binding for **isShow**.
## SheetOptions ## SheetOptions
| Name| Type| Mandatory| Description| | Name | Type | Mandatory | Description |
| ----- | ----- | ----- | ------ | | --------------- | ---------------------------------------- | ---- | --------------- |
| height | [SheetSize](#sheetsize) \| [Length](ts-types.md#length) | No| Height of the sheet.<br>Default value: **LARGE**| | height | [SheetSize](#sheetsize) \| [Length](ts-types.md#length) | No | Height of the sheet.<br>Default value: **LARGE**|
| dragBar | boolean | No| Whether to display the drag bar. By default, the drag bar is displayed .| | dragBar | boolean | No | Whether to display the drag bar. By default, the drag bar is displayed . |
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No| Background color of the sheet.| | backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | No | Background color of the sheet. |
| onAppear | () => void | No| Callback invoked when the sheet is displayed.| | onAppear | () => void | No | Callback invoked when the sheet is displayed. |
| onDisappear | () => void | No| Callback invoked when the sheet is hidden.| | onDisappear | () => void | No | Callback invoked when the sheet is hidden. |
## SheetSize ## SheetSize
| Name| Description| | Name | Description |
| -------- | -------- | | ------ | --------------- |
| MEDIUM | The sheet height is half of the screen height.| | MEDIUM | The sheet height is half of the screen height.|
| LARGE | The sheet height is almost the screen height.| | LARGE | The sheet height is almost the screen height.|
## Example ## Example
......
# Mouse Event # Mouse Event
If an action triggers multiple events, the order of these events is fixed. By default, mouse events are transmitted transparently. If an action triggers multiple events, the order of these events is fixed. By default, mouse events are transmitted transparently.
...@@ -9,32 +13,32 @@ If an action triggers multiple events, the order of these events is fixed. By de ...@@ -9,32 +13,32 @@ If an action triggers multiple events, the order of these events is fixed. By de
## Events ## Events
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | | ---------------------------------------- | ---- | ---------------------------------------- |
| onHover(event: (isHover?: boolean, event<sup>10+</sup>?: HoverEvent) =&gt; void) | Yes | Triggered when the mouse cursor enters or leaves the component.<br>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component.<br>**event**: bubbling blocking of the event.| | onHover(event: (isHover?: boolean, event<sup>10+</sup>?: HoverEvent) =&gt; void) | Yes | Triggered when the mouse cursor enters or leaves the component.<br>**isHover**: whether the mouse cursor hovers over the component. The value **true** means that the mouse cursor enters the component, and the value **false** means that the mouse cursor leaves the component.<br>**event**: bubbling blocking of the event.|
| onMouse(event: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered.| | onMouse(event: (event?: MouseEvent) =&gt; void) | Yes | Triggered when the component is clicked by a mouse button or the mouse cursor moves on the component. The **event** parameter indicates the timestamp, mouse button, action, coordinates of the clicked point on the entire screen, and coordinates of the clicked point relative to the component when the event is triggered.|
## MouseEvent ## MouseEvent
| Name | Type | Description | | Name | Type | Description |
| --------- | ------------------------------- | -------------------- | | ---------------------- | ---------------------------------------- | ---------------------------- |
| screenX | number | X coordinate of the cursor position relative to the upper left corner of the application window.| | screenX | number | X coordinate of the cursor position relative to the upper left corner of the application window. |
| screenY | number | Y coordinate of the cursor position relative to the upper left corner of the application window.| | screenY | number | Y coordinate of the cursor position relative to the upper left corner of the application window. |
| x | number | X coordinate of the cursor position relative to the upper left corner of the component being clicked.| | x | number | X coordinate of the cursor position relative to the upper left corner of the component being clicked. |
| y | number | Y coordinate of the mouse position relative to the upper left corner of the component being clicked.| | y | number | Y coordinate of the mouse position relative to the upper left corner of the component being clicked. |
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. | | button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | Mouse action. | | action | [MouseAction](ts-appendix-enums.md#mouseaction) | Mouse action. |
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards. | | stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| | timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the component that triggers the event.| | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the component that triggers the event. |
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.| | source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device. |
## HoverEvent<sup>10+</sup> ## HoverEvent<sup>10+</sup>
| Name | Type | Description | | Name | Type | Description |
| --------- | ------------------------------- | -------------------- | | --------------- | ---------- | ------- |
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards.| | stopPropagation | () => void | Stops the event from bubbling upwards or downwards.|
## Example ## Example
......
...@@ -14,6 +14,8 @@ Allows an application to access Bluetooth configurations. ...@@ -14,6 +14,8 @@ Allows an application to access Bluetooth configurations.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.DISCOVER_BLUETOOTH ## ohos.permission.DISCOVER_BLUETOOTH
Allows an application to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices. Allows an application to configure Bluetooth on a device, initiate or cancel a scan for Bluetooth devices, and pair with Bluetooth devices.
...@@ -24,6 +26,8 @@ Allows an application to configure Bluetooth on a device, initiate or cancel a s ...@@ -24,6 +26,8 @@ Allows an application to configure Bluetooth on a device, initiate or cancel a s
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MANAGE_BLUETOOTH ## ohos.permission.MANAGE_BLUETOOTH
Allows an application to pair with a Bluetooth device and access the Contacts or messages of the device. Allows an application to pair with a Bluetooth device and access the Contacts or messages of the device.
...@@ -34,6 +38,8 @@ Allows an application to pair with a Bluetooth device and access the Contacts or ...@@ -34,6 +38,8 @@ Allows an application to pair with a Bluetooth device and access the Contacts or
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.ACCESS_BLUETOOTH ## ohos.permission.ACCESS_BLUETOOTH
Allows an application to access Bluetooth and use Bluetooth capabilities, such as pairing and connecting to peripheral devices. Allows an application to access Bluetooth and use Bluetooth capabilities, such as pairing and connecting to peripheral devices.
...@@ -44,6 +50,8 @@ Allows an application to access Bluetooth and use Bluetooth capabilities, such a ...@@ -44,6 +50,8 @@ Allows an application to access Bluetooth and use Bluetooth capabilities, such a
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.INTERNET ## ohos.permission.INTERNET
Allows an application to access the Internet. Allows an application to access the Internet.
...@@ -54,6 +62,8 @@ Allows an application to access the Internet. ...@@ -54,6 +62,8 @@ Allows an application to access the Internet.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.MODIFY_AUDIO_SETTINGS ## ohos.permission.MODIFY_AUDIO_SETTINGS
Allows an application to modify audio settings. Allows an application to modify audio settings.
...@@ -64,6 +74,8 @@ Allows an application to modify audio settings. ...@@ -64,6 +74,8 @@ Allows an application to modify audio settings.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.ACCESS_NOTIFICATION_POLICY ## ohos.permission.ACCESS_NOTIFICATION_POLICY
Allows an application to access the notification policy on the device. Allows an application to access the notification policy on the device.
...@@ -74,6 +86,8 @@ Allows an application to access the notification policy on the device. ...@@ -74,6 +86,8 @@ Allows an application to access the notification policy on the device.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 7
## ohos.permission.GET_TELEPHONY_STATE ## ohos.permission.GET_TELEPHONY_STATE
Allows an application to read telephony information. Allows an application to read telephony information.
...@@ -84,6 +98,8 @@ Allows an application to read telephony information. ...@@ -84,6 +98,8 @@ Allows an application to read telephony information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.REQUIRE_FORM ## ohos.permission.REQUIRE_FORM
Allows an application to obtain the Ability Form. Allows an application to obtain the Ability Form.
...@@ -94,6 +110,8 @@ Allows an application to obtain the Ability Form. ...@@ -94,6 +110,8 @@ Allows an application to obtain the Ability Form.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_NETWORK_INFO ## ohos.permission.GET_NETWORK_INFO
Allows an application to obtain network information. Allows an application to obtain network information.
...@@ -104,6 +122,8 @@ Allows an application to obtain network information. ...@@ -104,6 +122,8 @@ Allows an application to obtain network information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.PLACE_CALL ## ohos.permission.PLACE_CALL
Allows an application to make calls without starting the dialer. Allows an application to make calls without starting the dialer.
...@@ -114,6 +134,8 @@ Allows an application to make calls without starting the dialer. ...@@ -114,6 +134,8 @@ Allows an application to make calls without starting the dialer.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.SET_NETWORK_INFO ## ohos.permission.SET_NETWORK_INFO
Allows an application to set data network information. Allows an application to set data network information.
...@@ -124,6 +146,8 @@ Allows an application to set data network information. ...@@ -124,6 +146,8 @@ Allows an application to set data network information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.REMOVE_CACHE_FILES ## ohos.permission.REMOVE_CACHE_FILES
Allows the cache of the specified application to be cleared. Allows the cache of the specified application to be cleared.
...@@ -134,6 +158,8 @@ Allows the cache of the specified application to be cleared. ...@@ -134,6 +158,8 @@ Allows the cache of the specified application to be cleared.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.REBOOT ## ohos.permission.REBOOT
Allows an application to restart the device. Allows an application to restart the device.
...@@ -144,6 +170,8 @@ Allows an application to restart the device. ...@@ -144,6 +170,8 @@ Allows an application to restart the device.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.RUNNING_LOCK ## ohos.permission.RUNNING_LOCK
Allows an application to obtain a running lock. Allows an application to obtain a running lock.
...@@ -154,6 +182,8 @@ Allows an application to obtain a running lock. ...@@ -154,6 +182,8 @@ Allows an application to obtain a running lock.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.SET_TIME ## ohos.permission.SET_TIME
Allows an application to set the system time. Allows an application to set the system time.
...@@ -164,6 +194,8 @@ Allows an application to set the system time. ...@@ -164,6 +194,8 @@ Allows an application to set the system time.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.SET_TIME_ZONE ## ohos.permission.SET_TIME_ZONE
Allows an application to set the system time zone. Allows an application to set the system time zone.
...@@ -174,6 +206,8 @@ Allows an application to set the system time zone. ...@@ -174,6 +206,8 @@ Allows an application to set the system time zone.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.DOWNLOAD_SESSION_MANAGER ## ohos.permission.DOWNLOAD_SESSION_MANAGER
Allows an application to manage the download sessions. Allows an application to manage the download sessions.
...@@ -184,6 +218,8 @@ Allows an application to manage the download sessions. ...@@ -184,6 +218,8 @@ Allows an application to manage the download sessions.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.COMMONEVENT_STICKY ## ohos.permission.COMMONEVENT_STICKY
Allows an application to publish sticky common events. Allows an application to publish sticky common events.
...@@ -194,6 +230,8 @@ Allows an application to publish sticky common events. ...@@ -194,6 +230,8 @@ Allows an application to publish sticky common events.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.SYSTEM_FLOAT_WINDOW ## ohos.permission.SYSTEM_FLOAT_WINDOW
Allows an application to be displayed in a floating window on top of other applications. Allows an application to be displayed in a floating window on top of other applications.
...@@ -204,6 +242,8 @@ Allows an application to be displayed in a floating window on top of other appli ...@@ -204,6 +242,8 @@ Allows an application to be displayed in a floating window on top of other appli
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.PRIVACY_WINDOW ## ohos.permission.PRIVACY_WINDOW
Allows an application to set screens that cannot be captured or recorded. Allows an application to set screens that cannot be captured or recorded.
...@@ -214,6 +254,8 @@ Allows an application to set screens that cannot be captured or recorded. ...@@ -214,6 +254,8 @@ Allows an application to set screens that cannot be captured or recorded.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.POWER_MANAGER ## ohos.permission.POWER_MANAGER
Allows an application to hibernate or wake up the device by calling an API. Allows an application to hibernate or wake up the device by calling an API.
...@@ -224,6 +266,8 @@ Allows an application to hibernate or wake up the device by calling an API. ...@@ -224,6 +266,8 @@ Allows an application to hibernate or wake up the device by calling an API.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.REFRESH_USER_ACTION ## ohos.permission.REFRESH_USER_ACTION
Allows an application to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen. Allows an application to reset the screen timeout counter when a user input event occurs, such as pressing a key or touching the screen.
...@@ -234,6 +278,8 @@ Allows an application to reset the screen timeout counter when a user input even ...@@ -234,6 +278,8 @@ Allows an application to reset the screen timeout counter when a user input even
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.POWER_OPTIMIZATION ## ohos.permission.POWER_OPTIMIZATION
Allows an application to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes. Allows an application to set power saving mode, obtain configuration of the power saving mode, and receive notifications of the configuration changes.
...@@ -244,6 +290,8 @@ Allows an application to set power saving mode, obtain configuration of the powe ...@@ -244,6 +290,8 @@ Allows an application to set power saving mode, obtain configuration of the powe
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.REBOOT_RECOVERY ## ohos.permission.REBOOT_RECOVERY
Allows an application to restart the device and enter Recovery mode. Allows an application to restart the device and enter Recovery mode.
...@@ -254,6 +302,8 @@ Allows an application to restart the device and enter Recovery mode. ...@@ -254,6 +302,8 @@ Allows an application to restart the device and enter Recovery mode.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.MANAGE_LOCAL_ACCOUNTS ## ohos.permission.MANAGE_LOCAL_ACCOUNTS
Allows an application to manage local user accounts. Allows an application to manage local user accounts.
...@@ -264,6 +314,8 @@ Allows an application to manage local user accounts. ...@@ -264,6 +314,8 @@ Allows an application to manage local user accounts.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS ## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS
Allows access between multiple OS accounts. Allows access between multiple OS accounts.
...@@ -274,6 +326,8 @@ Allows access between multiple OS accounts. ...@@ -274,6 +326,8 @@ Allows access between multiple OS accounts.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.VIBRATE ## ohos.permission.VIBRATE
Allows an application to control vibration. Allows an application to control vibration.
...@@ -284,6 +338,8 @@ Allows an application to control vibration. ...@@ -284,6 +338,8 @@ Allows an application to control vibration.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CONNECT_IME_ABILITY ## ohos.permission.CONNECT_IME_ABILITY
Allows an application to bind the InputMethodAbility. Allows an application to bind the InputMethodAbility.
...@@ -294,6 +350,8 @@ Allows an application to bind the InputMethodAbility. ...@@ -294,6 +350,8 @@ Allows an application to bind the InputMethodAbility.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CONNECT_SCREEN_SAVER_ABILITY ## ohos.permission.CONNECT_SCREEN_SAVER_ABILITY
Allows an application to bind the ScreenSaverAbility. Allows an application to bind the ScreenSaverAbility.
...@@ -304,6 +362,8 @@ Allows an application to bind the ScreenSaverAbility. ...@@ -304,6 +362,8 @@ Allows an application to bind the ScreenSaverAbility.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.READ_SCREEN_SAVER ## ohos.permission.READ_SCREEN_SAVER
Allows an application to read the screen saver information, such as the list of screen savers that have been installed and the activated one. Allows an application to read the screen saver information, such as the list of screen savers that have been installed and the activated one.
...@@ -314,6 +374,8 @@ Allows an application to read the screen saver information, such as the list of ...@@ -314,6 +374,8 @@ Allows an application to read the screen saver information, such as the list of
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.WRITE_SCREEN_SAVER ## ohos.permission.WRITE_SCREEN_SAVER
Allows an application to modify the screen saver information, such as activating and previewing a screen saver. Allows an application to modify the screen saver information, such as activating and previewing a screen saver.
...@@ -324,9 +386,11 @@ Allows an application to modify the screen saver information, such as activating ...@@ -324,9 +386,11 @@ Allows an application to modify the screen saver information, such as activating
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.SET_WALLPAPER ## ohos.permission.SET_WALLPAPER
Allows an application to set a static wallpaper. Allows an application to set wallpapers.
**Permission level**: normal **Permission level**: normal
...@@ -334,6 +398,8 @@ Allows an application to set a static wallpaper. ...@@ -334,6 +398,8 @@ Allows an application to set a static wallpaper.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_WALLPAPER ## ohos.permission.GET_WALLPAPER
Allows an application to read wallpaper files. Allows an application to read wallpaper files.
...@@ -344,6 +410,8 @@ Allows an application to read wallpaper files. ...@@ -344,6 +410,8 @@ Allows an application to read wallpaper files.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CHANGE_ABILITY_ENABLED_STATE ## ohos.permission.CHANGE_ABILITY_ENABLED_STATE
Allows an application to enable or disable an application or component. Allows an application to enable or disable an application or component.
...@@ -354,6 +422,8 @@ Allows an application to enable or disable an application or component. ...@@ -354,6 +422,8 @@ Allows an application to enable or disable an application or component.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.ACCESS_MISSIONS ## ohos.permission.ACCESS_MISSIONS
Allows an application to obtain information about running processes and mission in a mission stack. Allows an application to obtain information about running processes and mission in a mission stack.
...@@ -364,6 +434,10 @@ Allows an application to obtain information about running processes and mission ...@@ -364,6 +434,10 @@ Allows an application to obtain information about running processes and mission
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
**Deprecated version**: 9
## ohos.permission.CLEAN_BACKGROUND_PROCESSES ## ohos.permission.CLEAN_BACKGROUND_PROCESSES
Allows an application to clear background processes based on their bundle names. Allows an application to clear background processes based on their bundle names.
...@@ -374,6 +448,8 @@ Allows an application to clear background processes based on their bundle names. ...@@ -374,6 +448,8 @@ Allows an application to clear background processes based on their bundle names.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.KEEP_BACKGROUND_RUNNING ## ohos.permission.KEEP_BACKGROUND_RUNNING
Allows a Service ability to keep running in the background. Allows a Service ability to keep running in the background.
...@@ -384,6 +460,8 @@ Allows a Service ability to keep running in the background. ...@@ -384,6 +460,8 @@ Allows a Service ability to keep running in the background.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.UPDATE_CONFIGURATION ## ohos.permission.UPDATE_CONFIGURATION
Allows an application to modify system settings. Allows an application to modify system settings.
...@@ -394,6 +472,8 @@ Allows an application to modify system settings. ...@@ -394,6 +472,8 @@ Allows an application to modify system settings.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.UPDATE_SYSTEM ## ohos.permission.UPDATE_SYSTEM
Allows an application to call the update APIs. Allows an application to call the update APIs.
...@@ -404,6 +484,8 @@ Allows an application to call the update APIs. ...@@ -404,6 +484,8 @@ Allows an application to call the update APIs.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.UPDATE_MIGRATE ## ohos.permission.UPDATE_MIGRATE
Allows data migration during the update process. Allows data migration during the update process.
...@@ -414,6 +496,8 @@ Allows data migration during the update process. ...@@ -414,6 +496,8 @@ Allows data migration during the update process.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.FACTORY_RESET ## ohos.permission.FACTORY_RESET
Allows an application to call the API for restoring factory settings. Allows an application to call the API for restoring factory settings.
...@@ -424,6 +508,8 @@ Allows an application to call the API for restoring factory settings. ...@@ -424,6 +508,8 @@ Allows an application to call the API for restoring factory settings.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GRANT_SENSITIVE_PERMISSIONS ## ohos.permission.GRANT_SENSITIVE_PERMISSIONS
Allows an application to grant sensitive permissions to other applications. Allows an application to grant sensitive permissions to other applications.
...@@ -434,6 +520,8 @@ Allows an application to grant sensitive permissions to other applications. ...@@ -434,6 +520,8 @@ Allows an application to grant sensitive permissions to other applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.REVOKE_SENSITIVE_PERMISSIONS ## ohos.permission.REVOKE_SENSITIVE_PERMISSIONS
Allows an application to revoke sensitive permissions granted to other applications. Allows an application to revoke sensitive permissions granted to other applications.
...@@ -444,6 +532,8 @@ Allows an application to revoke sensitive permissions granted to other applicati ...@@ -444,6 +532,8 @@ Allows an application to revoke sensitive permissions granted to other applicati
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_SENSITIVE_PERMISSIONS ## ohos.permission.GET_SENSITIVE_PERMISSIONS
Allows an application to obtain the sensitive permissions that have been granted to other applications. Allows an application to obtain the sensitive permissions that have been granted to other applications.
...@@ -454,6 +544,8 @@ Allows an application to obtain the sensitive permissions that have been granted ...@@ -454,6 +544,8 @@ Allows an application to obtain the sensitive permissions that have been granted
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION ## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION
Allows an application to set the attributes of applications of other users. Allows an application to set the attributes of applications of other users.
...@@ -464,6 +556,8 @@ Allows an application to set the attributes of applications of other users. ...@@ -464,6 +556,8 @@ Allows an application to set the attributes of applications of other users.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.LISTEN_BUNDLE_CHANGE ## ohos.permission.LISTEN_BUNDLE_CHANGE
Allows an application to listen for changes in other applications, when they are installed, updated, or uninstalled. Allows an application to listen for changes in other applications, when they are installed, updated, or uninstalled.
...@@ -474,9 +568,11 @@ Allows an application to listen for changes in other applications, when they are ...@@ -474,9 +568,11 @@ Allows an application to listen for changes in other applications, when they are
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_BUNDLE_INFO ## ohos.permission.GET_BUNDLE_INFO
Allows an application to query information about another application. This permission applies only to third-party applications. Allows an application to obtain basic information about another application.
**Permission level**: normal **Permission level**: normal
...@@ -484,9 +580,11 @@ Allows an application to query information about another application. This permi ...@@ -484,9 +580,11 @@ Allows an application to query information about another application. This permi
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_BUNDLE_INFO_PRIVILEGED ## ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
Allows an application to query information about other applications at the same time. Allows an application to obtain basic information and sensitive information about another application.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -494,6 +592,8 @@ Allows an application to query information about other applications at the same ...@@ -494,6 +592,8 @@ Allows an application to query information about other applications at the same
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.ACCELEROMETER ## ohos.permission.ACCELEROMETER
Allows an application to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor. Allows an application to read data from an acceleration sensor, uncalibrated acceleration sensor, or linear acceleration sensor.
...@@ -504,6 +604,8 @@ Allows an application to read data from an acceleration sensor, uncalibrated acc ...@@ -504,6 +604,8 @@ Allows an application to read data from an acceleration sensor, uncalibrated acc
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GYROSCOPE ## ohos.permission.GYROSCOPE
Allows an application to read data from a gyroscope sensor or uncalibrated gyroscope sensor. Allows an application to read data from a gyroscope sensor or uncalibrated gyroscope sensor.
...@@ -514,6 +616,8 @@ Allows an application to read data from a gyroscope sensor or uncalibrated gyros ...@@ -514,6 +616,8 @@ Allows an application to read data from a gyroscope sensor or uncalibrated gyros
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.INSTALL_BUNDLE ## ohos.permission.INSTALL_BUNDLE
Allows an application to install and uninstall other applications except enterprise applications, including enterprise InHouse, mobile device management (MDM), and Normal applications. Allows an application to install and uninstall other applications except enterprise applications, including enterprise InHouse, mobile device management (MDM), and Normal applications.
...@@ -524,6 +628,8 @@ Allows an application to install and uninstall other applications except enterpr ...@@ -524,6 +628,8 @@ Allows an application to install and uninstall other applications except enterpr
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.MANAGE_SHORTCUTS ## ohos.permission.MANAGE_SHORTCUTS
Allows an application to query and start shortcuts of other applications. Allows an application to query and start shortcuts of other applications.
...@@ -534,6 +640,8 @@ Allows an application to query and start shortcuts of other applications. ...@@ -534,6 +640,8 @@ Allows an application to query and start shortcuts of other applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.radio.ACCESS_FM_AM ## ohos.permission.radio.ACCESS_FM_AM
Allows an application to access radio services. Allows an application to access radio services.
...@@ -544,6 +652,8 @@ Allows an application to access radio services. ...@@ -544,6 +652,8 @@ Allows an application to access radio services.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.SET_TELEPHONY_STATE ## ohos.permission.SET_TELEPHONY_STATE
Allows an application to change the telephone state. Allows an application to change the telephone state.
...@@ -554,6 +664,8 @@ Allows an application to change the telephone state. ...@@ -554,6 +664,8 @@ Allows an application to change the telephone state.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.START_ABILITIES_FROM_BACKGROUND ## ohos.permission.START_ABILITIES_FROM_BACKGROUND
Allows an application to start or access other components from the background. Allows an application to start or access other components from the background.
...@@ -564,6 +676,8 @@ Allows an application to start or access other components from the background. ...@@ -564,6 +676,8 @@ Allows an application to start or access other components from the background.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.BUNDLE_ACTIVE_INFO ## ohos.permission.BUNDLE_ACTIVE_INFO
Allows an application to obtain how long other applications have been running in the foreground or background. Allows an application to obtain how long other applications have been running in the foreground or background.
...@@ -574,6 +688,8 @@ Allows an application to obtain how long other applications have been running in ...@@ -574,6 +688,8 @@ Allows an application to obtain how long other applications have been running in
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.START_INVISIBLE_ABILITY ## ohos.permission.START_INVISIBLE_ABILITY
Allows an application to start an invisible ability. Allows an application to start an invisible ability.
...@@ -584,6 +700,8 @@ Allows an application to start an invisible ability. ...@@ -584,6 +700,8 @@ Allows an application to start an invisible ability.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.sec.ACCESS_UDID ## ohos.permission.sec.ACCESS_UDID
Allows an application to obtain the Unified Device ID (UDID). Allows an application to obtain the Unified Device ID (UDID).
...@@ -594,6 +712,8 @@ Allows an application to obtain the Unified Device ID (UDID). ...@@ -594,6 +712,8 @@ Allows an application to obtain the Unified Device ID (UDID).
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.LAUNCH_DATA_PRIVACY_CENTER ## ohos.permission.LAUNCH_DATA_PRIVACY_CENTER
Allows an application to switch from its privacy statement page to the <b>Data & privacy</b> page. Allows an application to switch from its privacy statement page to the <b>Data & privacy</b> page.
...@@ -604,6 +724,8 @@ Allows an application to switch from its privacy statement page to the <b>Data & ...@@ -604,6 +724,8 @@ Allows an application to switch from its privacy statement page to the <b>Data &
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.MANAGE_MEDIA_RESOURCES ## ohos.permission.MANAGE_MEDIA_RESOURCES
Allows an application to obtain and manage the media resources that are being played on the device. Allows an application to obtain and manage the media resources that are being played on the device.
...@@ -614,6 +736,8 @@ Allows an application to obtain and manage the media resources that are being pl ...@@ -614,6 +736,8 @@ Allows an application to obtain and manage the media resources that are being pl
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.PUBLISH_AGENT_REMINDER ## ohos.permission.PUBLISH_AGENT_REMINDER
Allows an application to use agent-powered reminders. Allows an application to use agent-powered reminders.
...@@ -624,6 +748,8 @@ Allows an application to use agent-powered reminders. ...@@ -624,6 +748,8 @@ Allows an application to use agent-powered reminders.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR ## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR
Allows an application to use sync task animations. Allows an application to use sync task animations.
...@@ -634,6 +760,8 @@ Allows an application to use sync task animations. ...@@ -634,6 +760,8 @@ Allows an application to use sync task animations.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.INPUT_MONITORING ## ohos.permission.INPUT_MONITORING
Allows an application to listen for input events. Only the system signed applications can apply for this permission. Allows an application to listen for input events. Only the system signed applications can apply for this permission.
...@@ -644,6 +772,8 @@ Allows an application to listen for input events. Only the system signed applica ...@@ -644,6 +772,8 @@ Allows an application to listen for input events. Only the system signed applica
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.MANAGE_MISSIONS ## ohos.permission.MANAGE_MISSIONS
Allows an application to manage ability mission stacks. Allows an application to manage ability mission stacks.
...@@ -654,6 +784,8 @@ Allows an application to manage ability mission stacks. ...@@ -654,6 +784,8 @@ Allows an application to manage ability mission stacks.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.NOTIFICATION_CONTROLLER ## ohos.permission.NOTIFICATION_CONTROLLER
Allows an application to manage and subscribe to notifications. Allows an application to manage and subscribe to notifications.
...@@ -664,6 +796,8 @@ Allows an application to manage and subscribe to notifications. ...@@ -664,6 +796,8 @@ Allows an application to manage and subscribe to notifications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.CONNECTIVITY_INTERNAL ## ohos.permission.CONNECTIVITY_INTERNAL
Allows an application to obtain network information or modify network settings. Allows an application to obtain network information or modify network settings.
...@@ -674,6 +808,8 @@ Allows an application to obtain network information or modify network settings. ...@@ -674,6 +808,8 @@ Allows an application to obtain network information or modify network settings.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MANAGE_VPN ## ohos.permission.MANAGE_VPN
Allows an application to start or stop the VPN. Allows an application to start or stop the VPN.
...@@ -684,6 +820,8 @@ Allows an application to start or stop the VPN. ...@@ -684,6 +820,8 @@ Allows an application to start or stop the VPN.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.MANAGE_NET_STRATEGY ## ohos.permission.MANAGE_NET_STRATEGY
Allows an application to obtain network strategy information or modify network strategy settings. Allows an application to obtain network strategy information or modify network strategy settings.
...@@ -694,6 +832,8 @@ Allows an application to obtain network strategy information or modify network s ...@@ -694,6 +832,8 @@ Allows an application to obtain network strategy information or modify network s
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.GET_NETWORK_STATS ## ohos.permission.GET_NETWORK_STATS
Allows an application to obtain historical traffic information and listen for traffic changes. Allows an application to obtain historical traffic information and listen for traffic changes.
...@@ -704,6 +844,20 @@ Allows an application to obtain historical traffic information and listen for tr ...@@ -704,6 +844,20 @@ Allows an application to obtain historical traffic information and listen for tr
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.NETSYS_INTERNAL
Allows an SA to call the network management, Wi-Fi, network adapter listening, and iptables setting APIs of **netsys**.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.SET_ABILITY_CONTROLLER ## ohos.permission.SET_ABILITY_CONTROLLER
Allows an application to set the start and stop of an ability. Allows an application to set the start and stop of an ability.
...@@ -714,6 +868,8 @@ Allows an application to set the start and stop of an ability. ...@@ -714,6 +868,8 @@ Allows an application to set the start and stop of an ability.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.USE_USER_IDM ## ohos.permission.USE_USER_IDM
Allows an application to access the system identity credential information. Allows an application to access the system identity credential information.
...@@ -724,9 +880,11 @@ Allows an application to access the system identity credential information. ...@@ -724,9 +880,11 @@ Allows an application to access the system identity credential information.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 8
## ohos.permission.MANAGE_USER_IDM ## ohos.permission.MANAGE_USER_IDM
Allows an application to use the system identity credential management capability to enroll, modify, and delete PINs, face images, and fingerprints. Allows an application to enroll and manage user identity authentication credentials.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -734,6 +892,8 @@ Allows an application to use the system identity credential management capabilit ...@@ -734,6 +892,8 @@ Allows an application to use the system identity credential management capabilit
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 8
## ohos.permission.ACCESS_BIOMETRIC ## ohos.permission.ACCESS_BIOMETRIC
Allows an application to use biometric recognition for identity authentication. Allows an application to use biometric recognition for identity authentication.
...@@ -744,9 +904,11 @@ Allows an application to use biometric recognition for identity authentication. ...@@ -744,9 +904,11 @@ Allows an application to use biometric recognition for identity authentication.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 6
## ohos.permission.ACCESS_USER_AUTH_INTERNAL ## ohos.permission.ACCESS_USER_AUTH_INTERNAL
Allows an application to use the system identity authentication capability to authenticate or identify users. Allows an application to call internal system interfaces of IAM.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -754,9 +916,11 @@ Allows an application to use the system identity authentication capability to au ...@@ -754,9 +916,11 @@ Allows an application to use the system identity authentication capability to au
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 8
## ohos.permission.ACCESS_PIN_AUTH ## ohos.permission.ACCESS_PIN_AUTH
Allows a system application to call the PIN input APIs to present a password input dialog box for users. Allows an application to register the callback for obtaining the PIN during the PIN authentication process.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -764,6 +928,8 @@ Allows a system application to call the PIN input APIs to present a password inp ...@@ -764,6 +928,8 @@ Allows a system application to call the PIN input APIs to present a password inp
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 8
## ohos.permission.GET_RUNNING_INFO ## ohos.permission.GET_RUNNING_INFO
Allows an application to obtain running status information. Allows an application to obtain running status information.
...@@ -774,6 +940,8 @@ Allows an application to obtain running status information. ...@@ -774,6 +940,8 @@ Allows an application to obtain running status information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CLEAN_APPLICATION_DATA ## ohos.permission.CLEAN_APPLICATION_DATA
Allows an application to clear application data. Allows an application to clear application data.
...@@ -784,6 +952,8 @@ Allows an application to clear application data. ...@@ -784,6 +952,8 @@ Allows an application to clear application data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.RUNNING_STATE_OBSERVER ## ohos.permission.RUNNING_STATE_OBSERVER
Allows an application to observe the application status. Allows an application to observe the application status.
...@@ -794,6 +964,8 @@ Allows an application to observe the application status. ...@@ -794,6 +964,8 @@ Allows an application to observe the application status.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CAPTURE_SCREEN ## ohos.permission.CAPTURE_SCREEN
Allows an application to take screenshots. Allows an application to take screenshots.
...@@ -804,9 +976,11 @@ Allows an application to take screenshots. ...@@ -804,9 +976,11 @@ Allows an application to take screenshots.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_WIFI_INFO ## ohos.permission.GET_WIFI_INFO
Allows an application to obtain WLAN information. Allows an application to obtain Wi-Fi information.
**Permission level**: normal **Permission level**: normal
...@@ -814,9 +988,11 @@ Allows an application to obtain WLAN information. ...@@ -814,9 +988,11 @@ Allows an application to obtain WLAN information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_WIFI_INFO_INTERNAL ## ohos.permission.GET_WIFI_INFO_INTERNAL
Allows an application to obtain WLAN information. Allows a system application to obtain Wi-Fi parameters.
**Permission level**: system_core **Permission level**: system_core
...@@ -824,9 +1000,11 @@ Allows an application to obtain WLAN information. ...@@ -824,9 +1000,11 @@ Allows an application to obtain WLAN information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.SET_WIFI_INFO ## ohos.permission.SET_WIFI_INFO
Allows an application to set WLAN devices. Allows an application to set Wi-Fi devices.
**Permission level**: normal **Permission level**: normal
...@@ -834,9 +1012,11 @@ Allows an application to set WLAN devices. ...@@ -834,9 +1012,11 @@ Allows an application to set WLAN devices.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_WIFI_PEERS_MAC ## ohos.permission.GET_WIFI_PEERS_MAC
Allows an application to obtain the MAC address of the peer WLAN or Bluetooth device. Allows an application to obtain the MAC address of the peer Wi-Fi device.
**Permission level**: system_core **Permission level**: system_core
...@@ -844,9 +1024,11 @@ Allows an application to obtain the MAC address of the peer WLAN or Bluetooth de ...@@ -844,9 +1024,11 @@ Allows an application to obtain the MAC address of the peer WLAN or Bluetooth de
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_WIFI_LOCAL_MAC ## ohos.permission.GET_WIFI_LOCAL_MAC
Allows an application to obtain the MAC address of the local WLAN or Bluetooth device. Allows an application to obtain the MAC address of the local Wi-Fi device.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -854,9 +1036,11 @@ Allows an application to obtain the MAC address of the local WLAN or Bluetooth d ...@@ -854,9 +1036,11 @@ Allows an application to obtain the MAC address of the local WLAN or Bluetooth d
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_WIFI_CONFIG ## ohos.permission.GET_WIFI_CONFIG
Allows an application to obtain the WLAN configuration. Allows an application to obtain the Wi-Fi configuration.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -864,9 +1048,11 @@ Allows an application to obtain the WLAN configuration. ...@@ -864,9 +1048,11 @@ Allows an application to obtain the WLAN configuration.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.SET_WIFI_CONFIG ## ohos.permission.SET_WIFI_CONFIG
Allows an application to set WLAN information. Allows an application to configure Wi-Fi information.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -874,9 +1060,11 @@ Allows an application to set WLAN information. ...@@ -874,9 +1060,11 @@ Allows an application to set WLAN information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MANAGE_WIFI_CONNECTION ## ohos.permission.MANAGE_WIFI_CONNECTION
Allows an application to manage WLAN connections. Allows an application to manage Wi-Fi connections.
**Permission level**: system_core **Permission level**: system_core
...@@ -884,6 +1072,8 @@ Allows an application to manage WLAN connections. ...@@ -884,6 +1072,8 @@ Allows an application to manage WLAN connections.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MANAGE_WIFI_HOTSPOT ## ohos.permission.MANAGE_WIFI_HOTSPOT
Allows an application to enable or disable Wi-Fi hotspots. Allows an application to enable or disable Wi-Fi hotspots.
...@@ -894,6 +1084,8 @@ Allows an application to enable or disable Wi-Fi hotspots. ...@@ -894,6 +1084,8 @@ Allows an application to enable or disable Wi-Fi hotspots.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.GET_ALL_APP_ACCOUNTS ## ohos.permission.GET_ALL_APP_ACCOUNTS
Allows an application to obtain all application account information. Allows an application to obtain all application account information.
...@@ -904,6 +1096,8 @@ Allows an application to obtain all application account information. ...@@ -904,6 +1096,8 @@ Allows an application to obtain all application account information.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 7
## ohos.permission.MANAGE_SECURE_SETTINGS ## ohos.permission.MANAGE_SECURE_SETTINGS
Allows an application to modify security settings. Allows an application to modify security settings.
...@@ -914,6 +1108,8 @@ Allows an application to modify security settings. ...@@ -914,6 +1108,8 @@ Allows an application to modify security settings.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.READ_DFX_SYSEVENT ## ohos.permission.READ_DFX_SYSEVENT
Allows an application to access system event logging data. Allows an application to access system event logging data.
...@@ -924,9 +1120,11 @@ Allows an application to access system event logging data. ...@@ -924,9 +1120,11 @@ Allows an application to access system event logging data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN ## ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN
Allows an application to activate the device administrator app. Allows an application to activate a device administrator application.
**Permission level**: system_core **Permission level**: system_core
...@@ -934,9 +1132,11 @@ Allows an application to activate the device administrator app. ...@@ -934,9 +1132,11 @@ Allows an application to activate the device administrator app.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.SET_ENTERPRISE_INFO ## ohos.permission.SET_ENTERPRISE_INFO
Allows the device administrator application to set enterprise information. Allows a device administrator application to set enterprise information.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -944,9 +1144,11 @@ Allows the device administrator application to set enterprise information. ...@@ -944,9 +1144,11 @@ Allows the device administrator application to set enterprise information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT ## ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT
Allows the device administrator application to subscribe to management events. Allows a device administrator application to subscribe to management events.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -954,9 +1156,11 @@ Allows the device administrator application to subscribe to management events. ...@@ -954,9 +1156,11 @@ Allows the device administrator application to subscribe to management events.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ENTERPRISE_SET_DATETIME ## ohos.permission.ENTERPRISE_SET_DATETIME
Allows the device administrator application to set the system time. Allows a device administrator application to set the system time.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -964,9 +1168,11 @@ Allows the device administrator application to set the system time. ...@@ -964,9 +1168,11 @@ Allows the device administrator application to set the system time.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ENTERPRISE_GET_DEVICE_INFO ## ohos.permission.ENTERPRISE_GET_DEVICE_INFO
Allows the device administrator application to obtain device information. Allows a device administrator application to read device information.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -974,9 +1180,11 @@ Allows the device administrator application to obtain device information. ...@@ -974,9 +1180,11 @@ Allows the device administrator application to obtain device information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_RESET_DEVICE ## ohos.permission.ENTERPRISE_RESET_DEVICE
Allows the device administrator to restore factory settings of the device. Allows a device administrator application to restore devices' factory settings.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -984,6 +1192,8 @@ Allows the device administrator to restore factory settings of the device. ...@@ -984,6 +1192,8 @@ Allows the device administrator to restore factory settings of the device.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_WIFI ## ohos.permission.ENTERPRISE_SET_WIFI
Allows a device administrator application to set and query Wi-Fi information. Allows a device administrator application to set and query Wi-Fi information.
...@@ -994,6 +1204,8 @@ Allows a device administrator application to set and query Wi-Fi information. ...@@ -994,6 +1204,8 @@ Allows a device administrator application to set and query Wi-Fi information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_GET_NETWORK_INFO ## ohos.permission.ENTERPRISE_GET_NETWORK_INFO
Allows a device administrator application to query network information. Allows a device administrator application to query network information.
...@@ -1004,9 +1216,11 @@ Allows a device administrator application to query network information. ...@@ -1004,9 +1216,11 @@ Allows a device administrator application to query network information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY ## ohos.permission.ENTERPRISE_SET_ACCOUNT_POLICY
Allows the device administrator to set account management policies. Allows a device administrator application to set account management policies.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1014,9 +1228,11 @@ Allows the device administrator to set account management policies. ...@@ -1014,9 +1228,11 @@ Allows the device administrator to set account management policies.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY ## ohos.permission.ENTERPRISE_SET_BUNDLE_INSTALL_POLICY
Allows the device administrator to set bundle installation policies. Allows a device administrator application to set bundle installation policies.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1024,9 +1240,11 @@ Allows the device administrator to set bundle installation policies. ...@@ -1024,9 +1240,11 @@ Allows the device administrator to set bundle installation policies.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_NETWORK ## ohos.permission.ENTERPRISE_SET_NETWORK
Allows the device administrator application to set network information. Allows a device administrator application to set network information.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1034,9 +1252,11 @@ Allows the device administrator application to set network information. ...@@ -1034,9 +1252,11 @@ Allows the device administrator application to set network information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY ## ohos.permission.ENTERPRISE_MANAGE_SET_APP_RUNNING_POLICY
Allows the device administrator application to set application running policies. Allows a device administrator application to set application running policies.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1044,9 +1264,11 @@ Allows the device administrator application to set application running policies. ...@@ -1044,9 +1264,11 @@ Allows the device administrator application to set application running policies.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_SCREENOFF_TIME ## ohos.permission.ENTERPRISE_SET_SCREENOFF_TIME
Allows the device administrator application to set the screen off time. Allows a device administrator application to set the screen-off time.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1054,6 +1276,8 @@ Allows the device administrator application to set the screen off time. ...@@ -1054,6 +1276,8 @@ Allows the device administrator application to set the screen off time.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_INSTALL_BUNDLE ## ohos.permission.ENTERPRISE_INSTALL_BUNDLE
Allows a device administrator application to install and uninstall bundles. Allows a device administrator application to install and uninstall bundles.
...@@ -1064,9 +1288,11 @@ Allows a device administrator application to install and uninstall bundles. ...@@ -1064,9 +1288,11 @@ Allows a device administrator application to install and uninstall bundles.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_GET_SETTINGS ## ohos.permission.ENTERPRISE_GET_SETTINGS
Allows a device administrator application to obtain the **Settings** application data. Allows a device administrator application to query the **Settings** application data.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1074,6 +1300,8 @@ Allows a device administrator application to obtain the **Settings** application ...@@ -1074,6 +1300,8 @@ Allows a device administrator application to obtain the **Settings** application
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_MANAGE_CERTIFICATE ## ohos.permission.ENTERPRISE_MANAGE_CERTIFICATE
Allows a device administrator application to manage certificates. Allows a device administrator application to manage certificates.
...@@ -1084,6 +1312,8 @@ Allows a device administrator application to manage certificates. ...@@ -1084,6 +1312,8 @@ Allows a device administrator application to manage certificates.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_RESTRICT_POLICY ## ohos.permission.ENTERPRISE_RESTRICT_POLICY
Allows a device administrator application to deliver and obtain restriction policies. Allows a device administrator application to deliver and obtain restriction policies.
...@@ -1094,6 +1324,8 @@ Allows a device administrator application to deliver and obtain restriction poli ...@@ -1094,6 +1324,8 @@ Allows a device administrator application to deliver and obtain restriction poli
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_MANAGE_USB ## ohos.permission.ENTERPRISE_MANAGE_USB
Allows a device administrator application to manage the USB. Allows a device administrator application to manage the USB.
...@@ -1104,6 +1336,8 @@ Allows a device administrator application to manage the USB. ...@@ -1104,6 +1336,8 @@ Allows a device administrator application to manage the USB.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_MANAGE_NETWORK ## ohos.permission.ENTERPRISE_MANAGE_NETWORK
Allows a device administrator application to manage the network. Allows a device administrator application to manage the network.
...@@ -1114,9 +1348,11 @@ Allows a device administrator application to manage the network. ...@@ -1114,9 +1348,11 @@ Allows a device administrator application to manage the network.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ENTERPRISE_SET_BROWSER_POLICY ## ohos.permission.ENTERPRISE_SET_BROWSER_POLICY
Allows the device to set or cancel browser policies. Allows a device administrator application to set or delete browser policies.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1124,6 +1360,8 @@ Allows the device to set or cancel browser policies. ...@@ -1124,6 +1360,8 @@ Allows the device to set or cancel browser policies.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.NFC_TAG ## ohos.permission.NFC_TAG
Allows an application to read NFC tag information. Allows an application to read NFC tag information.
...@@ -1134,6 +1372,8 @@ Allows an application to read NFC tag information. ...@@ -1134,6 +1372,8 @@ Allows an application to read NFC tag information.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 7
## ohos.permission.NFC_CARD_EMULATION ## ohos.permission.NFC_CARD_EMULATION
Allows an application to implement card emulation. Allows an application to implement card emulation.
...@@ -1144,6 +1384,8 @@ Allows an application to implement card emulation. ...@@ -1144,6 +1384,8 @@ Allows an application to implement card emulation.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 8
## ohos.permission.PERMISSION_USED_STATS ## ohos.permission.PERMISSION_USED_STATS
Allows a system application to access the permission usage records. Allows a system application to access the permission usage records.
...@@ -1154,6 +1396,8 @@ Allows a system application to access the permission usage records. ...@@ -1154,6 +1396,8 @@ Allows a system application to access the permission usage records.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.NOTIFICATION_AGENT_CONTROLLER ## ohos.permission.NOTIFICATION_AGENT_CONTROLLER
Allows an application to send agent-powered notifications. Allows an application to send agent-powered notifications.
...@@ -1164,6 +1408,8 @@ Allows an application to send agent-powered notifications. ...@@ -1164,6 +1408,8 @@ Allows an application to send agent-powered notifications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ANSWER_CALL ## ohos.permission.ANSWER_CALL
Allows an application to answer incoming calls. Allows an application to answer incoming calls.
...@@ -1174,9 +1420,11 @@ Allows an application to answer incoming calls. ...@@ -1174,9 +1420,11 @@ Allows an application to answer incoming calls.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_CALENDAR ## ohos.permission.READ_CALENDAR
Allows an application to read calendar data. Allows an application to read Calendar data.
**Permission level**: normal **Permission level**: normal
...@@ -1184,6 +1432,8 @@ Allows an application to read calendar data. ...@@ -1184,6 +1432,8 @@ Allows an application to read calendar data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.READ_CALL_LOG ## ohos.permission.READ_CALL_LOG
Allows an application to read call logs. Allows an application to read call logs.
...@@ -1194,6 +1444,8 @@ Allows an application to read call logs. ...@@ -1194,6 +1444,8 @@ Allows an application to read call logs.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.READ_CELL_MESSAGES ## ohos.permission.READ_CELL_MESSAGES
Allows an application to read cell broadcast messages received by the device. Allows an application to read cell broadcast messages received by the device.
...@@ -1204,6 +1456,8 @@ Allows an application to read cell broadcast messages received by the device. ...@@ -1204,6 +1456,8 @@ Allows an application to read cell broadcast messages received by the device.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.READ_CONTACTS ## ohos.permission.READ_CONTACTS
Allows an application to read the Contacts. Allows an application to read the Contacts.
...@@ -1214,6 +1468,8 @@ Allows an application to read the Contacts. ...@@ -1214,6 +1468,8 @@ Allows an application to read the Contacts.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.READ_MESSAGES ## ohos.permission.READ_MESSAGES
Allows an application to read messages. Allows an application to read messages.
...@@ -1224,6 +1480,8 @@ Allows an application to read messages. ...@@ -1224,6 +1480,8 @@ Allows an application to read messages.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.RECEIVE_MMS ## ohos.permission.RECEIVE_MMS
Allows an application to receive and process MMS messages. Allows an application to receive and process MMS messages.
...@@ -1234,6 +1492,8 @@ Allows an application to receive and process MMS messages. ...@@ -1234,6 +1492,8 @@ Allows an application to receive and process MMS messages.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.RECEIVE_SMS ## ohos.permission.RECEIVE_SMS
Allows an application to receive and process SMS messages. Allows an application to receive and process SMS messages.
...@@ -1244,6 +1504,8 @@ Allows an application to receive and process SMS messages. ...@@ -1244,6 +1504,8 @@ Allows an application to receive and process SMS messages.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.RECEIVE_WAP_MESSAGES ## ohos.permission.RECEIVE_WAP_MESSAGES
Allows an application to receive and process WAP messages. Allows an application to receive and process WAP messages.
...@@ -1254,6 +1516,8 @@ Allows an application to receive and process WAP messages. ...@@ -1254,6 +1516,8 @@ Allows an application to receive and process WAP messages.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.MICROPHONE ## ohos.permission.MICROPHONE
Allows an application to access the microphone. Allows an application to access the microphone.
...@@ -1264,6 +1528,8 @@ Allows an application to access the microphone. ...@@ -1264,6 +1528,8 @@ Allows an application to access the microphone.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.SEND_MESSAGES ## ohos.permission.SEND_MESSAGES
Allows an application to send messages. Allows an application to send messages.
...@@ -1274,6 +1540,8 @@ Allows an application to send messages. ...@@ -1274,6 +1540,8 @@ Allows an application to send messages.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.WRITE_CALENDAR ## ohos.permission.WRITE_CALENDAR
Allows an application to add, remove, and modify Calendar events. Allows an application to add, remove, and modify Calendar events.
...@@ -1284,6 +1552,8 @@ Allows an application to add, remove, and modify Calendar events. ...@@ -1284,6 +1552,8 @@ Allows an application to add, remove, and modify Calendar events.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.WRITE_CALL_LOG ## ohos.permission.WRITE_CALL_LOG
Allows an application to add, remove, and modify call logs. Allows an application to add, remove, and modify call logs.
...@@ -1294,6 +1564,8 @@ Allows an application to add, remove, and modify call logs. ...@@ -1294,6 +1564,8 @@ Allows an application to add, remove, and modify call logs.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.WRITE_CONTACTS ## ohos.permission.WRITE_CONTACTS
Allows an application to add, remove, and modify the Contacts. Allows an application to add, remove, and modify the Contacts.
...@@ -1304,6 +1576,8 @@ Allows an application to add, remove, and modify the Contacts. ...@@ -1304,6 +1576,8 @@ Allows an application to add, remove, and modify the Contacts.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.DISTRIBUTED_DATASYNC ## ohos.permission.DISTRIBUTED_DATASYNC
Allows an application to exchange data with other devices. Allows an application to exchange data with other devices.
...@@ -1314,6 +1588,8 @@ Allows an application to exchange data with other devices. ...@@ -1314,6 +1588,8 @@ Allows an application to exchange data with other devices.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.MANAGE_VOICEMAIL ## ohos.permission.MANAGE_VOICEMAIL
Allows an application to leave messages in the voice mailbox. Allows an application to leave messages in the voice mailbox.
...@@ -1324,6 +1600,8 @@ Allows an application to leave messages in the voice mailbox. ...@@ -1324,6 +1600,8 @@ Allows an application to leave messages in the voice mailbox.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 8
## ohos.permission.LOCATION_IN_BACKGROUND ## ohos.permission.LOCATION_IN_BACKGROUND
Allows an application running in the background to obtain the device location. Allows an application running in the background to obtain the device location.
...@@ -1334,29 +1612,35 @@ Allows an application running in the background to obtain the device location. ...@@ -1334,29 +1612,35 @@ Allows an application running in the background to obtain the device location.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 7
## ohos.permission.LOCATION ## ohos.permission.LOCATION
Allows an application to obtain the device location. Allows an application to obtain the device location.
**Application conditions**: The applications developed using the SDK earlier than API version 9 can directly apply for this permission. For the applications developed using the SDK of API version 9 or later, you need to apply for [ohos.permission.APPROXIMATELY_LOCATION](#ohospermissionapproximately_location) before applying for this permission.
**Permission level**: normal **Permission level**: normal
**Authorization mode**: user_grant **Authorization mode**: user_grant
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Application conditions**: The applications developed using the SDK earlier than API version 9 can directly apply for this permission. For the applications developed using the SDK of API version 9 or later, you need to apply for [ohos.permission.APPROXIMATELY_LOCATION](#ohospermissionapproximately_location) before applying for this permission. **Start version**: 7
## ohos.permission.APPROXIMATELY_LOCATION ## ohos.permission.APPROXIMATELY_LOCATION
Allows an application to obtain the approximate location information of a device. Allows an application to obtain the approximate location information of a device.
**Application conditions**: Only applications developed using the SDK of API version 9 or later can apply for this permission.
**Permission level**: normal **Permission level**: normal
**Authorization mode**: user_grant **Authorization mode**: user_grant
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Application conditions**: Only applications developed using the SDK of API version 9 or later can apply for this permission. **Start version**: 9
## ohos.permission.MEDIA_LOCATION ## ohos.permission.MEDIA_LOCATION
...@@ -1368,6 +1652,8 @@ Allows an application to access geographical locations in the user's media file. ...@@ -1368,6 +1652,8 @@ Allows an application to access geographical locations in the user's media file.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.CAMERA ## ohos.permission.CAMERA
Allows an application to use the camera to take photos and record videos. Allows an application to use the camera to take photos and record videos.
...@@ -1378,6 +1664,8 @@ Allows an application to use the camera to take photos and record videos. ...@@ -1378,6 +1664,8 @@ Allows an application to use the camera to take photos and record videos.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_MEDIA ## ohos.permission.READ_MEDIA
Allows an application to read media files from the user's external storage. Allows an application to read media files from the user's external storage.
...@@ -1388,6 +1676,8 @@ Allows an application to read media files from the user's external storage. ...@@ -1388,6 +1676,8 @@ Allows an application to read media files from the user's external storage.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.WRITE_MEDIA ## ohos.permission.WRITE_MEDIA
Allows an application to read media files from and write media files into the user's external storage. Allows an application to read media files from and write media files into the user's external storage.
...@@ -1398,6 +1688,8 @@ Allows an application to read media files from and write media files into the us ...@@ -1398,6 +1688,8 @@ Allows an application to read media files from and write media files into the us
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.ACTIVITY_MOTION ## ohos.permission.ACTIVITY_MOTION
Allows an application to read the current workout status of the user. Allows an application to read the current workout status of the user.
...@@ -1408,6 +1700,8 @@ Allows an application to read the current workout status of the user. ...@@ -1408,6 +1700,8 @@ Allows an application to read the current workout status of the user.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.READ_HEALTH_DATA ## ohos.permission.READ_HEALTH_DATA
Allows an application to read the health data of the user. Allows an application to read the health data of the user.
...@@ -1418,6 +1712,8 @@ Allows an application to read the health data of the user. ...@@ -1418,6 +1712,8 @@ Allows an application to read the health data of the user.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 7
## ohos.permission.GET_DEFAULT_APPLICATION ## ohos.permission.GET_DEFAULT_APPLICATION
Allows an application to query default applications. Allows an application to query default applications.
...@@ -1428,6 +1724,8 @@ Allows an application to query default applications. ...@@ -1428,6 +1724,8 @@ Allows an application to query default applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.SET_DEFAULT_APPLICATION ## ohos.permission.SET_DEFAULT_APPLICATION
Allows an application to set and reset default applications. Allows an application to set and reset default applications.
...@@ -1438,6 +1736,8 @@ Allows an application to set and reset default applications. ...@@ -1438,6 +1736,8 @@ Allows an application to set and reset default applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.MANAGE_DISPOSED_APP_STATUS ## ohos.permission.MANAGE_DISPOSED_APP_STATUS
Allows an application to set and query the application handling state. Allows an application to set and query the application handling state.
...@@ -1448,6 +1748,8 @@ Allows an application to set and query the application handling state. ...@@ -1448,6 +1748,8 @@ Allows an application to set and query the application handling state.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ACCESS_IDS ## ohos.permission.ACCESS_IDS
Allows an application to query the unique identifier of a device. Allows an application to query the unique identifier of a device.
...@@ -1458,6 +1760,8 @@ Allows an application to query the unique identifier of a device. ...@@ -1458,6 +1760,8 @@ Allows an application to query the unique identifier of a device.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.DUMP ## ohos.permission.DUMP
Allows the basic system information and SA service information to be exported. Allows the basic system information and SA service information to be exported.
...@@ -1468,6 +1772,8 @@ Allows the basic system information and SA service information to be exported. ...@@ -1468,6 +1772,8 @@ Allows the basic system information and SA service information to be exported.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.DISTRIBUTED_SOFTBUS_CENTER ## ohos.permission.DISTRIBUTED_SOFTBUS_CENTER
Allows networking between different devices. Allows networking between different devices.
...@@ -1478,6 +1784,8 @@ Allows networking between different devices. ...@@ -1478,6 +1784,8 @@ Allows networking between different devices.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 9
## ohos.permission.ACCESS_DLP_FILE ## ohos.permission.ACCESS_DLP_FILE
Allows configuration and management of the permissions on .dlp files. Allows configuration and management of the permissions on .dlp files.
...@@ -1488,6 +1796,8 @@ Allows configuration and management of the permissions on .dlp files. ...@@ -1488,6 +1796,8 @@ Allows configuration and management of the permissions on .dlp files.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.PROVISIONING_MESSAGE ## ohos.permission.PROVISIONING_MESSAGE
Allows the Super Device Manager application to be activated. Allows the Super Device Manager application to be activated.
...@@ -1498,6 +1808,8 @@ Allows the Super Device Manager application to be activated. ...@@ -1498,6 +1808,8 @@ Allows the Super Device Manager application to be activated.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ACCESS_SYSTEM_SETTINGS ## ohos.permission.ACCESS_SYSTEM_SETTINGS
Allows an application to access or start system **Settings**. Allows an application to access or start system **Settings**.
...@@ -1508,6 +1820,8 @@ Allows an application to access or start system **Settings**. ...@@ -1508,6 +1820,8 @@ Allows an application to access or start system **Settings**.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_IMAGEVIDEO ## ohos.permission.READ_IMAGEVIDEO
Allows access to the images or video files in a user's directory. Allows access to the images or video files in a user's directory.
...@@ -1518,6 +1832,8 @@ Allows access to the images or video files in a user's directory. ...@@ -1518,6 +1832,8 @@ Allows access to the images or video files in a user's directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_AUDIO ## ohos.permission.READ_AUDIO
Allows access to the audio files in a user directory. Allows access to the audio files in a user directory.
...@@ -1528,6 +1844,8 @@ Allows access to the audio files in a user directory. ...@@ -1528,6 +1844,8 @@ Allows access to the audio files in a user directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_DOCUMENT ## ohos.permission.READ_DOCUMENT
Allows access to the files in a user directory. Allows access to the files in a user directory.
...@@ -1538,6 +1856,8 @@ Allows access to the files in a user directory. ...@@ -1538,6 +1856,8 @@ Allows access to the files in a user directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.WRITE_IMAGEVIDEO ## ohos.permission.WRITE_IMAGEVIDEO
Allows modification to the images or video files in a user's directory. Allows modification to the images or video files in a user's directory.
...@@ -1548,6 +1868,8 @@ Allows modification to the images or video files in a user's directory. ...@@ -1548,6 +1868,8 @@ Allows modification to the images or video files in a user's directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.WRITE_AUDIO ## ohos.permission.WRITE_AUDIO
Allows modification to the audio files in a user directory. Allows modification to the audio files in a user directory.
...@@ -1558,6 +1880,8 @@ Allows modification to the audio files in a user directory. ...@@ -1558,6 +1880,8 @@ Allows modification to the audio files in a user directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.WRITE_DOCUMENT ## ohos.permission.WRITE_DOCUMENT
Allows modification to the files in a user's directory. Allows modification to the files in a user's directory.
...@@ -1568,6 +1892,8 @@ Allows modification to the files in a user's directory. ...@@ -1568,6 +1892,8 @@ Allows modification to the files in a user's directory.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ABILITY_BACKGROUND_COMMUNICATION ## ohos.permission.ABILITY_BACKGROUND_COMMUNICATION
Allows an application to start the Ability component in the background and establish a connection with it. Allows an application to start the Ability component in the background and establish a connection with it.
...@@ -1578,6 +1904,8 @@ Allows an application to start the Ability component in the background and estab ...@@ -1578,6 +1904,8 @@ Allows an application to start the Ability component in the background and estab
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.securityguard.REPORT_SECURITY_INFO ## ohos.permission.securityguard.REPORT_SECURITY_INFO
Allows an application to report risk data for security guard. Allows an application to report risk data for security guard.
...@@ -1588,6 +1916,8 @@ Allows an application to report risk data for security guard. ...@@ -1588,6 +1916,8 @@ Allows an application to report risk data for security guard.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT ## ohos.permission.securityguard.REQUEST_SECURITY_MODEL_RESULT
Allows an application to obtain the device risk status. Allows an application to obtain the device risk status.
...@@ -1598,6 +1928,8 @@ Allows an application to obtain the device risk status. ...@@ -1598,6 +1928,8 @@ Allows an application to obtain the device risk status.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO ## ohos.permission.securityguard.REQUEST_SECURITY_EVENT_INFO
Allows an application to obtain detailed risk data. Allows an application to obtain detailed risk data.
...@@ -1608,6 +1940,8 @@ Allows an application to obtain detailed risk data. ...@@ -1608,6 +1940,8 @@ Allows an application to obtain detailed risk data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_ACCESSIBILITY_CONFIG ## ohos.permission.READ_ACCESSIBILITY_CONFIG
Allows an application to read the accessibility configuration. Allows an application to read the accessibility configuration.
...@@ -1618,6 +1952,8 @@ Allows an application to read the accessibility configuration. ...@@ -1618,6 +1952,8 @@ Allows an application to read the accessibility configuration.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 9
## ohos.permission.WRITE_ACCESSIBILITY_CONFIG ## ohos.permission.WRITE_ACCESSIBILITY_CONFIG
Allows an application to set the accessibility configuration. Allows an application to set the accessibility configuration.
...@@ -1628,6 +1964,8 @@ Allows an application to set the accessibility configuration. ...@@ -1628,6 +1964,8 @@ Allows an application to set the accessibility configuration.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 9
## ohos.permission.ACCESS_CERT_MANAGER_INTERNAL ## ohos.permission.ACCESS_CERT_MANAGER_INTERNAL
Allows an application to install, uninstall, enable, and disable certificates and credentials. Allows an application to install, uninstall, enable, and disable certificates and credentials.
...@@ -1638,9 +1976,11 @@ Allows an application to install, uninstall, enable, and disable certificates an ...@@ -1638,9 +1976,11 @@ Allows an application to install, uninstall, enable, and disable certificates an
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ACCESS_CERT_MANAGER ## ohos.permission.ACCESS_CERT_MANAGER
Allows an application to manage private credentials and query certificate status. Allows an application to query certificates and private credentials.
**Permission level**: normal **Permission level**: normal
...@@ -1648,6 +1988,8 @@ Allows an application to manage private credentials and query certificate status ...@@ -1648,6 +1988,8 @@ Allows an application to manage private credentials and query certificate status
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 9
## ohos.permission.ACCESS_PUSH_SERVICE ## ohos.permission.ACCESS_PUSH_SERVICE
Allows an application to access the Ability of the push service. Allows an application to access the Ability of the push service.
...@@ -1658,6 +2000,8 @@ Allows an application to access the Ability of the push service. ...@@ -1658,6 +2000,8 @@ Allows an application to access the Ability of the push service.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_APP_PUSH_DATA ## ohos.permission.READ_APP_PUSH_DATA
Allows the push service to read data from an application. Allows the push service to read data from an application.
...@@ -1668,6 +2012,8 @@ Allows the push service to read data from an application. ...@@ -1668,6 +2012,8 @@ Allows the push service to read data from an application.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.WRITE_APP_PUSH_DATA ## ohos.permission.WRITE_APP_PUSH_DATA
Allows the push service to write data to an application. Allows the push service to write data to an application.
...@@ -1678,6 +2024,8 @@ Allows the push service to write data to an application. ...@@ -1678,6 +2024,8 @@ Allows the push service to write data to an application.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.RECEIVER_STARTUP_COMPLETED ## ohos.permission.RECEIVER_STARTUP_COMPLETED
Allows an application to subscribe to the startup broadcast. Allows an application to subscribe to the startup broadcast.
...@@ -1688,6 +2036,8 @@ Allows an application to subscribe to the startup broadcast. ...@@ -1688,6 +2036,8 @@ Allows an application to subscribe to the startup broadcast.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 9
## ohos.permission.MANAGE_CAMERA_CONFIG ## ohos.permission.MANAGE_CAMERA_CONFIG
Allows an application to enable or disable cameras globally. Allows an application to enable or disable cameras globally.
...@@ -1696,11 +2046,13 @@ Allows an application to enable or disable cameras globally. ...@@ -1696,11 +2046,13 @@ Allows an application to enable or disable cameras globally.
**Authorization mode**: system_grant **Authorization mode**: system_grant
**Enable ACL**: FALSE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_WHOLE_CALENDAR ## ohos.permission.READ_WHOLE_CALENDAR
Allows an application to read all calendar information. Allows an application to read all Calendar information.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -1708,6 +2060,8 @@ Allows an application to read all calendar information. ...@@ -1708,6 +2060,8 @@ Allows an application to read all calendar information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.WRITE_WHOLE_CALENDAR ## ohos.permission.WRITE_WHOLE_CALENDAR
Allows an application to add, remove, or change all Calendar events. Allows an application to add, remove, or change all Calendar events.
...@@ -1718,9 +2072,11 @@ Allows an application to add, remove, or change all Calendar events. ...@@ -1718,9 +2072,11 @@ Allows an application to add, remove, or change all Calendar events.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
## ohos.permission.ENFORCE_USER_IAM **Start version**: 9
Allows an SA to delete user information from the IAM subsystem without a token. ## ohos.permission.ENFORCE_USER_IDM
Allows an SA to delete the IAM user information without a token.
**Permission level**: system_core **Permission level**: system_core
...@@ -1728,6 +2084,8 @@ Allows an SA to delete user information from the IAM subsystem without a token. ...@@ -1728,6 +2084,8 @@ Allows an SA to delete user information from the IAM subsystem without a token.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ACCESS_AUTH_RESPOOL ## ohos.permission.ACCESS_AUTH_RESPOOL
Allows an SA to register the executor. Allows an SA to register the executor.
...@@ -1738,6 +2096,8 @@ Allows an SA to register the executor. ...@@ -1738,6 +2096,8 @@ Allows an SA to register the executor.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.MOUNT_UNMOUNT_MANAGER ## ohos.permission.MOUNT_UNMOUNT_MANAGER
Allows an application to mount and unmount external cards. Allows an application to mount and unmount external cards.
...@@ -1748,6 +2108,8 @@ Allows an application to mount and unmount external cards. ...@@ -1748,6 +2108,8 @@ Allows an application to mount and unmount external cards.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.MOUNT_FORMAT_MANAGER ## ohos.permission.MOUNT_FORMAT_MANAGER
Allows an application to format external cards. Allows an application to format external cards.
...@@ -1758,6 +2120,8 @@ Allows an application to format external cards. ...@@ -1758,6 +2120,8 @@ Allows an application to format external cards.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.STORAGE_MANAGER ## ohos.permission.STORAGE_MANAGER
Allows an application to call the interfaces of the Storage Manager service to query space statistics and volume information. Allows an application to call the interfaces of the Storage Manager service to query space statistics and volume information.
...@@ -1768,6 +2132,8 @@ Allows an application to call the interfaces of the Storage Manager service to q ...@@ -1768,6 +2132,8 @@ Allows an application to call the interfaces of the Storage Manager service to q
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.BACKUP ## ohos.permission.BACKUP
Allows an application to have backup and restore capabilities. Allows an application to have backup and restore capabilities.
...@@ -1778,6 +2144,8 @@ Allows an application to have backup and restore capabilities. ...@@ -1778,6 +2144,8 @@ Allows an application to have backup and restore capabilities.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.CLOUDFILE_SYNC_MANAGER ## ohos.permission.CLOUDFILE_SYNC_MANAGER
Allows an application to obtain the device-cloud synchronization management capability. Allows an application to obtain the device-cloud synchronization management capability.
...@@ -1788,6 +2156,8 @@ Allows an application to obtain the device-cloud synchronization management capa ...@@ -1788,6 +2156,8 @@ Allows an application to obtain the device-cloud synchronization management capa
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.CLOUDFILE_SYNC ## ohos.permission.CLOUDFILE_SYNC
Allows an application to perform device-cloud synchronization. Allows an application to perform device-cloud synchronization.
...@@ -1798,6 +2168,8 @@ Allows an application to perform device-cloud synchronization. ...@@ -1798,6 +2168,8 @@ Allows an application to perform device-cloud synchronization.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.FILE_ACCESS_MANAGER ## ohos.permission.FILE_ACCESS_MANAGER
Allows a file management application to access user data files through the FAF. Allows a file management application to access user data files through the FAF.
...@@ -1808,6 +2180,8 @@ Allows a file management application to access user data files through the FAF. ...@@ -1808,6 +2180,8 @@ Allows a file management application to access user data files through the FAF.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.MANAGE_AUDIO_CONFIG ## ohos.permission.MANAGE_AUDIO_CONFIG
Allows an application to mute microphones globally. Allows an application to mute microphones globally.
...@@ -1818,6 +2192,8 @@ Allows an application to mute microphones globally. ...@@ -1818,6 +2192,8 @@ Allows an application to mute microphones globally.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.ACCESS_SERVICE_DM ## ohos.permission.ACCESS_SERVICE_DM
Allows a system application to obtain the authentication and networking capability of distributed devices. Allows a system application to obtain the authentication and networking capability of distributed devices.
...@@ -1828,6 +2204,8 @@ Allows a system application to obtain the authentication and networking capabili ...@@ -1828,6 +2204,8 @@ Allows a system application to obtain the authentication and networking capabili
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10+
## ohos.permission.APP_TRACKING_CONSENT ## ohos.permission.APP_TRACKING_CONSENT
Allows an application to read the open anonymous device identifier (OAID). Allows an application to read the open anonymous device identifier (OAID).
...@@ -1838,6 +2216,8 @@ Allows an application to read the open anonymous device identifier (OAID). ...@@ -1838,6 +2216,8 @@ Allows an application to read the open anonymous device identifier (OAID).
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.RUN_ANY_CODE ## ohos.permission.RUN_ANY_CODE
Allows an application to run unsigned code. Allows an application to run unsigned code.
...@@ -1848,6 +2228,8 @@ Allows an application to run unsigned code. ...@@ -1848,6 +2228,8 @@ Allows an application to run unsigned code.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT ## ohos.permission.PUBLISH_SYSTEM_COMMON_EVENT
Allows an application to publish system common events. Allows an application to publish system common events.
...@@ -1858,6 +2240,8 @@ Allows an application to publish system common events. ...@@ -1858,6 +2240,8 @@ Allows an application to publish system common events.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ACCESS_SCREEN_LOCK_INNER ## ohos.permission.ACCESS_SCREEN_LOCK_INNER
Allows an application to use the lock screen service to lock the screen, send a screen lock event, and invoke the system event callback. Allows an application to use the lock screen service to lock the screen, send a screen lock event, and invoke the system event callback.
...@@ -1866,7 +2250,9 @@ Allows an application to use the lock screen service to lock the screen, send a ...@@ -1866,7 +2250,9 @@ Allows an application to use the lock screen service to lock the screen, send a
**Authorization mode**: system_grant **Authorization mode**: system_grant
**Enable ACL**: FALSE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.PRINT ## ohos.permission.PRINT
...@@ -1878,6 +2264,8 @@ Allows an application to obtain the print framework capability. ...@@ -1878,6 +2264,8 @@ Allows an application to obtain the print framework capability.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.MANAGE_PRINT_JOB ## ohos.permission.MANAGE_PRINT_JOB
Allows an application to obtain the capability of managing print tasks. Allows an application to obtain the capability of managing print tasks.
...@@ -1888,6 +2276,8 @@ Allows an application to obtain the capability of managing print tasks. ...@@ -1888,6 +2276,8 @@ Allows an application to obtain the capability of managing print tasks.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.CHANGE_OVERLAY_ENABLED_STATE ## ohos.permission.CHANGE_OVERLAY_ENABLED_STATE
Allows a system application to disable the application with the overlay feature enabled. Allows a system application to disable the application with the overlay feature enabled.
...@@ -1898,6 +2288,8 @@ Allows a system application to disable the application with the overlay feature ...@@ -1898,6 +2288,8 @@ Allows a system application to disable the application with the overlay feature
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.CONNECT_CELLULAR_CALL_SERVICE ## ohos.permission.CONNECT_CELLULAR_CALL_SERVICE
Allows a system ability (SA) to access the cellular call SA. Allows a system ability (SA) to access the cellular call SA.
...@@ -1908,6 +2300,8 @@ Allows a system ability (SA) to access the cellular call SA. ...@@ -1908,6 +2300,8 @@ Allows a system ability (SA) to access the cellular call SA.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.CONNECT_IMS_SERVICE ## ohos.permission.CONNECT_IMS_SERVICE
Allows an SA to access the IMS SA. Allows an SA to access the IMS SA.
...@@ -1918,6 +2312,8 @@ Allows an SA to access the IMS SA. ...@@ -1918,6 +2312,8 @@ Allows an SA to access the IMS SA.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.ACCESS_SENSING_WITH_ULTRASOUND ## ohos.permission.ACCESS_SENSING_WITH_ULTRASOUND
Allows an application to use ultrasonic sensing. Allows an application to use ultrasonic sensing.
...@@ -1928,9 +2324,11 @@ Allows an application to use ultrasonic sensing. ...@@ -1928,9 +2324,11 @@ Allows an application to use ultrasonic sensing.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.INSTALL_ENTERPRISE_BUNDLE ## ohos.permission.INSTALL_ENTERPRISE_BUNDLE
Allows an application to install and uninstall enterprise InHouse applications. Allows an application to install enterprise InHouse applications.
**Permission level**: system_core **Permission level**: system_core
...@@ -1938,6 +2336,8 @@ Allows an application to install and uninstall enterprise InHouse applications. ...@@ -1938,6 +2336,8 @@ Allows an application to install and uninstall enterprise InHouse applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.PROXY_AUTHORIZATION_URI ## ohos.permission.PROXY_AUTHORIZATION_URI
Allows the application proxy to authorize the URI. Allows the application proxy to authorize the URI.
...@@ -1948,6 +2348,8 @@ Allows the application proxy to authorize the URI. ...@@ -1948,6 +2348,8 @@ Allows the application proxy to authorize the URI.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.GET_INSTALLED_BUNDLE_LIST ## ohos.permission.GET_INSTALLED_BUNDLE_LIST
Allows an application to obtain the list of installed applications. Allows an application to obtain the list of installed applications.
...@@ -1958,6 +2360,8 @@ Allows an application to obtain the list of installed applications. ...@@ -1958,6 +2360,8 @@ Allows an application to obtain the list of installed applications.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS ## ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS
Allows an application to manage distributed account information. Allows an application to manage distributed account information.
...@@ -1968,6 +2372,8 @@ Allows an application to manage distributed account information. ...@@ -1968,6 +2372,8 @@ Allows an application to manage distributed account information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.GET_DISTRIBUTED_ACCOUNTS ## ohos.permission.GET_DISTRIBUTED_ACCOUNTS
Allows an application to obtain distributed account information. Allows an application to obtain distributed account information.
...@@ -1978,6 +2384,8 @@ Allows an application to obtain distributed account information. ...@@ -1978,6 +2384,8 @@ Allows an application to obtain distributed account information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.GET_LOCAL_ACCOUNTS ## ohos.permission.GET_LOCAL_ACCOUNTS
Allows an application to obtain local account information. Allows an application to obtain local account information.
...@@ -1988,6 +2396,8 @@ Allows an application to obtain local account information. ...@@ -1988,6 +2396,8 @@ Allows an application to obtain local account information.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.READ_HIVIEW_SYSTEM ## ohos.permission.READ_HIVIEW_SYSTEM
Allows an application to access HiView data. Allows an application to access HiView data.
...@@ -1998,6 +2408,8 @@ Allows an application to access HiView data. ...@@ -1998,6 +2408,8 @@ Allows an application to access HiView data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.WRITE_HIVIEW_SYSTEM ## ohos.permission.WRITE_HIVIEW_SYSTEM
Allows an application to modify HiView data. Allows an application to modify HiView data.
...@@ -2008,6 +2420,8 @@ Allows an application to modify HiView data. ...@@ -2008,6 +2420,8 @@ Allows an application to modify HiView data.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ACCESS_CAST_ENGINE_MIRROR ## ohos.permission.ACCESS_CAST_ENGINE_MIRROR
Allows an application to use the mirror projection capability. Allows an application to use the mirror projection capability.
...@@ -2018,6 +2432,8 @@ Allows an application to use the mirror projection capability. ...@@ -2018,6 +2432,8 @@ Allows an application to use the mirror projection capability.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.ACCESS_CAST_ENGINE_STREAM ## ohos.permission.ACCESS_CAST_ENGINE_STREAM
Allows an application to invoke the system resource projection capability. Allows an application to invoke the system resource projection capability.
...@@ -2028,6 +2444,8 @@ Allows an application to invoke the system resource projection capability. ...@@ -2028,6 +2444,8 @@ Allows an application to invoke the system resource projection capability.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.CLOUDDATA_CONFIG ## ohos.permission.CLOUDDATA_CONFIG
Allows an application to obtain the device-cloud information of the configuration database. Allows an application to obtain the device-cloud information of the configuration database.
...@@ -2038,6 +2456,8 @@ Allows an application to obtain the device-cloud information of the configuratio ...@@ -2038,6 +2456,8 @@ Allows an application to obtain the device-cloud information of the configuratio
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.MANAGE_SENSOR ## ohos.permission.MANAGE_SENSOR
Allows an application that cannot directly use the sensor to turn on and off the sensor. Allows an application that cannot directly use the sensor to turn on and off the sensor.
...@@ -2048,6 +2468,8 @@ Allows an application that cannot directly use the sensor to turn on and off the ...@@ -2048,6 +2468,8 @@ Allows an application that cannot directly use the sensor to turn on and off the
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.DEVICE_STANDBY_EXEMPTION ## ohos.permission.DEVICE_STANDBY_EXEMPTION
Allows an application to use resources when the system is in standby mode. Allows an application to use resources when the system is in standby mode.
...@@ -2058,6 +2480,8 @@ Allows an application to use resources when the system is in standby mode. ...@@ -2058,6 +2480,8 @@ Allows an application to use resources when the system is in standby mode.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.RESTRICT_APPLICATION_ACTIVE ## ohos.permission.RESTRICT_APPLICATION_ACTIVE
Allows a standby component to publish a customized network limit event. Allows a standby component to publish a customized network limit event.
...@@ -2068,6 +2492,8 @@ Allows a standby component to publish a customized network limit event. ...@@ -2068,6 +2492,8 @@ Allows a standby component to publish a customized network limit event.
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.UPLOAD_SESSION_MANAGER ## ohos.permission.UPLOAD_SESSION_MANAGER
Allows an application to manage the upload sessions. Allows an application to manage the upload sessions.
...@@ -2078,6 +2504,8 @@ Allows an application to manage the upload sessions. ...@@ -2078,6 +2504,8 @@ Allows an application to manage the upload sessions.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.PREPARE_APP_TERMINATE ## ohos.permission.PREPARE_APP_TERMINATE
Allows an application to perform customized pre-termination actions before being terminated. Allows an application to perform customized pre-termination actions before being terminated.
...@@ -2088,6 +2516,8 @@ Allows an application to perform customized pre-termination actions before being ...@@ -2088,6 +2516,8 @@ Allows an application to perform customized pre-termination actions before being
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.MANAGE_ECOLOGICAL_RULE ## ohos.permission.MANAGE_ECOLOGICAL_RULE
Allows the rules for generating the scene code and the matching experience to be set for the manager service. Allows the rules for generating the scene code and the matching experience to be set for the manager service.
...@@ -2098,6 +2528,8 @@ Allows the rules for generating the scene code and the matching experience to be ...@@ -2098,6 +2528,8 @@ Allows the rules for generating the scene code and the matching experience to be
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.GET_SCENE_CODE ## ohos.permission.GET_SCENE_CODE
Allows an application to obtain the scene code of the specified application. Allows an application to obtain the scene code of the specified application.
...@@ -2108,6 +2540,8 @@ Allows an application to obtain the scene code of the specified application. ...@@ -2108,6 +2540,8 @@ Allows an application to obtain the scene code of the specified application.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.FILE_GUARD_MANAGER ## ohos.permission.FILE_GUARD_MANAGER
Allows an application to scan user directories and set file extended properties. Allows an application to scan user directories and set file extended properties.
...@@ -2118,6 +2552,8 @@ Allows an application to scan user directories and set file extended properties. ...@@ -2118,6 +2552,8 @@ Allows an application to scan user directories and set file extended properties.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.SET_FILE_GUARD_POLICY ## ohos.permission.SET_FILE_GUARD_POLICY
Allows an application to update the file guard policy. Allows an application to update the file guard policy.
...@@ -2128,6 +2564,8 @@ Allows an application to update the file guard policy. ...@@ -2128,6 +2564,8 @@ Allows an application to update the file guard policy.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.securityguard.SET_MODEL_STATE ## ohos.permission.securityguard.SET_MODEL_STATE
Allows an application to control the SecurityGuard model switch. Allows an application to control the SecurityGuard model switch.
...@@ -2138,6 +2576,8 @@ Allows an application to control the SecurityGuard model switch. ...@@ -2138,6 +2576,8 @@ Allows an application to control the SecurityGuard model switch.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.hsdr.HSDR_ACCESS ## ohos.permission.hsdr.HSDR_ACCESS
Allows an application to access OpenHarmony Security Detection and Response Framework. Allows an application to access OpenHarmony Security Detection and Response Framework.
...@@ -2148,6 +2588,8 @@ Allows an application to access OpenHarmony Security Detection and Response Fram ...@@ -2148,6 +2588,8 @@ Allows an application to access OpenHarmony Security Detection and Response Fram
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.SUPPORT_USER_AUTH ## ohos.permission.SUPPORT_USER_AUTH
Allows an application to interact with the user authentication framework and register ExtensionAbilities. Allows an application to interact with the user authentication framework and register ExtensionAbilities.
...@@ -2158,6 +2600,8 @@ Allows an application to interact with the user authentication framework and reg ...@@ -2158,6 +2600,8 @@ Allows an application to interact with the user authentication framework and reg
**Enable ACL**: FALSE **Enable ACL**: FALSE
**Start version**: 10
## ohos.permission.ACCESS_BUNDLE_DIR ## ohos.permission.ACCESS_BUNDLE_DIR
Allows an application to access the installation directory of another application. Allows an application to access the installation directory of another application.
...@@ -2168,6 +2612,8 @@ Allows an application to access the installation directory of another applicatio ...@@ -2168,6 +2612,8 @@ Allows an application to access the installation directory of another applicatio
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 9
## ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO ## ohos.permission.CAPTURE_VOICE_DOWNLINK_AUDIO
Allows an application to capture the downlink voice audio. Allows an application to capture the downlink voice audio.
...@@ -2178,6 +2624,8 @@ Allows an application to capture the downlink voice audio. ...@@ -2178,6 +2624,8 @@ Allows an application to capture the downlink voice audio.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.MANAGE_INTELLIGENT_VOICE ## ohos.permission.MANAGE_INTELLIGENT_VOICE
Allows an application to access the intelligent voice service interfaces. Allows an application to access the intelligent voice service interfaces.
...@@ -2198,6 +2646,8 @@ Allows an enterprise MDM bundle to be installed on enterprise devices. ...@@ -2198,6 +2646,8 @@ Allows an enterprise MDM bundle to be installed on enterprise devices.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE ## ohos.permission.INSTALL_ENTERPRISE_NORMAL_BUNDLE
Allows an enterprise Normal bundle to be installed on enterprise devices. Allows an enterprise Normal bundle to be installed on enterprise devices.
...@@ -2208,6 +2658,8 @@ Allows an enterprise Normal bundle to be installed on enterprise devices. ...@@ -2208,6 +2658,8 @@ Allows an enterprise Normal bundle to be installed on enterprise devices.
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.INSTALL_SELF_BUNDLE ## ohos.permission.INSTALL_SELF_BUNDLE
Allows automatic updates of the enterprise MDM applications on enterprise devices. Allows automatic updates of the enterprise MDM applications on enterprise devices.
...@@ -2217,3 +2669,17 @@ Allows automatic updates of the enterprise MDM applications on enterprise device ...@@ -2217,3 +2669,17 @@ Allows automatic updates of the enterprise MDM applications on enterprise device
**Authorization mode**: system_grant **Authorization mode**: system_grant
**Enable via ACL**: TRUE **Enable via ACL**: TRUE
**Start version**: 10
## ohos.permission.OBSERVE_FORM_RUNNING
Allows an application to listen for the card running status.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable via ACL**: TRUE
**Start version**: 10
# Background Task Management # Background Task Management
- Background Task - [Background Task Overview](background-task-overview.md)
- [Background Task Management Overview](background-task-overview.md) - [Transient Task](transient-task.md)
- [Transient Task Development](transient-task-dev-guide.md) - [Continuous Task](continuous-task.md)
- [Continuous Task Development](continuous-task-dev-guide.md) - [Deferred Task](work-scheduler.md)
- [Work Scheduler Development](work-scheduler-dev-guide.md) - [Agent-powered Reminder](agent-powered-reminder.md)
- [WorkSchedulerExtensionAbility Development](workscheduler-extensionability.md) - [Requesting Efficiency Resources (for Privileged System Applications Only)](efficiency-resource-request.md)
- [Efficiency Resource Request Development](efficiency-resources-apply-dev-guide.md)
- Agent-Powered Reminder
- [Agent-Powered Reminder Overview](reminder-agent-overview.md)
- [Agent-Powered Reminder Development](reminder-agent-development.md)
\ No newline at end of file
# Agent-Powered Reminder Development # Agent-powered Reminder
## Overview
### Introduction
After an application switches to the background or an application process is terminated, it may have scheduled tasks for reminding users, for example, flash sale reminders for shopping applications. To meet this requirement, the system provides agent-powered reminders (implemented by **reminderAgentManager**). When the application switches to the background or the process is terminated, the system sends reminders on behalf of the application. Currently, the following reminder types are supported: timer, calendar, and alarm.
- Timer: reminders based on countdown timers
- Calendar: reminders based on calendar events
- Alarm: reminders based on alarm clocks
### Constraints
- **Quantity limit**: A third-party application supports a maximum of 30 valid reminders. A system application supports a maximum of 10,000 valid reminders. The entire system supports a maximum of 12,000 valid reminders. (A reminder is considered valid as long as it is published.)
- **Redirection limit**: The application that is redirected to upon a click on the notification must be the application that requested the agent-powered reminder.
## Available APIs ## Available APIs
The agent-powered reminder feature provides APIs for publishing background reminders. You can call these APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. The APIs are encapsulated in the [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md) class. The table below uses promise as an example to describe the APIs used for developing agent-powered reminders. For details about more APIs and their usage, see [reminderAgentManager](../reference/apis/js-apis-reminderAgentManager.md).
**Table 1** Major APIs in reminderAgentManager **Table 1** Main APIs for agent-powered reminders
| API | Description | | API| Description|
| ---------------------------------------- | ---------------------------------------- | | -------- | -------- |
| publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback&lt;number&gt;): void<br>publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application<br>and 2000 for the entire system.| | publishReminder(reminderReq: ReminderRequest): Promise&lt;number&gt; | Publishes a reminder.|
| cancelReminder(reminderId: number, callback: AsyncCallback&lt;void&gt;): void<br>cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.)| | cancelReminder(reminderId: number): Promise&lt;void&gt; | Cancels a reminder.|
| getValidReminders(callback: AsyncCallback&lt;Array&lt;ReminderRequest&gt;&gt;): void<br>getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application. | | getValidReminders(): Promise&lt;Array&lt;ReminderRequest&gt;&gt; | Obtains all valid reminders set by the current application.|
| cancelAllReminders(callback: AsyncCallback&lt;void&gt;): void<br>cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application. | | cancelAllReminders(): Promise&lt;void&gt; | Cancels all reminders set by the current application.|
| addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback&lt;void&gt;): void<br>addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Registers a **NotificationSlot** instance to be used by the reminder. | | addNotificationSlot(slot: NotificationSlot): Promise&lt;void&gt; | Adds a notification slot.|
| removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback&lt;void&gt;): void<br>removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a **NotificationSlot** instance of a specified type. | | removeNotificationSlot(slotType: notification.SlotType): Promise&lt;void&gt; | Removes a notification slot.|
## How to Develop ## How to Develop
1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). 1. Request the **ohos.permission.PUBLISH_AGENT_REMINDER** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. [Enable the notification feature](../notification/notification-enable.md). 2. [Enable the notification feature](../notification/notification-enable.md). Agent-powered reminders can be used only after being authorized by the user.
3. Import the modules. 3. Import the modules.
```js ```js
import reminderAgentManager from '@ohos.reminderAgentManager'; import reminderAgentManager from '@ohos.reminderAgentManager';
import notificationManager from '@ohos.notificationManager'; import notificationManager from '@ohos.notificationManager';
``` ```
4. Define a reminder agent. You can define the following types of reminder agents based on project requirements. 4. Define a reminder. You can define the following types of reminders based on project requirements.
- Countdown timer
- Timer
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = { let targetReminderAgent: reminderAgentManager.ReminderRequestTimer = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is countdown timer. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, // The reminder type is timer.
triggerTimeInSeconds: 10, triggerTimeInSeconds: 10,
actionButton: [ // Set the button type and title displayed for the reminder in the notification panel. actionButton: [ // Set the button type and title displayed for the reminder in the notification panel.
{ {
...@@ -43,11 +62,11 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -43,11 +62,11 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
} }
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: {// Information about the target ability that is automatically started when the specified reminder time arrives is displayed in full screen. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
...@@ -58,15 +77,16 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -58,15 +77,16 @@ The agent-powered reminder feature provides APIs for publishing background remin
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
} }
``` ```
- Calendar event
- Calendar
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = { let targetReminderAgent: reminderAgentManager.ReminderRequestCalendar = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar event. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR, // The reminder type is calendar.
dateTime: { // Reminder time. dateTime: { // Reminder time.
year: 2023, year: 2023,
month: 7, month: 1,
day: 30, day: 1,
hour: 11, hour: 11,
minute: 14, minute: 14,
second: 30 second: 30
...@@ -83,17 +103,17 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -83,17 +103,17 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
}, },
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 300, // Reminder snooze interval, in seconds. timeInterval: 5, // Reminder snooze interval, in seconds.
title: 'this is title', // Reminder title. title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
...@@ -102,11 +122,12 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -102,11 +122,12 @@ The agent-powered reminder feature provides APIs for publishing background remin
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder. slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION // Type of the slot used by the reminder.
} }
``` ```
- Alarm clock
- Alarm
```js ```js
let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = { let targetReminderAgent: reminderAgentManager.ReminderRequestAlarm = {
reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm clock. reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM, // The reminder type is alarm.
hour: 23, // Hour portion of the reminder time. hour: 23, // Hour portion of the reminder time.
minute: 9, // Minute portion of the reminder time. minute: 9, // Minute portion of the reminder time.
daysOfWeek: [2], // Days of a week when the reminder repeats.. daysOfWeek: [2], // Days of a week when the reminder repeats..
...@@ -120,17 +141,17 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -120,17 +141,17 @@ The agent-powered reminder feature provides APIs for publishing background remin
type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE
}, },
], ],
wantAgent: {// Information about the target UIAbility that is displayed after the reminder notification is touched. wantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
maxScreenWantAgent: { // Information about the target UIAbility that is displayed after the reminder notification is touched. maxScreenWantAgent: { // Information about the target UIAbility that is automatically started when the specified reminder time arrives is displayed in full screen.
pkgName: 'com.example.myapplication', pkgName: 'com.example.myapplication',
abilityName: 'EntryAbility' abilityName: 'EntryAbility'
}, },
ringDuration: 5, // Ringing duration, in seconds. ringDuration: 5, // Ringing duration, in seconds.
snoozeTimes: 2, // Number of reminder snooze times. snoozeTimes: 2, // Number of reminder snooze times.
timeInterval: 300, // Reminder snooze interval, in seconds. timeInterval: 5, // Reminder snooze interval, in seconds.
title: 'this is title', // Reminder title. title: 'this is title', // Reminder title.
content: 'this is content', // Reminder content. content: 'this is content', // Reminder content.
expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires. expiredContent: 'this reminder has expired', // Content to be displayed after the reminder expires.
...@@ -140,38 +161,33 @@ The agent-powered reminder feature provides APIs for publishing background remin ...@@ -140,38 +161,33 @@ The agent-powered reminder feature provides APIs for publishing background remin
} }
``` ```
5. Publish the reminder agent. After the agent is published, your application can use the agent-powered reminder feature. 5. Publish the reminder. After the reminder is published, your application can use the agent-powered reminder feature.
```js ```js
try { try {
reminderAgentManager.publishReminder(targetReminderAgent).then(res => { reminderAgentManager.publishReminder(targetReminderAgent).then(res => {
console.info('publishReminder promise reminderId: ' + res); console.info('Succeeded in publishing reminder. ');
let reminderId: number = res; let reminderId: number = res; // ID of the published reminder.
// ...
}).catch(err => { }).catch(err => {
console.info('publishReminder err code: ' + err.code + ' message:' + err.message); console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
}) })
} catch (error) { } catch (err) {
console.info('publishReminder code: ' + error.code + ' message:' + error.message); console.error(`Failed to publish reminder. Code: ${err.code}, message: ${err.message}`);
} }
``` ```
The following figure shows the running effect of an alarm clock. 6. Delete the reminder as required.
![en-us_image_0000001416585578](figures/en-us_image_0000001416585578.png)
6. To delete a reminder task, call [reminderAgentManager.cancelReminder()](../reference/apis/js-apis-reminderAgentManager.md#reminderagentmanagercancelreminder).
```js
let reminderId = 0; // The reminderId is obtained from the callback after the agent is published.
```js
try { try {
// The reminder ID is obtained from the callback after the reminder is published.
reminderAgentManager.cancelReminder(reminderId).then(() => { reminderAgentManager.cancelReminder(reminderId).then(() => {
console.log("cancelReminder promise"); console.log('Succeeded in canceling reminder.');
}).catch(err => { }).catch(err => {
console.log("promise err code: " + err.code + ", message:" + err.message); console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`);
}); });
} catch (error) { } catch (err) {
console.log("cancelReminder code: " + error.code + ", message: " + error.message); console.error(`Failed to cancel reminder. Code: ${err.code}, message: ${err.message}`);
}; }
``` ```
# Background Task Management Overview # Background Task Overview
Frequent activities of background applications cause user devices to consume power quickly and respond slowly. To meet performance and power consumption requirements, the system allows applications in the background to execute only activities within the specifications. Activities beyond the specifications are suspended by default, and resources allocated to them will be reclaimed when the available resources are insufficient.
If an application or a service module running in the background has a service to continue, it can request a [transient task](#transient-tasks) to delay the suspension or a [continuous task](#continuous-tasks) to prevent the suspension. If an application needs to execute a non-real-time task when running in the background, it can request a [Work Scheduler task](#work-scheduler-tasks). A privileged application can also request [efficiency resources](#efficiency-resources) for more flexibility.
**Resource usage constraints**: The system provides resource quotas for running services, including the memory usage and CPU usage in a continuous period of time, as well as disk write I/O volume in 24 hours. When the quota is reached, the system generates a warning-level log if the process is running in the foreground, and terminates the process if it is running in the background. ## Introduction
When you return to the home screen, lock the screen, or switch to another application, the current application is switched to the background. If the application continues all the activities when running in the background, the power consumption of the device may be high and the UI may freeze. To reduce the power consumption and deliver a positive user experience, the system manages the application running in the background. For example, the system can suspend the application process by stopping allocating CPU resources. It can also stop distributing [common events](../application-models/common-event-overview.md) to the application process or terminate the process.
## Background Task Types - After an application is switched to the background for a short period of time (defined by the system), the system suspends the application process.
For more targeted management of background applications, OpenHarmony classifies background tasks into the following types and provides an extended resource request mode — efficiency resources:
- **No background task required**: An application or service module does not need further processing when switched to the background.
- **Transient task**: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension.
- **Continuous task**: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
- **Work Scheduler task**: The Work Scheduler provides a mechanism for applications to execute non-real-time tasks when the system is idle. If the preset conditions are met, the tasks will be placed in the execution queue and scheduled when the system is idle.
**Efficiency resources**: If an application needs to ensure that it will not be suspended within a period of time or can normally use certain system resources when it is suspended, it can request efficiency resources, including software and hardware resources. Different types of efficiency resources come with different privileges. For example, the CPU resources enable an application or process to keep running without being suspended, and the WORK_SCHEDULER resources allow for more task execution time before the application or process is suspended.
## Selecting a Background Task
![Background Task Selection](figures/bgtask_choice.png)
## Transient Tasks
As mentioned above, applications and service modules with transient tasks have their suspension delayed so that their running is not affected by background lifecycle management within the specified time frame.
> **NOTE**
>
> Applications and service modules can request transient tasks only for temporary tasks. The time quota is 3 minutes per time and 10 minutes per day. The system allocates the time frame based on the application scenario and system status.
### Restrictions on Using Transient Tasks
Adhere to the following constraints and rules when using transient tasks:
- **When to request**: An application can request a transient task only when it is running in the foreground or before it is suspended in the background. Otherwise, the application may be suspended, resulting in request failure. By default, an application has 6–12 seconds of running time (subject to the application scenario) before it is suspended in the background.
- **Timeout**: If a suspension delay is about to time out, the system notifies the application of the timeout by using a callback. The application must then cancel the delayed suspension. Otherwise, the application will be forcibly terminated.
- **When to cancel**: The application shall proactively cancel the request when the transient task is complete, rather than waiting for a system callback. Otherwise, the time frame allowed for the application to run in the background will be affected. - After an application running in the background is accessed for a short period of time (defined by the system), the system suspends the application process.
- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). The default quota for a single day is 10 minutes, and the maximum quota for each request is 3 minutes. After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) - In case of resource insufficiency, the system terminates some application processes (by reclaiming all resources of these processes).
## Continuous Tasks To ensure the normal use of features such as music playback and calendar reminders in the background, the system provides constrained background tasks to extend the running time of applications in the background.
Continuous tasks provide background running lifecycle support for services that can be directly perceived by users and need to run in the background. For example, if a service needs to play audio or continue with navigation and positioning in the background, which can be perceived by users, it can execute a continuous task in the respective background mode. ## Background Task Types
### Background Mode Classification
OpenHarmony provides 9 background modes for services that require continuous task execution.
**Table 1** Background modes for continuous tasks
| Background Mode | Description | Hint in Notification Panel | Remarks |
| --------------------- | ------------------------- | ------------ | ------------------------- |
| dataTransfer | Data transfer through the network or peer device, such as download, backup, share, and transfer| A data transfer task is running. | - |
| audioPlayback | Audio output | An audio playback task is running. | - |
| audioRecording | Audio input | A recording task is running. | - |
| location | Positioning and navigation | A positioning task is running. | - |
| bluetoothInteraction | Bluetooth transmission | A Bluetooth-related task is running. | - |
| multiDeviceConnection | Multi-device application collaboration | A distributed task is running. | - |
| wifiInteraction | WLAN transmission | A WLAN-related task is running.| System API, which is available only to system applications|
| voip | Voice and video calls over VoIP | A call-related task is running. | System API, which is available only to system applications|
| taskKeeping | Computing task | A computing task is running | Effective only for specific devices |
### Restrictions on Using Continuous Tasks
- If a user triggers a perceivable task, such as broadcasting and navigation, the corresponding background mode is triggered. When the task is started, the system forcibly displays a notification to the user.
- If the task is complete, the application should exit the background mode. If the system detects that an application is not using the resources in the corresponding background mode when the application is running in the background, the application is suspended.
- Ensure that the requested continuous task background mode matches the application type. If the background mode does not match the application type, the system will suspend the task once it detects the issue.
- If a requested continuous task is not actually executed, the system will suspend the task once it detects the issue.
- An ability can request only one continuous task at a time. If an application has multiple abilities, you can request a continuous task for each ability.
## Work Scheduler Tasks
The Work Scheduler provides a mechanism for an application to execute a non-real-time task, for example, data learning, when the system is idle. The system places the Work Scheduler tasks requested by applications in a queue and determines the optimal scheduling time of each task based on the storage space, power consumption, temperature, and more. Persistence is supported. This means that a requested Work Scheduler task can be triggered when the application exits or the device restarts.
### Restrictions on Using Work Scheduler Tasks
The use of the Work Scheduler must comply with the following restrictions and rules:
- **Timeout**: The Work Scheduler callback can run only within the specified period of time. After the timeout, the callback automatically stops. The default timeout duration is 2 minutes. System applications can request [efficiency resources](efficiency-resources-apply-dev-guide.md) to obtain a longer duration (20 minutes in the charging state and 10 minutes in the non-charging state).
- **Execution frequency**: The system controls the execution frequency of Work Scheduler tasks based on the activity level of their respective applications. If an application has applied for the WORK_SCHEDULER resources through the efficiency resource API, the execution frequency is not limited within the validity period of the resources.
| Application Group | Work Scheduler Task Execution Frequency|
| ---------------------------------------- | ---------- |
| Active | At a minimum interval of 2 hours |
| Used every day | At a minimum interval of 4 hours |
| Frequently used | At a minimum interval of 24 hours |
| Infrequently used | At a minimum interval of 48 hours |
| Restricted | Prohibited |
| Unused | Prohibited |
| [Exemption group for efficiency resources](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#resourcetype)| Unlimited |
- **WorkInfo setting**
- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the name of the current application. Otherwise, the verification will fail.
- At least one condition must be set.
- The repeat interval must be at least 20 minutes and must work with the Always repeat pattern or repeat times. For standard-system devices, OpenHarmony provides the following types of constrained background tasks: transient tasks, continuous tasks, deferred tasks, agent-powered reminders, and efficiency resources.
- The carried parameters can be of the number, string, or boolean type. You can select a proper background task type to ensure that your application can continue running after switching to the background.
## Efficiency Resources - **Transient tasks**: suitable for tasks that have high requirements on real-time performance and can be completed in a short period of time, for example, status saving.
Efficiency resources are classified into software (WORK_SCHEDULER, COMMON_EVENT, and TIMER) and hardware resources (CPU, GPS, BLUETOOTH, and AUDIO). - **Continuous tasks**: suitable for tasks that need to run in the background for a long time and can be perceived by users, such as music playback in the background, navigation, and device connection. Using continuous tasks to prevent application processes from being suspended.
An application can perform different operations based on the requested efficiency resources. - **Deferred tasks**: suitable for tasks that do not have high requirements on real-time performance and can be executed at a later time. The system enqueues these tasks and schedules them in a unified manner based on the memory and power consumption.
* With the CPU resources, the application or process will not be suspended.
* With the WORK_SCHEDULER resources, the application has more time to execute a task and is not restricted by the execution frequency.
* With the COMMON_EVENT resources, the application can still receive common events when it is suspended in the background.
* With the TIMER resources, the application can use the timer to execute precise scheduled tasks.
* With the GPS, BLUETOOTH, and AUDIO resources, the application can still be woken up by related services to execute tasks when it is suspended in the background.
- **Agent-powered reminders**: After an application is switched to the background or an application process is terminated, the system sends a reminder on behalf of the application. You can create scheduled reminders for countdown timers, calendar events, and alarm clocks.
**Table 2** Efficiency resource types For system applications that provide basic capabilities, the system provides an API for [requesting energy resources](efficiency-resource-request.md). After an application calls the API, the system exempts the application from management.
| Name | Value | Description | **Figure 1** Selecting a type of background task
| -------------- | ---- | ------------------- | ![bgtask_choice](figures/bgtask_choice.png)
| CPU | 1 | CPU resources, which prevent the application from being suspended. |
| COMMON_EVENT | 2 | COMMON_EVENT resources, which prevent common events from being proxied when the application is suspended. |
| TIMER | 4 | TIMER resources, which prevent timers from being proxied when the application is suspended. |
| WORK_SCHEDULER | 8 | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. |
| BLUETOOTH | 16 | BLUETOOTH resources, which prevent Bluetooth resources from being proxied when the application is suspended. |
| GPS | 32 | GPS resources, which prevent GPS resources from being proxied when the application is suspended.|
| AUDIO | 64 | AUDIO resources, which prevent audio resources from being proxied when the application is suspended. |
### Restrictions on Using Efficiency Resources
- Applications or processes are responsible for requesting and releasing efficiency resources. A process can release the resources requested by itself, whereas an application can release the resources requested by both itself and its processes. For example, an application requests CPU resources, and its process requests CPU and WORK_SCHEDULER resources. If the application initiates CPU resource release, the CPU resources requested by the process are also released. However, the WORK_SCHEDULER resources are not released. If the process initiates CPU resource release, the CPU resources requested by the application are retained until being released by the application. > **NOTE**
- If persistent resources and non-persistent resources of the same type are requested, the persistent resources overwrite the non-persistent resources and they will not be released upon a timeout. For example, if an application first requests 10-second CPU resources and then requests persistent CPU resources at the 5th second, the CPU resources become persistent and will not be released at the tenth second. If the application releases the CPU resources at the 8th second, both types of CPU resources are released. >
- The WORK_SCHEDULER resources can be requested and released by applications, but not by processes. > 1. The system supports only constrained background tasks. If an application does not use a constrained background task or selects an inappropriate type of background task after switching to the background, its process will be suspended or terminated.
- To use efficiency resources, an application must be a system application that submits a request to the application center to configure the corresponding privileges. >
> 2. For an application that requests a constrained background task, only the priority of reclaiming the application process is increased. If system resources are severely insufficient, the application process may still be terminated.
# Continuous Task Development
## When to Use
If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, device connection, and VoIP.
There is no time limit for a continuous task running in the background. To prevent abuse, the system limits the number of continuous tasks that can be requested. It also attaches a notification to each of the tasks so that the tasks are perceivable. In addition, the system verifies whether the application is actually executing a continuous task.
## Available APIs
**Table 1** Main APIs for continuous tasks
| API | Description |
| ---------------------------------------- | ---------------------------- |
| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise&lt;void&gt; | Requests a continuous task from the system so that the application keeps running in the background.|
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels the continuous task. |
For details about **wantAgent**, see [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
**Table 2** Background modes
| Name | Description | Item |
| ----------------------- | -------------- | --------------------- |
| DATA_TRANSFER | Data transfer. | dataTransfer |
| AUDIO_PLAYBACK | Audio playback. | audioPlayback |
| AUDIO_RECORDING | Audio recording. | audioRecording |
| LOCATION | Positioning and navigation. | location |
| BLUETOOTH_INTERACTION | Bluetooth-related task. | bluetoothInteraction |
| MULTI_DEVICE_CONNECTION | Multi-device connection. | multiDeviceConnection |
| WIFI_INTERACTION | WLAN-related task (reserved). | wifiInteraction |
| VOIP | Voice and video call (reserved). | voip |
| TASK_KEEPING | Computing task (for specific devices only).| taskKeeping |
## How to Develop
### Development in the Stage Model
For details about the stage model, see [Stage Model Development Overview](../application-models/stage-model-development-overview.md).
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **module.json5** file, and declare the corresponding background mode type for the ability that needs to use the task.
```
"module": {
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
}
],
"requestPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. If an application needs to execute a continuous task for its own, include the execution logic in the Page ability. This is because an application cannot use **startAbilityByCall** to create and run its own ability in the background due to the restriction of ability startup controls. For details, see [UIAbility Component Overview](../application-models/uiability-overview.md).
```ts
import wantAgent from '@ohos.app.ability.wantAgent';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
@Entry
@Component
struct Index {
@State message: string = 'test'
// Use getContext to obtain the context of the Page ability.
private context: any = getContext(this)
startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
build() {
Row() {
Column() {
Text("Index")
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() { Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule)
.margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40)
.onClick(() => {
// Request a continuous task by clicking a button.
this.startContinuousTask();
// Execute the continuous task logic, for example, music playback.
})
Button() {Text('Cancel continuous task') .fontSize(25).fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule)
.margin({ top: 10 }).backgroundColor('#0D9FFB').width(250).height(40)
.onClick(() => {
// Stop the continuous task.
// Cancel the continuous task by clicking a button.
this.stopContinuousTask();
})
}
.width('100%')
}
.height('100%')
}
}
```
3. If a continuous task needs to be executed in the background for another application or on another device, you can create and run an ability in the background in Call mode. For details, see [Using Ability Call (Intra-Device)](../application-models/uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only) and [Using Ability Call (Inter-Device)](../application-models/hop-multi-device-collaboration.md#using-cross-device-call).
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
const MSG_SEND_METHOD: string = 'CallSendMsg';
let mContext = null;
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((error) => {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
class MyParcelable {
num: number = 0;
str: String = "";
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MyParcelable(0, "")
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// You can execute different methods based on the str value in the sequenceable data sent by the caller.
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new MyParcelable(10, "Callee test");
}
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on("test", sendMsgCallback);
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) {
console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
mContext = this.context;
}
onDestroy() {
console.info("[Demo] BgTaskAbility onDestroy")
}
onWindowStageCreate(windowStage) {
console.info("[Demo] BgTaskAbility onWindowStageCreate")
windowStage.loadContent("pages/index").then((data)=> {
console.info(`load content succeed with data ${JSON.stringify(data)}`)
}).catch((error)=>{
console.error(`load content failed with error ${JSON.stringify(error)}`)
})
}
onWindowStageDestroy() {
console.info("[Demo] BgTaskAbility onWindowStageDestroy")
}
onForeground() {
console.info("[Demo] BgTaskAbility onForeground")
}
onBackground() {
console.info("[Demo] BgTaskAbility onBackground")
}
};
```
### Development in the FA Model
For details about how to use the ServiceAbility in the FA model, see [ServiceAbility Component Overview](../application-models/serviceability-overview.md).
If an application does not need to interact with a continuous task in the background, you can use **startAbility()** to start the ServiceAbility. In the **onStart** callback of the ServiceAbility, call **startBackgroundRunning()** to declare that the ServiceAbility needs to run in the background for a long time. After the task execution is complete, call **stopBackgroundRunning()** to release resources.
If an application needs to interact with a continuous task in the background (for example, an application related to music playback), you can use **connectAbility()** to start and connect to the ServiceAbility. After obtaining the proxy of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
1. Configure the continuous task permission **ohos.permission.KEEP_BACKGROUND_RUNNING** in the **config.json** file, and declare the corresponding background mode type for the ServiceAbility that needs to use the task.
```json
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"dataTransfer",
"location"
], // Background mode
"type": "service" // The ability type is Service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
2. Call the APIs for requesting and canceling a continuous task in the ServiceAbility.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "EntryAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
try {
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => {
console.info("Operation startBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation startBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation startBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
});
} catch (error) {
console.error(`Operation getWantAgent failed. code is ${error.code} message is ${error.message}`);
}
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info("Operation stopBackgroundRunning succeeded");
}).catch((err) => {
console.error("Operation stopBackgroundRunning failed Cause: " + err);
});
} catch (error) {
console.error(`Operation stopBackgroundRunning failed. code is ${error.code} message is ${error.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// The meaning of code is user-defined.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart() {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, startId) {
console.info('ServiceAbility onCommand');
}
};
```
\ No newline at end of file
# Continuous Task
## Overview
### Introduction
If an application has a perceivable task that needs to run in an extended period of time in the background, it can request a continuous task to prevent itself from being suspended. Examples of continuous tasks include music playback and navigation in the background.
After an application requests a continuous task, the system verifies whether the application is actually executing the continuous task. It also attaches a notification to the continuous task. If the user deletes the notification, the system automatically stops the task.
### Use Cases
The table below lists the types of continuous tasks, which are used in various scenarios. You can select a task type suitable for your case based on the description.
**Table 1** Continuous task types
| Name| Description| Example Scenario|
| -------- | -------- | -------- |
| DATA_TRANSFER | Data transfer| The browser downloads a large file in the background.|
| AUDIO_PLAYBACK | Audio playback| A music application plays music in the background.|
| AUDIO_RECORDING | Audio recording| A recorder records audio in the background.|
| LOCATION | Positioning and navigation| A navigation application provides navigation in the background.|
| BLUETOOTH_INTERACTION | Bluetooth-related task| Transfer a file through Bluetooth.|
| MULTI_DEVICE_CONNECTION | Multi-device connection| Carry out distributed service connection.|
| WIFI_INTERACTION | WLAN-related task (for system applications only)| Transfer a file over Wi-Fi.|
| VOIP | Voice and video calls (for system applications only)| Use a system chat application to make an audio call in the background.|
| TASK_KEEPING | Computing task (for specific devices only)| Run antivirus software.|
- When an application requests a continuous task of the DATA_TRANSFER type, the system increases the priority of the application process to reduce the probability of terminating the process. However, it still suspends the process. To use the upload and download feature, the application must call the [upload and download agent API](../reference/apis/js-apis-request.md) so that the system functions as the agent.
- To implement background playback, the application must request an [AV session](../media/avsession-overview.md) in addition to a continuous task of the AUDIO_PLAYBACK type.
### Constraints
- **Ability limit**: In the stage model, only the UIAbility can request continuous tasks. In the FA model, only the ServiceAbility can request continuous tasks.
- **Quantity limit**: A UIAbility (ServiceAbility in the FA model) can request only one continuous task at a time. If a UIAbility has a running continuous task, it can request another one only after the running task is finished. If an application needs to request multiple continuous tasks at the same time, it must create multiple UIAbilities. After a UIAbility requests a continuous task, all the processes of the application are not suspended.
- **Running verification**: The system performs continuous task verification. If an application requests a continuous task but does not execute the task of the requested type or finishes the task, the system performs certain control. For example, if the system detects that an application has requested a continuous task of the AUDIO_PLAYBACK type but does not play audio, the system terminates the application process.
> **NOTE**
>
> The application shall proactively cancel a continuous task when it is finished. Otherwise, the system will forcibly cancel the task. For example, when a user taps the UI to pause music playback, the application must cancel the continuous task in a timely manner. When the user taps the UI again to continue music playback, the application needs to request a continuous task.
## Available APIs
The table below uses promise as an example to describe the APIs used for developing continuous tasks. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 2** Main APIs for continuous tasks
| API| Description|
| -------- | -------- |
| startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md)): Promise&lt;void&gt; | Requests a continuous task.|
| stopBackgroundRunning(context: Context): Promise&lt;void&gt; | Cancels a continuous task.|
## How to Develop
### Stage Model
1. Request the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
2. Declare the continuous task type.
Declare the continuous task type for the target UIAbility in the **module.json5** file.
```ts
"module": {
"abilities": [
{
"backgroundModes": [
"audioRecording"
], // Background mode
}
],
...
}
```
3. Import the modules.
```ts
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import wantAgent from '@ohos.app.ability.wantAgent';
```
4. Request and cancel a continuous task.
- In the stage model, an application can request a continuous task for itself or another application either on the local device or on a remote device.
- When a continuous task is executed across devices or applications in the background, the UIAbility can be created and run in the background in call mode. For details, see [Using Call to Implement UIAbility Interaction (for System Applications Only)](../application-models/uiability-intra-device-interaction.md#using-call-to-implement-uiability-interaction-for-system-applications-only) and [Using Cross-Device Call](../application-models/hop-multi-device-collaboration.md#using-cross-device-call).
The code snippet below shows how an application requests a continuous task for itself.
```ts
@Entry
@Component
struct Index {
@State message: string = 'ContinuousTask';
// Use getContext to obtain the context of the UIAbility for the page.
private context = getContext(this);
startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(this.context,
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to start background running. Code is ${error.code} message is ${error.message}`);
}
});
}
stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(this.context).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to stop background running. Code is ${error.code} message is ${error.message}`);
}
}
build() {
Row() {
Column() {
Text("Index")
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Request continuous task').fontSize(25).fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => {
// Request a continuous task by clicking a button.
this.startContinuousTask();
// Execute the continuous task logic, for example, music playback.
})
Button() {
Text ('Cancel continuous task').fontSize (25).fontWeight (FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({ top: 10 })
.backgroundColor('#0D9FFB')
.width(250)
.height(40)
.onClick(() => {
// Stop the continuous task.
// Cancel the continuous task by clicking a button.
this.stopContinuousTask();
})
}
.width('100%')
}
.height('100%')
}
}
```
The code snippet below shows how an application requests a continuous task across devices or applications.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
const MSG_SEND_METHOD: string = 'CallSendMsg'
let mContext = null;
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility",
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(mContext,
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(mContext).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (err) {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
}
class MyParcelable {
num: number = 0;
str: String = '';
constructor(num, string) {
this.num = num;
this.str = string;
}
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MyParcelable(0, '')
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// You can execute different methods based on the str value in the sequenceable data sent by the caller object.
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new MyParcelable(10, 'Callee test');
}
export default class BgTaskAbility extends UIAbility {
onCreate(want, launchParam) {
console.info("[Demo] BgTaskAbility onCreate")
this.callee.on('test', sendMsgCallback);
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) {
console.error(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
}
mContext = this.context;
}
onDestroy() {
console.info('[Demo] BgTaskAbility onDestroy')
}
onWindowStageCreate(windowStage) {
console.info('[Demo] BgTaskAbility onWindowStageCreate')
windowStage.loadContent("pages/index").then((data) => {
console.info(`load content succeed with data ${JSON.stringify(data)}`)
}).catch((error) => {
console.error(`load content failed with error ${JSON.stringify(error)}`)
})
}
onWindowStageDestroy() {
console.info('[Demo] BgTaskAbility onWindowStageDestroy')
}
onForeground() {
console.info('[Demo] BgTaskAbility onForeground')
}
onBackground() {
console.info('[Demo] BgTaskAbility onBackground')
}
};
```
### FA Model
1. Start and connect to a ServiceAbility.
- If no user interaction is required, use **startAbility()** to start the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). In the **onStart** callback of the ServiceAbility, call the APIs to request and cancel continuous tasks.
- If user interaction is required (for example, in music playback scenarios), use **connectAbility()** to start and connect to the ServiceAbility. For details, see [ServiceAbility Component](../application-models/serviceability-overview.md). After obtaining the agent of the ServiceAbility, the application can communicate with the ServiceAbility and control the request and cancellation of continuous tasks.
2. Configure permissions and declare the continuous task type.
Configure the **ohos.permission.KEEP_BACKGROUND_RUNNING** permission in the **config.json** file. For details, see [Declaring Permissions in the Configuration File](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file). In addition, declare the continuous task type for the ServiceAbility.
```js
"module": {
"package": "com.example.myapplication",
"abilities": [
{
"backgroundModes": [
"audioRecording",
], // Background mode
"type": "service" // The ability type is Service.
}
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
```
3. Import the modules.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
import featureAbility from '@ohos.ability.featureAbility';
import wantAgent from '@ohos.app.ability.wantAgent';
import rpc from "@ohos.rpc";
```
4. Request and cancel a continuous task. In the ServiceAbility, call **startBackgroundRunning()** and **startBackgroundRunning()** to request and cancel a continuous task.
```js
function startContinuousTask() {
let wantAgentInfo = {
// List of operations to be executed after the notification is clicked.
wants: [
{
bundleName: "com.example.myapplication",
abilityName: "com.example.myapplication.MainAbility"
}
],
// Type of the operation to perform after the notification is clicked.
operationType: wantAgent.OperationType.START_ABILITY,
// Custom request code.
requestCode: 0,
// Execution attribute of the operation to perform after the notification is clicked.
wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
};
// Obtain the WantAgent object by using the getWantAgent API of the wantAgent module.
wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => {
try {
backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(),
backgroundTaskManager.BackgroundMode.AUDIO_RECORDING, wantAgentObj).then(() => {
console.info(`Succeeded in operationing startBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to operation startBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
});
}
function stopContinuousTask() {
try {
backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => {
console.info(`Succeeded in operationing stopBackgroundRunning.`);
}).catch((err) => {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
});
} catch (error) {
console.error(`Failed to operation stopBackgroundRunning. Code is ${err.code}, message is ${err.message}`);
}
}
async function processAsyncJobs() {
// Execute the continuous task.
// After the continuous task is complete, call the API to release resources.
stopContinuousTask();
}
let mMyStub;
class MyStub extends rpc.RemoteObject {
constructor(des) {
if (typeof des === 'string') {
super(des);
} else {
return null;
}
}
onRemoteRequest(code, data, reply, option) {
console.log('ServiceAbility onRemoteRequest called');
// Custom request code.
if (code === 1) {
// Receive the request code for requesting a continuous task.
startContinuousTask();
// Execute the continuous task.
} else if (code === 2) {
// Receive the request code for canceling the continuous task.
stopContinuousTask();
} else {
console.log('ServiceAbility unknown request code');
}
return true;
}
}
export default {
onStart(want) {
console.info('ServiceAbility onStart');
mMyStub = new MyStub("ServiceAbility-test");
// Call the API to start the task.
startContinuousTask();
processAsyncJobs();
},
onStop() {
console.info('ServiceAbility onStop');
},
onConnect(want) {
console.info('ServiceAbility onConnect');
return mMyStub;
},
onReconnect(want) {
console.info('ServiceAbility onReconnect');
},
onDisconnect() {
console.info('ServiceAbility onDisconnect');
},
onCommand(want, restart, startId) {
console.info('ServiceAbility onCommand');
}
};
```
# Requesting Efficiency Resources (for Privileged System Applications Only)
## Overview
### Introduction
Some system applications need to run for an extended period of time to provide basic system functions. For example, to maintain the connection between the system and server, the application that provides the default persistent connection push service must send heartbeat messages to the server at a short interval. To prevent the application process from being suspended, the application can request efficiency resources.
### Basic Concepts
- **APIs for requesting efficiency resources**: APIs used by a system application to request energy resources for its processes. An application or process can request CPU resources to prevent itself from being suspended.
- **Privileged system application**: a system application that is configured with the [runningResourcesApply privilege](../../device-dev/subsystems/subsys-app-privilege-config-guide.md#device-specific-application-privileges).
### Constraints
- Efficiency resources can be used only by privileged system applications.
- CPU resources can be requested by process or application. Other resources can be requested only by application.
## Available APIs
The table below lists the main APIs used for efficient resources. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 1** Main APIs for efficiency resources
| API| Description|
| -------- | -------- |
| applyEfficiencyResources(request:EfficiencyResourcesRequest): void | Requests efficiency resources.|
| resetAllEfficiencyResources():void | Releases all efficiency resources.|
**Table 2** Parameters for requesting efficiency resources
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| resourceTypes | number | Yes| Type of the resource to request.|
| isApply | boolean | Yes| Whether the request is used to apply for resources.<br>- **true**: The request is used to apply for resources.<br>- **false**: The request is used to release resources.|
| timeOut | number | Yes| Duration for which the resource will be used, in milliseconds.|
| isPersist | boolean | No| Whether the resource is permanently held. The default value is **false**.<br>- **true**: The resource is permanently held.<br>- **false**: The resource is held for a limited period of time.|
| isProcess | boolean | No| Whether the request is initiated by a process. The default value is **false**.<br>- **true**: The request is initiated by a process.<br>- **false**: The request is initiated by an application.|
| reason | string | Yes| Reason for requesting the resource.|
**Table 3** Efficiency resource types
| Name| Value| Description|
| -------- | -------- | -------- |
| CPU | 1 | CPU resource. Such type of resource prevents an application from being suspended.|
| COMMON_EVENT | 2 | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.|
| TIMER | 4 | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.|
| WORK_SCHEDULER | 8 | Deferred task resource. Such type of resource provides a loose control policy for an application.|
| BLUETOOTH | 16 | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.|
| GPS | 32 | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.|
| AUDIO | 64 | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.|
## How to Develop
1. Import the module.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```
2. Request efficiency resources.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// The application needs to remain active in the background.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU, // The resource type is CPU, which prevents the application process from being suspended.
isApply: true, // The request is used to apply for the resources.
timeOut: 0, // Timeout interval. Resources are automatically released when the timeout interval expires.
reason: "apply", // Reason for the request.
isPersist: true, // The resources are permanently held.
isProcess: false, // The request is initiated by an application.
};
try {
backgroundTaskManager.applyEfficiencyResources(request);
console.info("Succeeded in invoking applyEfficiencyResources.");
} catch (error) {
console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
```
3. Release the efficiency resources. After completing work in the background, the application should release the resources in a timer manner. It can release some or all resources.
```js
// The application releases all the efficiency resources.
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
console.error(`Failed to invoke resetAllEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
// The application releases some efficiency resources.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.CPU,
isApply: false, // The request is used to release resources.
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: false, // The request is initiated by an application.
};
try {
backgroundTaskManager.applyEfficiencyResources(request);
console.info("Succeeded in invoking applyEfficiencyResources.");
} catch (error) {
console.error(`Failed to invoke applyEfficiencyResources. Code is ${error.code} message is ${error.message}`);
}
```
> **NOTE**
>
> Applications can dynamically request efficiency resources. Therefore, it is recommended that the application proactively releases the resources after the task is complete so as to reduce power consumption and ensure smooth user experience.
# Efficiency Resource Request Development
## When to Use
To further balance power consumption overhead of the system, privileged system applications can be suspended in the background as other applications. To ensure normal provisioning of important functions, efficiency resource APIs are provided for these applications so that they can execute special tasks and use specific system resources in the background. For example, if they want to receive common events when suspended, they can use the APIs to request the common event resources.
To upgrade your application as a privileged application, you must evaluate your service requirements and submit a request to the application center. The application center will determine whether to accept the request based on the conditions.
## Constraints
Only system applications can request efficiency resources.
## Available APIs
**Table 1** Main APIs for efficiency resources
| API | Description |
| ---------------------------------------- | ---------- |
| applyEfficiencyResources(request: [EfficiencyResourcesRequest](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#efficiencyresourcesrequest)): boolean | Requests efficiency resources. |
| resetAllEfficiencyResources():void | Releases efficiency resources.|
## How to Develop
1. When a privileged application in the background needs to use special resources, request the target resources from the system.
2. When the task is complete, release the resources in time. You can choose whether to release some or all resources.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
// Request efficiency resources.
let request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT |
backgroundTaskManager.ResourceType.TIMER,
isApply: true,
timeOut: 0,
reason: "apply",
isPersist: true,
isProcess: true,
};
let res;
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// Release some efficiency resources.
request = {
resourceTypes: backgroundTaskManager.ResourceType.COMMON_EVENT,
isApply: false,
timeOut: 0,
reason: "reset",
isPersist: true,
isProcess: true,
};
try {
res = backgroundTaskManager.applyEfficiencyResources(request);
console.info("the result of request is: " + res);
} catch (error) {
console.error(`Operation applyEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
// Release all efficiency resources.
try {
backgroundTaskManager.resetAllEfficiencyResources();
} catch (error) {
console.error(`Operation resetAllEfficiencyResources failed. code is ${error.code} message is ${error.message}`);
}
```
\ No newline at end of file
# Agent-Powered Reminder Overview
To deliver a better user experience, OpenHarmony manages background application processes in a more orderly manner. Applications cannot reside in the background randomly, and their background behavior is strictly managed to minimize malicious behavior. However, for some applications that are running in the background or have exited, notifications may need to be sent at a specified time. For example, a shopping application wants to remind users of flash sale activities at some time points. To meet these service requirements, OpenHarmony provides the agent-powered redminder feature. After an application switches to the background or exits, their timing and pop-up notification functions are taken over by the background agent.
OpenHarmony provides the following types of background agents:
- Countdown timers: Applications can use this type to implement short-time timing notification services.
- Calendar events: Applications can use this type to implement long-time notification services.
- Alarm clocks: Applications can use this type to implement alarm-related services.
# Transient Task Development
## When to Use
By default, an application can run for a period of 6 to 12 seconds after it switches to the background. When this period expires, the application is suspended. If an application requires more time to execute an important task, it can call the **requestSuspendDelay** API to request a transient task to delay the suspension.
You are advised not to call the [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) method to apply for delayed suspension after the application is running in the background. Instead, you need to call this interface to declare the execution time of the extended application to the system before performing any time-consuming operation. It is recommended that an application calls [requestSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagerrequestsuspenddelay) when it is running in the foreground, so as not to affect the transient task quota of the application.
An application can obtain the remaining duration before being suspended by calling [getRemainingDelayTime()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagergetremainingdelaytime). Each application has a daily time quota for transient tasks. Therefore, after the time-consuming task finishes execution, the application should call [cancelSuspendDelay()](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md#backgroundtaskmanagercancelsuspenddelay) to cancel the transient task in a timely manner.
Typical time-consuming tasks include saving status data to the local database, opening and processing a large file, and synchronizing data to the cloud server.
## Available APIs
**Table 1** Main APIs for transient tasks
| API | Description |
| ---------------------------------------- | ---------------------------------------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): [DelaySuspendInfo](../reference/apis/js-apis-backgroundTaskManager.md#delaysuspendinfo)| Requests delayed suspension after the application switches to the background.<br>The default duration of delayed suspension is 3 minutes when the battery level is normal and 1 minute when the battery level is low.|
| getRemainingDelayTime(requestId: number): Promise&lt;number&gt; | Obtains the remaining duration before the application is suspended.<br>This API uses a promise to return the result. |
| cancelSuspendDelay(requestId: number): void | Cancels the suspension delay. |
## How to Develop
When an application needs to execute a time-consuming task in the background, call the API to request a transient task. After the time-consuming task finishes execution, call the API to cancel the transient task.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
let id; // ID of the suspension delay request.
let delayTime; // Remaining duration for the suspension delay request.
// Request a suspension delay.
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; // Reason for the suspension delay request.
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// The callback is invoked to notify the application that the suspension delay request is about to time out. The application needs to perform some cleanup and annotation operations and cancels the transient task.
console.info("[backgroundTaskManager] Request suspension delay will time out.");
backgroundTaskManager.cancelSuspendDelay(id);
})
id = delayInfo.requestId;
delayTime = delayInfo.actualDelayTime;
console.info("[backgroundTaskManager] The requestId is: " + id);
console.info("[backgroundTaskManager]The actualDelayTime is: " + delayTime);
} catch (error) {
console.error(`[backgroundTaskManager] requestSuspendDelay failed. code is ${error.code} message is ${error.message}`);
}
}
// Obtain the remaining duration before the application is suspended.
async function getRemainingDelayTime() {
try {
await backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.log('[backgroundTaskManager] promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch(error => {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
})
} catch (error) {
console.error(`[backgroundTaskManager] promise => Operation getRemainingDelayTime failed. code is ${error.code} message is ${error.message}`);
}
}
// Cancel the suspension delay.
function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id);
}
async function performingLongRunningTask() {
// Before executing a time-consuming task, call the API to request a transient task to delay the suspension.
requestSuspendDelay();
// If required, obtain the available time quota through the getRemainingDelayTime() API.
await getRemainingDelayTime();
if (delayTime < 0) {// If the time is less than a certain value, cancel the time-consuming task.
// Handle the scenario where the time quota is insufficient.
cancelSuspendDelay();
return;
}
// Execute the time-consuming task.
// After the time-consuming task is executed, call the API to cancel the transient task.
cancelSuspendDelay();
}
```
# Transient Task
## Overview
An application is suspended after it runs in the background for a short period of time. If the application needs to execute a short-time task in the background, for example, saving the status, it can request a transient task to extend the running time in the background.
### Constraints
- **When to request**: An application can request a transient task when it is running in the foreground or within 5 seconds after it switches to the background.
- **Quantity limit**: An application can request a maximum of three transient tasks during a time segment. As shown in the figure below, the application requests two transient tasks in the time segments ①, ②, and ③, and one transient task in the time segment ④.
- **Quota mechanism**: An application has a certain quota for transient tasks (adjusted based on the system status and user habits). The default quota for a single day (within 24 hours) is 10 minutes, and the maximum quota for each request is 3 minutes. In case of [low battery](../reference/apis/js-apis-battery-info.md), the default quota for each request is 1 minute. After the quota is used up, the application cannot request transient tasks anymore. The system also provides an API for an application to query the remaining duration of a transient task so as to determine whether to continue running other services.
- **Quota calculation**: Transient tasks are timed only when the application is running in the background. If the application has multiple transient tasks during the same time segment, no repeated timing is performed. As in the figure below, the application has two transient tasks, A and B. Task A is requested when the application is running in the foreground, and the timing starts when the application switches to the background (marked as ①). When the application switches to the foreground, the timing stops (marked as ②). When the application switches to the background again, the timing starts again (marked as ③). When task A is finished, task B still exists, and therefore the timing continues (marked as ④). In this process, the total time consumed by the transient tasks is ①+③+④.
**Figure 1** Quota calculation for transient tasks
![transient-task](figures/transient-task.png)
> **NOTE**
>
> The application shall proactively cancel a transient task when it is finished. Otherwise, the time frame allowed for the application to run in the background will be affected.
- **Timeout**: If a transient task is about to time out, the system notifies the application of the timeout by using a callback. The application needs to cancel the task. Otherwise, the system forcibly terminates the application process.
## Available APIs
The table below lists the main APIs used for transient task development. For details about more APIs and their usage, see [Background Task Management](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md).
**Table 1** Main APIs for transient tasks
| API| Description|
| -------- | -------- |
| requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspendInfo | Requests a transient task.|
| getRemainingDelayTime(requestId: number): Promise&lt;number&gt; | Obtains the remaining time of a transient task.|
| cancelSuspendDelay(requestId: number): void | Cancels a transient task.|
## How to Develop
1. Import the module.
```js
import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager';
```
2. Request a transient task and implement the callback.
```js
let id; // ID of the transient task.
let delayTime; // Remaining time of the transient task.
// Request a transient task.
function requestSuspendDelay() {
let myReason = 'test requestSuspendDelay'; // Reason for the request.
try {
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
// Callback function, which is triggered when the transient task is about to time out. The application can carry out data clear and annotation, and cancel the task in the callback.
console.info('Succeeded in requesting suspend delay.');
backgroundTaskManager.cancelSuspendDelay(id);
})
id = delayInfo.requestId;
delayTime = delayInfo.actualDelayTime;
} catch (err) {
console.error(`Failed to request suspend delay. Code: ${err.code}, message: ${err.message}`);
}
}
```
3. Obtain the remaining time of the transient task. Based on the remaining time, the application determines whether to continue to run other services. For example, the application has two small tasks. After the first task is executed, it queries the remaining time of the current transient task to determine whether to execute the second task.
```js
async function getRemainingDelayTime() {
try {
backgroundTaskManager.getRemainingDelayTime(id).then(res => {
console.info('Succeeded in getting remaining delay time.');
}).catch(err => {
console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`);
})
} catch (err) {
console.error(`Failed to get remaining delay time. Code: ${err.code}, message: ${err.message}`);
}
}
```
4. Cancel the transient task.
```js
function cancelSuspendDelay() {
backgroundTaskManager.cancelSuspendDelay(id);
}
```
# Work Scheduler Development
## When to Use
If your application needs to execute a non-real-time task or a persistent task, for example, data learning, you can harness the Work Scheduler mechanism, which will schedule the task based on the storage space, power consumption, temperature, and more when the preset conditions are met. Your application must implement the callbacks provided by [WorkSchedulerExtensionAbility](./workscheduler-extensionability.md) for Work Scheduler tasks.
For details about the restrictions, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
## Available APIs
**Table 1** Major workScheduler APIs
API | Description
---------------------------------------------------------|-----------------------------------------
startWork(work: WorkInfo): void; | Starts a Work Scheduler task.
stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a Work Scheduler task.
getWorkStatus(workId: number, callback: AsyncCallback\<WorkInfo>): void;| Obtains the status of a Work Scheduler task. This API uses an asynchronous callback to return the result.
getWorkStatus(workId: number): Promise\<WorkInfo>; | Obtains the status of a Work Scheduler task. This API uses a promise to return the result.
obtainAllWorks(callback: AsyncCallback\<void>): Array\<WorkInfo>;| Obtains all the Work Scheduler tasks. This API uses an asynchronous callback to return the result.
obtainAllWorks(): Promise<Array\<WorkInfo>>;| Obtains all the Work Scheduler tasks. This API uses a promise to return the result.
stopAndClearWorks(): void;| Stops and clears all the Work Scheduler tasks.
isLastWorkTimeOut(workId: number, callback: AsyncCallback\<void>): boolean;| Checks whether the last execution of the specified task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.
isLastWorkTimeOut(workId: number): Promise\<boolean>;| Checks whether the last execution of the specified task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.
**Table 2** WorkInfo parameters
For details about the restriction on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler](./background-task-overview.md#restrictions-on-using-work-scheduler).
Name| Type|Description
---------------------------------------------------------|-----------------------------------------|---------------------------------------------------------
workId| number | ID of the Work Scheduler task. Mandatory.
bundleName| string | Bundle name of the Work Scheduler task. Mandatory.
abilityName| string | Name of the ability to be notified by a Work Scheduler callback. Mandatory.
networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.
isCharging| boolean | Whether the device is charging.
chargerType| [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.
batteryLevel| number | Battery level.
batteryStatus| [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.
storageRequest| [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) |Storage status.
isRepeat| boolean |Whether the task is repeated.
repeatCycleTime| number |Repeat interval.
repeatCount | number|Number of repeat times.
parameters | {[key: string]: number | string | boolean} |Carried parameters.
**Table 3** Work Scheduler callbacks
API | Description
---------------------------------------------------------|-----------------------------------------
onWorkStart(work: WorkInfo): void | Called when the Work Scheduler task starts.
onWorkStop(work: WorkInfo): void | Called when the Work Scheduler task stops.
### How to Develop
1. Import the modules.
Import the **workScheduler** module.
```js
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Import the **WorkSchedulerExtensionAbility** module.
```js
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
2. Develop an ExtensionAbility to execute a Work Scheduler task. For details about the ExtensionAbility, see [ExtensionAbility Component Overview](../application-models/extensionability-overview.md) and [WorkSchedulerExtensionAbility Development](./workscheduler-extensionability.md).
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
export default class MyExtension extends WorkSchedulerExtensionAbility {
onWorkStart(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStart' + JSON.stringify(workInfo));
}
onWorkStop(workInfo) {
console.log('MyWorkSchedulerExtensionAbility onWorkStop' + JSON.stringify(workInfo));
}
}
```
3. Start a Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension",
parameters: {
mykey0: 1,
mykey1: "string value",
mykey2: true,
mykey3: 1.5
}
}
try{
workScheduler.startWork(workInfo);
console.info('workschedulerLog startWork success');
} catch (error) {
console.error(`workschedulerLog startwork failed. code is ${error.code} message is ${error.message}`);
}
```
4. Stop the Work Scheduler task.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
let workInfo = {
workId: 1,
batteryStatus:workScheduler.BatteryStatus.BATTERY_STATUS_LOW,
isRepeat: false,
isPersisted: true,
bundleName: "com.example.myapplication",
abilityName: "MyExtension",
parameters: {
mykey0: 1,
mykey1: "string value",
mykey2: true,
mykey3: 1.5
}
}
try{
workScheduler.stopWork(workInfo, false);
console.info('workschedulerLog stopWork success');
} catch (error) {
console.error(`workschedulerLog stopWork failed. code is ${error.code} message is ${error.message}`);
}
```
5. Obtain a specified Work Scheduler task.
```ts
try{
workScheduler.getWorkStatus(50, (error, res) => {
if (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
} else {
for (let item in res) {
console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`);
}
}
});
} catch (error) {
console.error(`workschedulerLog getWorkStatus failed. code is ${error.code} message is ${error.message}`);
}
```
6. Obtain all the Work Scheduler tasks.
```ts
try{
workScheduler.obtainAllWorks((error, res) =>{
if (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
} else {
console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`);
}
});
} catch (error) {
console.error(`workschedulerLog obtainAllWorks failed. code is ${error.code} message is ${error.message}`);
}
```
7. Stop and clear all the Work Scheduler tasks.
```ts
try{
workScheduler.stopAndClearWorks();
console.info(`workschedulerLog stopAndClearWorks success`);
} catch (error) {
console.error(`workschedulerLog stopAndClearWorks failed. code is ${error.code} message is ${error.message}`);
}
```
8. Check whether the last execution of a specified Work Scheduler task has timed out.
```ts
try{
workScheduler.isLastWorkTimeOut(500, (error, res) =>{
if (error) {
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
} else {
console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`);
}
});
} catch (error) {
console.error(`workschedulerLog isLastWorkTimeOut failed. code is ${error.code} message is ${error.message}`);
}
```
\ No newline at end of file
# Deferred Task
## Overview
### Introduction
If an application needs to execute a non-real-time task after switching to the background, for example, if the application wants to obtain emails irregularly when the network is available, the application can request deferred tasks. When the specified conditions (including the network type, charging type, storage status, battery status, and timing status) are met, the system adds the task to the execution queue. Then the system starts the application to execute the task based on the memory, power consumption, device temperature, and user habits.
### Working Principle
**Figure 1** Working principle of deferred task scheduling
![WorkScheduler](figures/WorkScheduler.png)
An application calls the **WorkScheduler** APIs to register, delete, and query deferred tasks. Based on the task-specific conditions (specified by **WorkInfo**, including the network type, charging type, and storage status) and system status (including the memory, power consumption, device temperature, and user habits), the WorkSchedulerService determines the time to schedule the tasks.
When the scheduling conditions are met or the task scheduling ends, the system calls back **onWorkStart()** or **onWorkStop()** in [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md). The system also creates an independent process for the **WorkSchedulerExtensionAbility** and provides a duration for the **WorkSchedulerExtensionAbility** to run. You can implement your own service logic in the callback functions.
### Constraints
- **Quantity limit**: An application can request a maximum of 10 deferred tasks during a time segment.
- **Execution frequency limit**: The system controls the execution frequency of deferred tasks based on the [application activity group](../reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md). Applications that request the WORK_SCHEDULER resource are placed in the efficiency resource exemption group.
**Table 1** Application activity groups
| Group| Deferred Task Execution Frequency|
| -------- | -------- |
| Group of active applications| At a minimum interval of 2 hours|
| Group of frequently used applications| At a minimum interval of 4 hours|
| Group of applications that are used neither frequently nor rarely| At a minimum interval of 24 hours|
| Group of rarely used applications| At a minimum interval of 48 hours|
| Group of restricted applications| Forbidden|
| Group of applications never used| Forbidden|
| Efficiency resource exemption group| No restriction|
- **Timeout**: The WorkSchedulerExtensionAbility can run for a maximum of 2 minutes for a single callback. If the application does not cancel the deferred task upon a timeout, the system forcibly terminates the process for the WorkSchedulerExtensionAbility. Privileged system applications can request the WORK_SCHEDULER resource to extend the duration to 20 minutes in the charging state and 10 minutes in the non-charging state.
- **Scheduling delay**: The system schedules deferred tasks in a unified manner based on the memory, power consumption, device temperature, and user habits. For example, when the system memory resources are insufficient or the temperature reaches a certain level, the system delays task scheduling.
- **Restrictions for WorkSchedulerExtensionAbility**: The following APIs cannot be called in the WorkSchedulerExtensionAbility:
[@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)
[@ohos.backgroundTaskManager (Background Task Management)](../reference/apis/js-apis-backgroundTaskManager.md)
[@ohos.multimedia.camera (Camera Management)](../reference/apis/js-apis-camera.md)
[@ohos.multimedia.audio (Audio Management)](../reference/apis/js-apis-audio.md)
[@ohos.multimedia.media (Media)](../reference/apis/js-apis-media.md)
## Available APIs
The table below lists the APIs used for developing deferred tasks. For details about more APIs and their usage, see [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](../reference/apis/js-apis-resourceschedule-workScheduler.md).
**Table 2** Main APIs for deferred tasks
| API| Description|
| -------- | -------- |
| startWork(work: WorkInfo): void; | Starts a deferred task.|
| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
| getWorkStatus(workId: number, callback: AsyncCallback&lt;WorkInfo&gt;): void; | Obtains the status of a deferred task. This API uses an asynchronous callback to return the result.|
| getWorkStatus(workId: number): Promise&lt;WorkInfo&gt;; | Obtains the status of a deferred task. This API uses a promise to return the result.|
| obtainAllWorks(callback: AsyncCallback&lt;void&gt;): Array&lt;WorkInfo&gt;; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.|
| obtainAllWorks(): Promise&lt;Array&lt;WorkInfo&gt;&gt;; | Obtains all the deferred tasks. This API uses a promise to return the result.|
| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.|
| isLastWorkTimeOut(workId: number, callback: AsyncCallback&lt;void&gt;): boolean; | Checks whether the last execution of a deferred task has timed out. This API uses an asynchronous callback to return the result. It is applicable to repeated tasks.|
| isLastWorkTimeOut(workId: number): Promise&lt;boolean&gt;; | Checks whether the last execution of a deferred task has timed out. This API uses a promise to return the result. It is applicable to repeated tasks.|
**Table 3** Options of WorkInfo
| Name| Type| Description.|
| -------- | -------- | -------- |
| workId | number | ID of a deferred task. This parameter is mandatory.|
| bundleName | string | Bundle name of the application that requests the deferred task.|
| abilityName | string | Name of the ability to be notified by a deferred task scheduling callback. This parameter is mandatory.|
| networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.|
| isCharging | boolean | Whether the device is charging.|
| chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.|
| batteryLevel | number | Battery level.|
| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.|
| storageRequest | [StorageRequest](../reference/apis/js-apis-resourceschedule-workScheduler.md#storagerequest) | Storage status.|
| isRepeat | boolean | Whether the deferred task is repeated.|
| repeatCycleTime | number | Repeat interval.|
| repeatCount | number | Number of repeat times.|
| parameters | [key: string]: number | Carried parameters.|
The **WorkInfo** parameter is used to set conditions for triggering task scheduling. Its setting must comply with the following rules:
- **workId**, **bundleName**, and **abilityName** are mandatory. **bundleName** must be set to the bundle name of the current application.
- The carried parameters can be of the number, string, or boolean type.
- At least one condition must be set, including the network type, charging type, storage status, battery status, and timing status.
- For repeated tasks, **repeatCycleTime** must be at least 20 minutes. When **isRepeat** is set, you must set **repeatCycleTime** or **repeatCount**.
The table below lists the APIs used for developing deferred task scheduling callbacks. For details about more APIs and their usage, see [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
**Table 4** Deferred task scheduling callbacks
| API| Description|
| -------- | -------- |
| onWorkStart(work: WorkInfo): void | Called when the system starts scheduling the deferred task.|
| onWorkStop(work: WorkInfo): void | Called when the system stops scheduling the deferred task.|
## How to Develop
The development of deferred task scheduling consists of two steps: implementing the deferred task scheduling capability and implementing deferred task scheduling.
1. **Implementing the deferred task scheduling capability**: Implement the callbacks for starting and stopping the WorkSchedulerExtensionAbility.
2. **Implementing deferred task scheduling**: Call the **WorkScheduler** APIs to start and stop delayed tasks.
### Implementing Deferred Task Scheduling Callbacks
1. Create a project directory.
In the **./entry/src/main/ets** directory of the project, create a directory and an ArkTS file. For example, create a directory and name it **extension**. In the **extension** directory, create an ArkTS file named **WorkSchedulerExtension.ets** and implement the callbacks for deferred task scheduling.
2. Import the module.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
3. Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class MyWorkSchedulerExtensionAbility extends WorkSchedulerExtensionAbility {
// Callback invoked when the system starts scheduling the deferred task.
onWorkStart(workInfo) {
console.info(`onWorkStart, workInfo = ${JSON.stringify(workInfo)}`);
}
// Callback invoked when the system stops scheduling the deferred task.
onWorkStop(workInfo) {
console.info(`onWorkStop, workInfo is ${JSON.stringify(workInfo)}`);
}
}
```
4. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) and set the tags as follows:
- Set **type** to **workScheduler**.
- Set **srcEntry** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "MyWorkSchedulerExtensionAbility",
"srcEntry": "./ets/WorkSchedulerExtension/WorkSchedulerExtension.ts",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
}
]
}
}
```
### Implementing Deferred Task Scheduling
1. Import the module.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
2. Start a deferred task.
```ts
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility'
}
try {
workScheduler.startWork(this.workInfo);
console.info(`startWork success`);
} catch (error) {
console.error(`startWork failed. code is ${error.code} message is ${error.message}`);
}
```
3. Cancel the deferred task.
```ts
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: 'com.example.application',
abilityName: 'MyWorkSchedulerExtensionAbility'
}
try {
workScheduler.stopWork(this.workInfo);
console.info(`stopWork success`);
} catch (error) {
console.error(`stopWork failed. code is ${error.code} message is ${error.message}`);
}
```
# WorkSchedulerExtensionAbility Development
If your application needs to execute a non-real-time task or a persistent task, you can harness the Work Scheduler mechanism, which will schedule the task when the preset conditions (including the network type, charging type, storage status, battery status, and timing status) are met.
**WorkSchedulerExtensionAbility** provides callbacks for Work Scheduler tasks. When a Work Scheduler task starts or stops, these callbacks are invoked to process your service logic.
## Working Principles
Figure 1 shows the working principle of Work Scheduler.
**Figure 1** Work Scheduler working principle
![WorkSchedulerExtensionAbility](figures/WorkSchedulerExtensionAbility.png)
An application starts, stops, and obtains Work Scheduler tasks through the [workScheduler APIs](../reference/apis/js-apis-resourceschedule-workScheduler.md).
The application service layer detects and determines the conditions. If the preset conditions are met, the application service layer calls back the **WorkSchedulerExtensionAbility** object to start the application and triggers the **onWorkStart** and **onWorkStop** callbacks.
## Available APIs
The **WorkSchedulerExtensionAbility** class has the following APIs. For details, see [WorkSchedulerExtensionAbility](../reference/apis/js-apis-WorkSchedulerExtensionAbility.md).
| Name| Description|
| -------- | -------- |
| onWorkStart(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task starts.|
| onWorkStop(work: workScheduler.WorkInfo): void | Called when the Work Scheduler task stops.|
## How to Develop
To create a WorkScheduler project in DevEco Studio, perform the following steps:
- [Implement callbacks for Work Scheduler](#implementing-callbacks-for-work-scheduler): Develop the callbacks provided by **WorkSchedulerExtensionAbility**.
- [Implement Work Scheduler](#implementing-work-scheduler): Develop the [workScheduler APIs] to implement functions such as starting or stopping Work Scheduler tasks.
- [Set the configuration file](#setting-the-configuration-file): Set the configuration file **module.json5**.
### Implementing Callbacks for Work Scheduler
1. Create a module named **library** in the root directory of the project, with the **Ohos Library** template selected.
2. In the **./library/src/main/ets** directory under **library**, create an ArkTS file named **workAbility.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility';
```
Implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class workAbility extends WorkSchedulerExtensionAbility {
// Callback invoked when the Work Scheduler task starts.
onWorkStart(workInfo) {
console.log(`onWorkStart CommonEvent publish start ${JSON.stringify(workInfo)}`);
// Publish an upgrade notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', upgradeMessage, '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStart notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStart notification publish success`);
});
}
// Callback invoked when the Work Scheduler task stops.
onWorkStop(workInfo) {
// Publish an upgrade completion notification.
let notificationRequest = notification.getNotificationContentBasic('upgrade', 'upgrade success', '');
notification.publish(notificationRequest, (err) => {
if (err) {
console.log(`onWorkStop notification publish err ${JSON.stringify(err)}`);
}
console.log(`onWorkStop notification publish success`);
});
}
}
```
3. In the **./entry/src/main/ets** directory under the **entry** module of the project, create a directory named **workAbility**. In the **workAbility** directory, create an ArkTS file named **WorkTest.ets** and implement the callbacks for Work Scheduler.
Import the module.
```ts
import { workAbility } from '@ohos/library'
```
Inherit from **workAbility** and implement the lifecycle callbacks for the WorkSchedulerExtensionAbility.
```ts
export default class WorkTest extends workAbility {
onWorkStart(workInfo) {
console.log(`onWorkStartTest start ${JSON.stringify(workInfo)}`);
super.onWorkStart(workInfo);
}
onWorkStopTest(workInfo) {
super.onWorkStop(workInfo);
console.log(`onWorkStop value`);
}
}
```
### Implementing Work Scheduler
1. In the **./library/src/main/ets** directory under **library**, create a TypeScript file named **DelayWork.ts**, and implement the Work Scheduler APIs.
Import the module.
```ts
import workScheduler from '@ohos.resourceschedule.workScheduler';
```
Encapsulate the APIs for starting and stopping Work Scheduler tasks.
```ts
export default class DelayWork {
private workInfo = {
workId: 1,
networkType: workScheduler.NetworkType.NETWORK_TYPE_WIFI,
bundleName: '',
abilityName: ''
}
// Start the Work Scheduler task.
startWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
try {
workScheduler.startWork(this.workInfo);
console.log(`startWork success`);
} catch (error) {
Logger.error(TAG, `startWork startwork failed. code is ${error.code} message is ${error.message}`);
prompt.showToast({
message: `${error.message}`
});
}
}
// Stop the Work Scheduler task.
stopWork(bundleName: string, abilityName: string) {
this.workInfo.bundleName = bundleName;
this.workInfo.abilityName = abilityName;
workScheduler.stopWork(this.workInfo, false);
console.log(`stopWork`);
}
}
```
2. In the **./entry/src/main/ets/pages/index.ets** directory under the **entry** module of the project, add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task.
Import the module.
```ts
import { workAbility } from '@ohos/library';
```
Add the **Upgrade** button, which, when being clicked, will call the API encapsulated in **library** to start the Work Scheduler task. In the API, **bundleName** and **abilityName** are passed in, where the value of **abilityName** is **WorkTest**.
```ts
Button($r('app.string.upgrade'))
.width('60%')
.height(40)
.fontSize(30)
.onClick(() => {
this.work.startWork('ohos.samples.workscheduler', 'WorkTest');
});
```
When the component is destructed, it calls the API to stop the Work Scheduler task.
```ts
aboutToDisappear() {
this.work.stopWork('ohos.samples.workscheduler', 'WorkTest');
}
```
### Setting the Configuration File
1. Register the WorkSchedulerExtensionAbility in the [module.json5 file](../quick-start/module-configuration-file.md) under the **entry** module. Set **type** to **workScheduler** and **srcEnty** to the code path of the WorkSchedulerExtensionAbility component.
```json
{
"module": {
"extensionAbilities": [
{
"name": "WorkTest",
"srcEntry": "./ets/workAbility/WorkTest.ets",
"label": "$string:WorkSchedulerExtensionAbility_label",
"description": "$string:WorkSchedulerExtensionAbility_desc",
"type": "workScheduler"
}
]
}
}
```
## Restrictions
To minimize the abuse of **WorkSchedulerExtensionAbility** by third-party applications, the following APIs cannot be invoked in **WorkSchedulerExtensionAbility**:
- @ohos.backgroundTaskManager.d.ts
- @ohos.resourceschedule.backgroundTaskManager.d.ts
- @ohos.multimedia.camera.d.ts
- @ohos.multimedia.audio.d.ts
- @ohos.multimedia.media.d.ts
...@@ -40,14 +40,26 @@ ...@@ -40,14 +40,26 @@
- [Drawing Geometric Shapes (Shape)](arkts-geometric-shape-drawing.md) - [Drawing Geometric Shapes (Shape)](arkts-geometric-shape-drawing.md)
- [Drawing Custom Graphics on the Canvas (Canvas)](arkts-drawing-customization-on-canvas.md) - [Drawing Custom Graphics on the Canvas (Canvas)](arkts-drawing-customization-on-canvas.md)
- Using Animation - Using Animation
- [Animation Overview](arkts-animation-overview.md) - [Animation Overview](arkts-animation.md)
- Animation Within a Page - Attribute Animation
- [Layout Update Animation](arkts-layout-update-animation.md) - [Attribute Animation Overview](arkts-attribute-animation-overview.md)
- [Transition Animation Within a Component](arkts-transition-animation-within-component.md) - [Attribute Animation APIs](arkts-attribute-animation-apis.md)
- [Spring Curve Animation](arkts-spring-animation.md) - [Custom Attribute Animation](arkts-custom-attribute-animation.md)
- Animation Between Pages - Transition Animation
- [Zoom Animation](arkts-zoom-animation.md) - [Transition Animation Overview](arkts-transition-overview.md)
- [Page Transition Animation](arkts-page-transition-animation.md) - [Enter/Exit Transition](arkts-enter-exit-transition.md)
- [Navigation Transition](arkts-navigation-transition.md)
- [Modal Transition](arkts-modal-transition.md)
- [Shared Element Transition](arkts-shared-element-transition.md)
- [Component Animation](arkts-component-animation.md)
- Animation Curve
- [Traditional Curve](arkts-traditional-curve.md)
- [Spring Curve](arkts-spring-curve.md)
- [Animation Smoothing](arkts-animation-smoothing.md)
- Animation Effects
- [Blur Effect](arkts-blur-effect.md)
- [Shadow Effect](arkts-shadow-effect.md)
- [Color Effect](arkts-color-effect.md)
- Using Interaction Events - Using Interaction Events
- [Interaction Event Overview](arkts-event-overview.md) - [Interaction Event Overview](arkts-event-overview.md)
- Universal Events - Universal Events
......
# Animation Overview
The principle of animation is that the UI appearance is changed for multiple times within a period of time. Because human eyes retain persistence of vision, what you finally see is a continuous animation. A change of the UI is called an animation frame, which corresponds to a screen refresh. An important indicator that determines the animation smoothness is the frame rate (FPS), that is, the number of animation frames per second. The higher the frame rate, the smoother the animation.
In ArkUI, an animation is generated by changing the attribute value and specifying the animation parameters. Animation parameters include animation duration, change rule (that is, curve), and more. After the attribute value changes, the original state is transited to the new state according to the animation parameters. In this way, an animation is formed.
The animation capability provided by ArkUI can be classified into intra-page animation and inter-page animation based on the page classification mode. As shown in the following figure, an animation on a page refers to an animation that can occur on a page, and an animation between pages refers to an animation that occurs only with redirection between pages.
**Figure 1** Animation by page
![en-us_image_0000001562700385](figures/en-us_image_0000001562700385.png)
By capability, the animation can be divided into three parts: attribute animation, explicit animation, and transition animation, as shown in the following figure.
**Figure 2** Animation classified by basic capability
![en-us_image_0000001562820753](figures/en-us_image_0000001562820753.png)
This topic will introduce you to the usage and precautions of animations by the preceding classification and use cases.
# Animation Smoothing
When running animations, the UI is also interacting with users in real time. It must respond immediately to changes in user behavior. For example, if the user swipes up to exit in the midst of an application launch process, the UI should immediately transit from the startup animation to the exit animation, rather than finishing the startup animation before exiting. In the scenario where the animation triggered when the user lifts their fingers off the screen, the initial velocity of the animation must inherit the gesture speed, so as to avoid pauses caused by speed disconnection. For the preceding and similar scenarios, OpenHarmony provides efficient APIs for smoothing between animations and between animations and gestures.
## Smoothing Between Animations
Assume that there is a running animation for an animatable attribute. If the end value of the attribute changes due to an operation on the UI, just change the attribute value in the **animateTo** closure or change the input parameter value of the **animation** API to create an animation. OpenHarmony then automatically connects the previous animation with the current animation – the created animation.
```ts
import curves from '@ohos.curves'
// Step 1: Declare the related state variable.
@state scaleToggle: boolean = true;
...
Column() {
Button()
// Step 2: Set the declared state variable to the related animatable attribute API.
.scale(this.scaleToggle ? 1 : 0.5)
// Step 3: Change the state variable value through the click event, which then changes the attribute value.
.onclick(() => {
this.scaleToggle = !this.scaleToggle;
})
// Step 4: Enable the implicit animation. When the end value of the animation changes, the system automatically adds the smoothing animation.
.animation({
curve: curves.springMotion()
})
}
...
```
A complete example is as follows: By clicking **click**, you change the **scale** attribute of the red square. When you click **click** repeatedly, the end value of the **scale** attribute changes continuously, and the current animation smoothly moves towards the new end value of the **scale** attribute.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct AnimationToAnimationDemo {
@State isAnimation: boolean = false;
build() {
Column() {
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xf56c6c)
.width(100)
.height(100)
.scale({ x: this.isAnimation ? 2 : 1, y: this.isAnimation ? 2 : 1 })
.animation({ curve: curves.springMotion(0.4, 0.8) })
Button('Click')
.margin({ top: 200 })
.onClick(() => {
this.isAnimation = !this.isAnimation;
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
![en-us_image_0000001599971890](figures/en-us_image_0000001599971890.gif)
## Smoothing Between Gestures and Animations
In scenarios where gestures are used, an attribute change is generally triggered when the user places or moves their finger (or fingers) on the screen, and continues after the user lifts their finger (or fingers) off the screen until the end value of the attributes is reached.
The initial velocity of the attribute change after the user lifts their finger (or fingers) should be consistent with the velocity of the attribute change at the moment before the user lifts their finger (or fingers). If the former is **0**, it feels like a running car stops suddenly, an unusual abrupt change not welcomed by users.
In cases where smoothing between gestures and animations is required, for example, when scrolling a list, you can apply a responsive spring curve for the attribute animation running when the user places or moves their finger (or fingers) on the screen; and apply a spring curve for the attribute animation running after the user lifts their finger (or fingers) off the screen. For the animation that uses the [springMotion](../reference/apis/js-apis-curve.md#curvesspringmotion9) curve, the attribute animation running when the user places or moves their finger (or fingers) on the screen automatically inherits the previous velocity and starts from where the previous animation leaves off.
```ts
import curves from '@ohos.curves'
// Step 1: Declare related state variables.
@state offsetX: number = 0;
@State offsetY: number = 0;
targetOffsetX: number = 100;
targetOffsetY: number = 100;
...
Column()
// Step 2: Set the declared state variables to the related animatable attribute APIs.
.translate({ x: this.offsetX, y: this.offsetY})
.gesture(
PanGesture({})
.onActionUpdate((event: GestureEvent) => {
// Step 3: Change the state variable value for the time when the user places or moves their finger (or fingers) on the screen and use reponsiveSpringMotion for movement toward the new value.
animateTo({
curve: curves.responsiveSpringMotion()
}, () => {
this.offsetX = event.offsetX;
this.offsetY = event.offsetY;
})
})
.onActionEnd(() => {
// Step 4: Set the end value of the state variable for after the user lifts their finger (or fingers), and use springMotion for movement toward the new value. The springMotion animation inherits the previous velocity.
animateTo({
curve: curves.SpringMotion()
}, () => {
this.offsetX = targetOffsetX;
this.offsetY = targetOffsetY;
})
})
)
...
```
Below is the complete sample code and effect.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct SpringMotionDemo {
@State positionX: number = 100;
@State positionY: number = 100;
diameter: number = 50;
build() {
Column() {
Row() {
Circle({ width: this.diameter, height: this.diameter })
.fill(Color.Blue)
.position({ x: this.positionX, y: this.positionY })
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Move) {
// When the user places or moves their finger on the screen, use the responsiveSpringMotion curve.
animateTo({ curve: curves.responsiveSpringMotion() }, () => {
// Subtract the radius so that the center of the ball moves to where the finger is placed.
this.positionX = event.touches[0].screenX - this.diameter / 2;
this.positionY = event.touches[0].screenY - this.diameter / 2;
console.info(`move, animateTo x:${this.positionX}, y:${this.positionY}`);
})
} else if (event.type === TouchType.Up) {
// After the user lifts their finger off the screen, use the springMotion curve.
animateTo({ curve: curves.springMotion() }, () => {
this.positionX = 100;
this.positionY = 100;
console.info(`touchUp, animateTo x:100, y:100`);
})
}
})
}
.width("100%").height("80%")
.clip(true) // If the ball moves beyond the parent component, it is invisible.
.backgroundColor(Color.Orange)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Center }) {
Text("Drag the ball").fontSize(16)
}
.width("100%")
Row() {
Text('Click position: [x: ' + Math.round(this.positionX) + ', y:' + Math.round(this.positionY) + ']').fontSize(16)
}
.padding(10)
.width("100%")
}.height('100%').width('100%')
}
}
```
![en-us_image_0000001647027001](figures/en-us_image_0000001647027001.gif)
# Animation Overview
The UI contains various components (such as time and wallpaper) that users can see when interacting with their devices. Attributes are APIs used to control the behavior of components. For example, you can adjust the location of a component on the screen through the location attribute.
In general cases, if the value of an attribute is changed, the UI will be updated accordingly. Animation can add smooth transition effects when the UI is updated. Let's look at an example. When the user touches an application icon on the home screen, the application window opens and replaces the home screen as the primary display area. In this application launch process, if no animation is added, the related attributes change immediately, and the application window directly replaces the home screen, resulting in a sense of visual discontinuity. By adding animation, we enable attribute changes to take place over time, thereby creating an illusion of visual continuity.
ArkUI provides a wide range of animation APIs (such as attribute animation and transition animation), which you can leverage to cause attributes to gradually change from the start value to the end value based on the specified settings. Although the attribute values are not absolutely continuous during the change, but rather discrete to some extent, what you finally see is a continuous animation, since human eyes retain persistence of vision. A change of the UI is called an animation frame, which corresponds to a screen refresh. An important indicator that determines the animation smoothness is the frame rate (FPS), that is, the number of animation frames per second. The higher the frame rate, the smoother the animation. In ArkUI, animation parameters include animation duration, animation curve, and more. As the main factor of the animation, the animation curve determines the law of attribute value changes. For example, with a linear animation curve, the attribute changes from the start value to the end value at a constant speed over the given duration. If the attribute changes too fast or too slow, the visual experience may suffer. Therefore, animation parameters, especially animation curves, must be well designed and adjusted to be tailored to use cases.
Animation APIs drive attribute values to continuously transit from one state to another according to the rule determined by the animation parameters, and thereby generate a continuous visual effect on the UI. This walkthrough demonstrates the steps and precautions to follow, for creating a fascinating animation experience for users. It is organized as follows.
![en-us_image_0000001595763076](figures/en-us_image_0000001595763076.png)
- Attribute animation: It is the most basic animation type. It drives attribute changes frame by frame based on animation parameters to create an animation on a frame-by-frame basis.
- Transition animation: animation for transitioning when components appear and disappear. To maintain animation consistency, some animation curves have been built in and cannot be customized.
- Whenever possible, avoid ability redirection in the animation. An ability is a task in effect and is individually displayed on the recent tasks screen. Redirection between abilities is redirection between tasks. In the typical scenario of viewing large images in an application, if you call the gallery ability from the application to open large images, then the gallery ability will appear on the recent tasks screen. This is not recommended. A more recommended practice is as follows: Build a large image component in the application and invoke that component through modal transition. In this way, the entire animation can be completed in one ability.
- To implement navigation, use the **\<Navigation>** component, instead of the page routing mode. The page routing mode causes page separation, which is inconvenient for implementing linked transition effects. In addition, it does not allow for one-time development for multi-device deployment.
- Component animation: Components provide default animations (such as the slide animation of the **\<List>** component). Some of them even support custom animations.
- Animation curve: You can use traditional and spring curves to control how the attribute values change, to create an engaging animation effect.
- Animation connection: Make the transition between animations and between gestures and animations as natural as possible.
- Advanced animation effect: You can up your animation game with advanced effects such as blur, shadow, color gradient, and the like.
# Attribute Animation APIs
ArkUI provides two types of APIs, namely, [animateTo](../reference/arkui-ts/ts-explicit-animation.md) and [animation](../reference/arkui-ts/ts-animatorproperty.md), to implement an attribute animation – a visual illusion of continuity created by driving component attributes to change over time based on animation parameters such as the animation curve.
| API| Scope| Principle| Description|
| -------- | -------- | -------- | -------- |
| animateTo | GUI changes caused by attribute changes in closures.<br>Transition for appearance and disappearance.| As a general function, animates the differences between the UIs before and after the state variable in the closure is changed.<br>This API can be called multiple times and can be nested.| Applicable when a single set of animation parameters is used to animate multiple attributes.<br>Applicable when animations need to be nested.|
| animation | GUI changes caused by attribute changes bound to components through attribute APIs.| Identifies the change of the animatable attributes of a component and automatically adds an animation.<br>As the API call sequence of the component is from bottom to top, this API applies only to the attributes above it.<br>In a component, you can set individual **animation** for attributes based on the call sequence.| Applicable when different sets of animation parameters are used to animate different attributes.|
## Using animateTo
```
animateTo(value: AnimateParam, event: () => void): void
```
Among the parameters of [animateTo](../reference/arkui-ts/ts-explicit-animation.md), **value** indicates the [animation parameters](../reference/arkui-ts/ts-explicit-animation.md#animateparam) (including duration and [curve](../reference/apis/js-apis-curve.md#curve); **event** indicates the closure of the animation. Attribute animations generated by variable changes within the closure follow the same animation parameters.
```ts
import curves from '@ohos.curves'
@Entry
@Component
struct AnimateToDemo {
@State animate: boolean = false;
// Step 1: Declare related state variables.
@State rotateValue: number = 0; // Rotation angle of component 1.
@State translateY: number = 0; // Offset of component 2
@State opacityValue: number = 1; // Opacity of component 2.
//Step 2: Set the declared state variables to the related animatable attribute APIs.
build() {
Column() {
// Component 1
Column() {
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width(150)
.height(150)
.borderRadius(10)
.rotate({ angle: this.rotateValue })
.backgroundColor(0xf56c6c)
// Component 2
Column() {
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width(150)
.height(150)
.backgroundColor(0x67C23A)
.borderRadius(10)
.opacity(this.opacityValue)
.translate({ y: this.translateY })
Button('Click')
.margin({ top: 120 })
.onClick(() => {
this.animate = !this.animate;
// Step 3: Enable the implicit animation.
animateTo({ curve: curves.springMotion() }, () => {
// Step 4: Change the state variables in the closure to update the UI.
// You can write any logic that can change the UI, such as array adding and visibility control. The system detects the differences between the new UI and the previous UI and adds animations for the differences.
// The rotate attribute of component 1 is changed. Therefore, a rotate animation is added to component 1.
this.rotateValue = this.animate ? 90 : 0;
// The scale attribute of component 2 is changed. Therefore, a scale animation is added to component 2.
this.opacityValue = this.animate ? 0.6 : 1;
// The offset attribute of component 2 is changed. Therefore, an offset animation is added to component 2.
this.translateY = this.animate ? 100 : 0;
})
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
![en-us_image_0000001599958466](figures/en-us_image_0000001599958466.gif)
## Using animation
Compared with the **animateTo** API, the [animation](../reference/arkui-ts/ts-animatorproperty.md) API does not need to use a closure. Just add it to the end of the target animatable attribute. Then the API automatically adds an attribute animation as long as it detects that the bound attribute is changed.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct AnimationDemo {
@State animate: boolean = false;
// Step 1: Declare related state variables.
@State rotateValue: number = 0; // Rotation angle of component 1.
@State translateY: number = 0; // Offset of component 2
@State color: Color = Color.White; // Font color of component 2.
@State opacityValue: number = 1; // Opacity of the parent component.
//Step 2: Set the declared state variables to the related animatable attribute APIs.
build() {
Column() {
Column() {
// Component 1
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0xf56c6c)
.rotate({ angle: this.rotateValue })
// Step 3: Enable the implicit animation. As the API call sequence of the component is from bottom to top, the API takes effect on the rotate attribute.
.animation({ curve: curves.springMotion(0.3, 1.0) })
.width(150)
.height(150)
// Component 2
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(this.color)
// Step 3: Enable the implicit animation. As the API call sequence of the component is from bottom to top, the API takes effect on the fontColor attribute.
.animation({ curve: curves.springMotion(0.6, 1.2) })
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0x67C23A)
.width(150)
.height(150)
.translate({ y: this.translateY })
// Step 3: Enable the implicit animation. As the API call sequence of the component is from bottom to top, the API takes effect on the translate attribute.
.animation({ curve: curves.springMotion(0.3, 0.6) })
}
.justifyContent(FlexAlign.Center)
.opacity(this.opacityValue)
// The animation API takes effect on the opacity attribute. This results in an opacity change of the parent component <Column>, which in turn results in an opacity change of its child components. Therefore, animations are added to the opacity attributes of <Column> and its child components.
.animation({ curve: curves.springMotion() })
// Step 4: Change the state variable to update the UI. The system detects the differences between the new UI and the previous UI and adds animations for the differences.
Button('Click')
.margin({ top: 120 })
.onClick(() => {
this.animate = !this.animate;
// The rotate attribute of component 1 is changed. Therefore, a rotate animation is added to component 1.
this.rotateValue = this.animate ? 90 : 0;
// The translate attribute of component 2 is changed. Therefore, a translate animation is added to component 2.
this.translateY = this.animate ? 100 : 0;
// The fontColor attribute of component 2 is changed. Therefore, a fontColor animation is added to component 2.
this.color = this.animate ? Color.Black : Color.White;
// The opacity attribute of the parent component <Column> is changed, which results in an opacity change of its child components. Therefore, opacity animations are added to <Column> and its child components.
this.opacityValue = this.animate ? 0.6 : 1;
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
![en-us_image_0000001649279705](figures/en-us_image_0000001649279705.gif)
> **NOTE**
> - When an animation is applied to the position or size change of a component, as layout measurement is involved, performance overheads are high. To reduce performance overheads, use the [scale](../reference/arkui-ts/ts-universal-attributes-transformation.md) instead, whose value change does not involve layout measurement. This practice is applicable where the component location and size change continuously, for example, where the component size changes as a response to gestures.
>
> - Attribute animations should be applied to the components that are always present. For the components that may appear or disappear, use the [transition animation](arkts-transition-overview.md).
>
> - Avoid using callbacks invoked when an animation ends. Implicit animations are applied to states that have occurred. You do not need to process the end logic. If such callbacks are needed, be sure to handle the data management of continuous operations correctly.
# Attribute Animation Overview
An attribute API (attribute for short) defines a multitude of attributes, such as size, layout, and location, for controlling behavior of the owning component. Changes to some attributes (such as location) on the UI will cause UI re-render. You can animate the value change of an attribute from the start point to the end point. Attributes can be classified as animatable or non-animatable, depending on whether an animation can be applied to their value changes. Specifically, an animatable attribute meets the following requirements:
1. Its value changes can cause UI re-render. For example, the [enabled](../reference/arkui-ts/ts-universal-attributes-enable.md) attribute is used to control whether a component can respond to events such as clicks and touches. However, as its value change does not cause UI re-render, it does not qualify as an animatable attribute.
2. An animation can be applied to the transition between value changes. For example, the [focusable](../reference/arkui-ts/ts-universal-attributes-focus.md) attribute determines whether the current component can obtain focus. If the value of this attribute changes, the component should immediately switch to the end state to respond to user behavior, and no animation is appropriate here. Therefore, the attribute does not qualify as an animatable attribute.
**Attribute classification:**
- Animatable attributes:
- Built-in animatable attributes
| Category | Example |
| -------- | ---------------------------------------------- |
| Layout| Position, size, padding, margin, alignment, and weight.|
| Affine transformation| Translation, rotation, scaling, and anchor. |
| Background | Background color and blur. |
| Content | Font size, font color, image alignment, and blur. |
| Foreground | Foreground color. |
| Overlay | Overlay. |
| Appearance | Opacity, rounded corner, border, and shadow. |
| ... | ... |
- Custom animatable attributes: animatable attributes abstracted through the custom attribute animation mechanism.
- Non-animatable attributes: **zIndex** and **focusable**, among others.
Generally, an animatable attribute accepts only continuous parameters, which allows for using interpolation to fill in gaps between data points, so as to create a visual illusion of continuity. That said, whether the parameter type of an attribute can be interpolated is not a key factor that determines whether an animation can be applied to the attribute. For example, with regard to the [direction](../reference/arkui-ts/ts-universal-attributes-location.md) attribute, which sets the horizontal layout of an element, as it is animatable, ArkUI allows you to apply an animation to the transition between its value changes, though its parameter type is enum.
Animatable attributes include both built-in and custom attributes.
- Built-in animatable attributes: system-provided component attributes for changing the UI, for example, position, zoom, and blur attributes.
- [Custom animatable attributes](../quick-start/arkts-animatable-extend.md): attributes made animatable with the use of the [@AnimatableExtend](../quick-start/arkts-animatable-extend.md) decorator. You can abstract animatable attributes from the custom drawing content to control the drawing content of each frame, for example, customizing the volume icon. By defining custom animatable attributes, you can apply animations to some attributes that otherwise do not support animations in ArkUI.
# Blur Effect
Animation effects can add detail to your animations and create a sense of realism. For example, blur and shadow effects can lend a 3D look to objects and deliver a more engaging animation experience. ArkUI provides a diverse array of efficient APIs for you to develop exquisite and personalized effects. This topic covers the common blur, shadow, and color effects.
Blur effects add a sense of depth and allow for distinction of hierarchical relationship between elements.
| API | Description |
| ---------------------------------------- | ---------------------- |
| [backdropBlur](../reference/arkui-ts/ts-universal-attributes-image-effect.md) | Applies a background blur effect to the component. The input parameter is the blur radius.|
| [blur](../reference/arkui-ts/ts-universal-attributes-image-effect.md) | Applies a foreground blur effect to the component. The input parameter is the blur radius.|
| [backgroundBlurStyle](../reference/arkui-ts/ts-universal-attributes-background.md) | Applies a background blur effect to the component. The input parameter is the blur style.|
| [foregroundBlurStyle](../reference/arkui-ts/ts-universal-attributes-foreground-blur-style.md) | Applies a foreground blur effect to the component. The input parameter is the blur style.|
## Applying Background Blur with backdropBlur
```ts
@Entry
@Component
struct BlurEffectsExample {
build() {
Column({ space: 10 }) {
Text('backdropblur')
.width('90%')
.height('90%')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.backdropBlur(10) // Apply background blur.
.backgroundImage($r('app.media.share'))
.backgroundImageSize({ width: 400, height: 300 })
}
.width('100%')
.height('50%')
.margin({ top: 20 })
}
}
```
![en-us_image_0000001599812870](figures/en-us_image_0000001599812870.png)
## Applying Foreground Blur with blur
```ts
@Entry
@Component
struct Index {
@State radius: number = 0;
@State text: string = '';
@State y: string = 'Finger not on the screen';
aboutToAppear() {
this.text = "Press a finger on the screen and slide up and down\n" + "Current finger position on the y-axis: " + this.y +
"\n" + "Blur radius:" + this.radius;
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text(this.text)
.height(200)
.fontSize(20)
.fontWeight(FontWeight.Bold)
.fontFamily("cursive")
.fontStyle(FontStyle.Italic)
Image($r("app.media.wall"))
.blur(this.radius) // Apply foreground blur.
.height('100%')
.width("100%")
.objectFit(ImageFit.Cover)
}.height('100%')
.width("100%")
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Move) {
this.y = parseInt(event.touches[0].y.toString()).toString();
this.radius = parseInt(this.y) / 10; // Modify the blur radius based on the sliding distance.
}
if (event.type === TouchType.Up) {
this.radius = 0;
this.y = 'Finger off the screen';
}
this.text = "Press a finger on the screen and slide up and down\n" + "Current finger position on the y-axis: " + this.y +
"\n" + "Blur radius:" + this.radius;
})
}
}
```
![en-us_image_0000001599813588](figures/en-us_image_0000001599813588.gif)
## Applying Background Blur with backgroundBlurStyle
```ts
@Entry
@Component
struct BackDropBlurStyleDemo {
build() {
Grid() {
GridItem() {
Column() {
Column() {
Text ('Original')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
Text ('Original')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Thin')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
// BlurStyle.Thin: Thin blur is applied.
// ThemeColorMode.LIGHT: The light color mode is used.
// AdaptiveColor.DEFAULT: Adaptive color mode is not used. The default color is used as the mask color.
// scale: blurredness of the background material. The default value is 1.
.backgroundBlurStyle(BlurStyle.Thin, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Thin')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Regular')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.Regular, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Regular')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Thick')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.Thick, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Thick')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_THIN')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.BACKGROUND_THIN, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_THIN')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_REGULAR')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.BACKGROUND_REGULAR, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_REGULAR')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_THICK')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.BACKGROUND_THICK, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_THICK')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_ULTRA_THICK')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.backgroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_ULTRA_THICK')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
}
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr 1fr 1fr')
.width('100%')
.height('100%')
.margin({ top: 40 })
}
}
```
![en-us_image_0000001649455517](figures/en-us_image_0000001649455517.png)
## Applying Foreground Blur with foregroundBlurStyle
```ts
@Entry
@Component
struct ForegroundBlurStyleDemo {
build() {
Grid() {
GridItem() {
Column() {
Column() {
Text ('Original')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
Text ('Original')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Thin')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
// BlurStyle.Thin: Thin blur is applied.
// ThemeColorMode.LIGHT: The light color mode is used.
// AdaptiveColor.DEFAULT: Adaptive color mode is not used. The default color is used as the mask color.
// scale: blurredness of the background material. The default value is 1.
.foregroundBlurStyle(BlurStyle.Thin, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Thin')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Regular')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.Regular, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Regular')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('Thick')
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.Thick, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('Thick')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_THIN')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.BACKGROUND_THIN, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_THIN')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_REGULAR')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.BACKGROUND_REGULAR, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_REGULAR')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_THICK')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.BACKGROUND_THICK, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_THICK')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
GridItem() {
Column() {
Column() {
Text('BACKGROUND_ULTRA_THICK')
.fontSize(12)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.height(100)
.aspectRatio(1)
.borderRadius(10)
.backgroundImage($r('app.media.share'))
.foregroundBlurStyle(BlurStyle.BACKGROUND_ULTRA_THICK, {
colorMode: ThemeColorMode.LIGHT,
adaptiveColor: AdaptiveColor.DEFAULT,
scale: 0.1
})
Text('BACKGROUND_ULTRA_THICK')
.fontSize(12)
.fontColor(Color.Black)
}
.height('100%')
.justifyContent(FlexAlign.Start)
}
.width(200)
.height(200)
}
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr 1fr 1fr')
.width('100%')
.height('100%')
.margin({ top: 40 })
}
}
```
![en-us_image_0000001599658168](figures/en-us_image_0000001599658168.png)
# Color Effect
## APIs
You can use the color gradient APIs to apply a background color gradient effect to a component.
| API| Description|
| -------- | -------- |
| [linearGradient](../reference/arkui-ts/ts-universal-attributes-gradient-color.md) | Applies a linear gradient to the component.|
| [sweepGradient](../reference/arkui-ts/ts-universal-attributes-gradient-color.md) | Applies a sweep gradient effect to the component.|
| [radialGradient](../reference/arkui-ts/ts-universal-attributes-gradient-color.md) | Applies a radial gradient effect to the component.|
## Applying Linear Gradient Effect
```ts
@Entry
@Component
struct LinearGradientDemo {
build() {
Grid() {
GridItem() {
Column() {
Text('angle: 180')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.linearGradient({
// A positive value indicates a clockwise rotation from the origin, (0, 0). The default value of the linear gradient start angle is 180°.
colors: [
[0xf56c6c, 0.0], // Color and weight of color stop 1, corresponding to the start position of the component in the 180° direction.
[0xffffff, 1.0], // Color and weight of color stop 2, corresponding to the end position of the component in the 180° direction.
]
})
}
GridItem() {
Column() {
Text('angle: 45')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.linearGradient({
angle: 45, // Set the linear gradient start angle to 45°.
colors: [
[0xf56c6c, 0.0],
[0xffffff, 1.0],
]
})
}
GridItem() {
Column() {
Text('repeat: true')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.linearGradient({
repeating: true, // Repeat the gradients of the area from 0 to 0.3 in the area from 0.3 to 1.0.
colors: [
[0xf56c6c, 0.0],
[0xE6A23C, .3],
]
})
}
GridItem() {
Column() {
Text('repeat: fasle')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.linearGradient({
colors: [
[0xf56c6c, 0.0], // As repeating is not specified, the default value false is used. In this case, only the area from 0 to 0.3 in the component have the color gradient effect.
[0xE6A23C, .3],
]
})
}
}
.columnsGap(10)
.rowsGap(10)
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr 1fr')
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001641176829](figures/en-us_image_0000001641176829.png)
## Applying Sweep Gradient Effect
```ts
@Entry
@Component
struct SweepGradientDemo {
build() {
Grid() {
GridItem() {
Column() {
Text('center: 50')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.sweepGradient({
center: [50, 50], // Center point of the sweep gradient.
start: 0, // Start point of the sweep gradient.
end: 360, // End point of the sweep gradient.
repeating: true, // The gradients are repeated.
colors: [
// Based on the center point, start point, and end point settings,
// the color changes from color stop 1 to color stop 2 in the area within angles from 0 to 0.125;
// the color changes from color stop 2 to color stop 3 in the area within angles from 0.125 to 0.25;
// the color gradients of the area within angles from 0 to 0.25 are repeated in the area within angles from 0.25 to 1.
[0xf56c6c, 0], // Color and weight of color stop 1. The corresponding angle is 0° (0 x 360°), and the corner is the center point.
[0xffffff, 0.125], // Color and weight of color stop 2.
[0x409EFF, 0.25] // Color and weight of color stop 3.
]
})
}
GridItem() {
Column() {
Text('center: 0')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.sweepGradient({
center: [0, 0], // Center point of the sweep gradient, which is the coordinate of the upper left corner of the component in this example.
start: 0,
end: 360,
repeating: true,
colors: [
// In the current component, the sweep gradient center is the upper left corner of the component. Therefore, the angle range from color stop 1 to color stop 3 can cover the entire component.
[0xf56c6c, 0], // Color and weight of color stop 1. The corresponding angle is 0° (0 x 360°)
[0xffffff, 0.125], // Color and weight of color stop 2. The corresponding angle is 45° (0.125 x 360°).
[0x409EFF, 0.25] // Color and weight of color stop 3. The corresponding angle is 90° (0.25 x 360°).
]
})
}
GridItem() {
Column() {
Text('repeat: true')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.sweepGradient({
center: [50, 50],
start: 0,
end: 360,
repeating: true,
colors: [
[0xf56c6c, 0],
[0xffffff, 0.125],
[0x409EFF, 0.25]
]
})
}
GridItem() {
Column() {
Text('repeat: false')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.sweepGradient({
center: [50, 50],
start: 0,
end: 360,
repeating: false, // The color gradient effect is generated only within the coverage of the color stop angles.
colors: [
[0xf56c6c, 0],
[0xffffff, 0.125],
[0x409EFF, 0.25]
]
})
}
}
.columnsGap(10)
.rowsGap(10)
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr 1fr')
.width('100%')
.height(437)
}
}
```
![en-us_image_0000001641177073](figures/en-us_image_0000001641177073.png)
## Applying Radial Gradient Effect
```ts
@Entry
@Component
struct radialGradientDemo {
build() {
Grid() {
GridItem() {
Column() {
Text('center: 50')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.radialGradient({
center: [50, 50], // Center point of the radial gradient.
radius: 100, // Radius of the radial gradient.
repeating: true, // The gradients are repeated outside the specified range to fill the entire component.
colors: [
// With [50, 50] as the center point, the gradient changes from color stop 1 to color stop 2 within the range of radius 0 to 12.5;
// the gradient changes from color stop 2 to color stop 3 within the range of radius 12.5 to 25;
// the gradients in the range of radius 0 to 25 are repeated to fill the entire component.
[0xf56c6c, 0], // Color and weight of color stop 1. The corresponding radius is 0 (0 x 100).
[0xffffff, 0.125], // Color and weight of color stop 2. The corresponding radius is 12.5 (0.125 x 100).
[0x409EFF, 0.25] // Color and weight of color stop 3. The corresponding radius is 25 (0.25 x 100).
]
})
}
GridItem() {
Column() {
Text('center: 0')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.radialGradient({
center: [0, 0], // Center point of the radial gradient, which is the coordinate of the upper left corner of the component in this example.
radius: 100,
repeating: true,
colors: [
[0xf56c6c, 0],
[0xffffff, 0.125],
[0x409EFF, 0.25]
]
})
}
GridItem() {
Column() {
Text('repeat: true')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.radialGradient({
center: [50, 50],
radius: 100,
repeating: true,
colors: [
[0xf56c6c, 0],
[0xffffff, 0.125],
[0x409EFF, 0.25]
]
})
}
GridItem() {
Column() {
Text('repeat: false')
.fontSize(15)
}
.width(100)
.height(100)
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.radialGradient({
center: [50, 50],
radius: 100,
repeating: false, // The gradients are not repeated.
colors: [
[0xf56c6c, 0],
[0xffffff, 0.125],
[0x409EFF, 0.25]
]
})
}
}
.columnsGap(10)
.rowsGap(10)
.columnsTemplate('1fr 1fr')
.rowsTemplate('1fr 1fr 1fr')
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001592904050](figures/en-us_image_0000001592904050.png)
# Component Animation
In addition to universal attribute animation and transition animation APIs, ArkUI provides default animation effects for certain components, for example, the swipe effect for the [\<List>](../reference/arkui-ts/ts-container-list.md) component and the click effect of the [\<Button>](../reference/arkui-ts/ts-basic-components-button.md#button) component. Based on these default animation effects, you can apply custom animations to the child components through the attribute animation and transition animation APIs.
## Using Default Component Animation
The default animation of a component exhibits the following features:
- Indicate the current state of the component. For example, after the user clicks a **\<Button>** component, the component turns gray, indicating that it is selected.
- Make UI interactions more intuitive and pleasurable.
- Reduce development workload, as the APIs are readily available.
For more effects, see [Component Overview](../reference/arkui-ts/ts-components-summary.md).
Below is the sample code and effect:
```ts
@Entry
@Component
struct ComponentDemo {
build() {
Row() {
Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
.select(true)
.selectedColor(0xed6f21)
.size({ width: 50, height: 50 })
Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
.select(false)
.selectedColor(0x39a2db)
.size({ width: 50, height: 50 })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
```
![en-us_image_0000001649338585](figures/en-us_image_0000001649338585.gif)
## Customizing Component Animation
Some components allow for animation customization for their child components through the [attribute animation](arkts-attribute-animation-overview.md) and [transition animation](arkts-transition-overview.md) APIs. For example, in the [\<Scroll>](../reference/arkui-ts/ts-container-scroll.md) component, you can customize the animation effect for when scrolling through its child components.
- For a scroll or click gesture, you can implement various effects by changing affine attributes of the child component.
- To customize the animation for a scroll , you can add a listener to listen for scroll distance in the **onScroll** callback and calculate the affine attribute of each component. You can also define gestures, monitor positions through the gestures, and manually call **ScrollTo** to change the scrolled-to position.
- Fine-tune the final scrolled-to position in the **onScrollStop** callback or gesture end callback.
Below is the sample code and effect for customizing the scroll effect of the child components of the **\<Scroll>** component:
```ts
import curves from '@ohos.curves';
import window from '@ohos.window';
import display from '@ohos.display';
import mediaquery from '@ohos.mediaquery';
/**
* Encapsulates the WindowManager class.
*/
export class WindowManager {
private static instance: WindowManager = null;
private displayInfo: display.Display = null;
private orientationListener = mediaquery.matchMediaSync('(orientation: landscape)');
private portraitFunc = null;
constructor() {
this.portraitFunc = this.onPortrait.bind(this);
this.orientationListener.on('change', this.portraitFunc)
this.loadDisplayInfo()
}
/**
* Sets the main window.
* @param win Indicates the current application window.
*/
setMainWin(win: window.Window) {
if (win == null) {
return
}
globalThis.mainWin = win;
win.on("windowSizeChange", (data: window.Size) => {
if (globalThis.mainWindowSize == undefined || globalThis.mainWindowSize == null) {
globalThis.mainWindowSize = data;
} else {
if (globalThis.mainWindowSize.width == data.width && globalThis.mainWindowSize.height == data.height) {
return
}
globalThis.mainWindowSize = data;
}
let winWidth = this.getMainWindowWidth();
AppStorage.SetOrCreate<number>('mainWinWidth', winWidth)
let winHeight = this.getMainWindowHeight();
AppStorage.SetOrCreate<number>('mainWinHeight', winHeight)
globalThis.context.eventHub.emit("windowSizeChange", winWidth, winHeight)
})
}
static getInstance(): WindowManager {
if (this.instance == null) {
this.instance = new WindowManager();
}
return this.instance
}
private onPortrait(mediaQueryResult: mediaquery.MediaQueryResult) {
if (mediaQueryResult.matches == AppStorage.Get<boolean>('isLandscape')) {
return
}
AppStorage.SetOrCreate<boolean>('isLandscape', mediaQueryResult.matches)
this.loadDisplayInfo()
}
/**
* Changes the screen orientation.
* @param ori Indicates the orientation.
*/
changeOrientation(ori: window.Orientation) {
if (globalThis.mainWin != null) {
globalThis.mainWin.setPreferredOrientation(ori)
}
}
private loadDisplayInfo() {
this.displayInfo = display.getDefaultDisplaySync()
AppStorage.SetOrCreate<number>('displayWidth', this.getDisplayWidth())
AppStorage.SetOrCreate<number>('displayHeight', this.getDisplayHeight())
}
/**
* Obtains the width of the main window, in vp.
*/
getMainWindowWidth(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.width) : 0
}
/**
* Obtains the height of the main window, in vp.
*/
getMainWindowHeight(): number {
return globalThis.mainWindowSize != null ? px2vp(globalThis.mainWindowSize.height) : 0
}
/**
* Obtains the screen width, in vp.
*/
getDisplayWidth(): number {
return this.displayInfo != null ? px2vp(this.displayInfo.width) : 0
}
/**
* Obtains the screen height, in vp.
*/
getDisplayHeight(): number {
return this.displayInfo != null ? px2vp(this.displayInfo.height) : 0
}
/**
* Releases resources.
*/
release() {
if (this.orientationListener) {
this.orientationListener.off('change', this.portraitFunc)
}
if (globalThis.mainWin != null) {
globalThis.mainWin.off('windowSizeChange')
}
WindowManager.instance = null;
}
}
/**
* Encapsulates the TaskData class.
*/
export class TaskData {
bgColor: Color | string | Resource = Color.White;
index: number = 0;
taskInfo: string = 'music';
constructor(bgColor: Color | string | Resource, index: number, taskInfo: string) {
this.bgColor = bgColor;
this.index = index;
this.taskInfo = taskInfo;
}
}
export const taskDataArr: Array<TaskData> =
[
new TaskData(0xFA8072, 0, 'music'),
new TaskData(0xF4A460, 1, 'mall'),
new TaskData(0xFFFACD, 2, 'photos'),
new TaskData(0x98FB98, 3, 'setting'),
new TaskData(0x7FFFD4, 4, 'call'),
new TaskData(0x87CEFA, 5, 'music'),
new TaskData(0x7B68EE, 6, 'mall'),
new TaskData(0x909399, 7, 'photos'),
new TaskData(0x888888, 8, 'setting'),
new TaskData(0xFFC0CB, 9, 'call'),
new TaskData(0xFFC0CB, 10, 'music'),
new TaskData(0x888888, 11, 'mall'),
new TaskData(0x909399, 12, 'photos'),
new TaskData(0x7B68EE, 13, 'setting'),
new TaskData(0x87CEFA, 14, 'call'),
new TaskData(0x7FFFD4, 15, 'music'),
new TaskData(0x98FB98, 16, 'mall'),
new TaskData(0xFFFACD, 17, 'photos'),
new TaskData(0xF4A460, 18, 'setting'),
new TaskData(0xFA8072, 19, 'call'),
];
@Entry
@Component
export struct TaskSwitchMainPage {
displayWidth: number = WindowManager.getInstance().getDisplayWidth();
scroller: Scroller = new Scroller();
bgImage: Resource = $r('app.media.share');
cardSpace: number = 0; // Widget spacing
cardWidth: number = this.displayWidth / 2 - this.cardSpace / 2; // Widget width
cardHeight: number = 400; // Widget height
cardPosition: Array<number> = []; // Initial position of the widget
clickIndex: boolean = false;
@State taskViewOffsetX: number = 0;
@State cardOffset: number = this.displayWidth / 4;
lastCardOffset: number = this.cardOffset;
startTime: number
// Initial position of each widget
aboutToAppear() {
for (let i = 0; i < taskDataArr.length; i++) {
this.cardPosition[i] = i * (this.cardWidth + this.cardSpace);
}
}
// Position of each widget
getProgress(index: number): number {
let progress = (this.cardOffset + this.cardPosition[index] - this.taskViewOffsetX + this.cardWidth / 2) / this.displayWidth;
return progress
}
build() {
Stack({ alignContent: Alignment.Bottom }) {
// Background
Column()
.width('100%')
.height('100%')
.backgroundColor(0xF0F0F0)
// <Scroll> component
Scroll(this.scroller) {
Row({ space: this.cardSpace }) {
ForEach(taskDataArr, (item, index) => {
Column()
.width(this.cardWidth)
.height(this.cardHeight)
.backgroundColor(item.bgColor)
.borderStyle(BorderStyle.Solid)
.borderWidth(1)
.borderColor(0xAFEEEE)
.borderRadius(15)
// Calculate the affine attributes of child components.
.scale((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ?
{
x: 1.1 - Math.abs(0.5 - this.getProgress(index)),
y: 1.1 - Math.abs(0.5 - this.getProgress(index))
} :
{ x: 1, y: 1 })
.animation({ curve: Curve.Smooth })
// Apply a pan animation.
.translate({ x: this.cardOffset })
.animation({ curve: curves.springMotion() })
.zIndex((this.getProgress(index) >= 0.4 && this.getProgress(index) <= 0.6) ? 2 : 1)
}, item => item)
}
.width((this.cardWidth + this.cardSpace) * (taskDataArr.length + 1))
.height('100%')
}
.gesture(
GestureGroup(GestureMode.Parallel,
PanGesture({ direction: PanDirection.Horizontal, distance: 5 })
.onActionStart((event: GestureEvent) => {
this.startTime = event.timestamp;
})
.onActionUpdate((event: GestureEvent) => {
this.cardOffset = this.lastCardOffset + event.offsetX;
})
.onActionEnd((event: GestureEvent) => {
let time = event.timestamp - this.startTime;
let speed = event.offsetX / (time / 1000000000);
let moveX = Math.pow(speed, 2) / 7000 * (speed > 0 ? 1 : -1);
this.cardOffset += moveX;
// When panning left to a position beyond the rightmost position
let cardOffsetMax = -(taskDataArr.length - 1) * (this.displayWidth / 2);
if (this.cardOffset < cardOffsetMax) {
this.cardOffset = cardOffsetMax;
}
// When panning right to a position beyond the rightmost position
if (this.cardOffset > this.displayWidth / 4) {
this.cardOffset = this.displayWidth / 4;
}
// Processing when the pan distance is less than the minimum distance
let remainMargin = this.cardOffset % (this.displayWidth / 2);
if (remainMargin < 0) {
remainMargin = this.cardOffset % (this.displayWidth / 2) + this.displayWidth / 2;
}
if (remainMargin <= this.displayWidth / 4) {
this.cardOffset += this.displayWidth / 4 - remainMargin;
} else {
this.cardOffset -= this.displayWidth / 4 - (this.displayWidth / 2 - remainMargin);
}
// Record the pan offset.
this.lastCardOffset = this.cardOffset;
})
), GestureMask.IgnoreInternal)
.scrollable(ScrollDirection.Horizontal)
.scrollBar(BarState.Off)
// Move to the beginning and end positions.
Button('Move to first/last')
.backgroundColor(0x888888)
.margin({ bottom: 30 })
.onClick(() => {
this.clickIndex = !this.clickIndex;
if (this.clickIndex) {
this.cardOffset = this.displayWidth / 4;
} else {
this.cardOffset = this.displayWidth / 4 - (taskDataArr.length - 1) * this.displayWidth / 2;
}
this.lastCardOffset = this.cardOffset;
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001599808406](figures/en-us_image_0000001599808406.gif)
# Custom Attribute Animation
The attribute animation is an illusion of movement created on the UI when the value of an animatable attribute changes over time. It is implemented by setting continuous value changes of an attribute to the attribute API that can cause the UI re-render.
ArkUI provides the [@AnimatableExtend](../quick-start/arkts-animatable-extend.md) decorator for customizing animatable attribute APIs, which accepts only parameters of the number type or a custom type that implements [AnimtableArithmetic<T>](../quick-start/arkts-animatable-extend.md) to deliver continuous value changes. During execution of **animateTo** or **animation** with a custom animatable attribute API and the animatable data type, the frame-by-frame callback is used to change the value of a non-animatable attribute so that an animation effect can be applied to the attribute.
## Animating Font Size Changes with Number Data Type and \@AnimatableExtend Decorator
```ts
// Step 1: Use the @AnimatableExtend decorator to customize an animatable attribute API.
@AnimatableExtend(Text) function animatableFontSize(size: number) {
.fontSize(size) // Invoke the system attribute API.
}
@Entry
@Component
struct AnimatablePropertyExample {
@State fontSize: number = 20;
build() {
Column() {
Text("AnimatableProperty")
.animatableFontSize(this.fontSize) // Step 2: Set the custom animatable attribute API on the component.
.animation({ duration: 1000, curve: "ease" }) // Step 3: Bind an animation to the custom animatable attribute API.
Button("Play")
.onClick(() => {
this.fontSize = this.fontSize == 20 ? 36 : 20; // Step 4: Change the value of the custom animatable attribute to generate an animation.
})
}.width("100%")
.padding(10)
}
}
```
![en-us_image_0000001600119626](figures/en-us_image_0000001600119626.gif)
## Animating Polyline Changes with Custom Data Type and \@AnimatableExtend Decorator
```ts
declare type Point = [x: number, y: number];
// Define the parameter type of the animatable attribute API and implement the addition, subtraction, multiplication, and equivalence judgment functions in the AnimtableArithmetic<T> API.
class PointClass extends Array<number> {
constructor(value: Point) {
super(value[0], value[1])
}
add(rhs: PointClass): PointClass {
let result = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(rhs[i] + this[i])
}
return new PointClass(result);
}
subtract(rhs: PointClass): PointClass {
let result = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(this[i] - rhs[i]);
}
return new PointClass(result);
}
multiply(scale: number): PointClass {
let result = new Array<number>() as Point;
for (let i = 0; i < 2; i++) {
result.push(this[i] * scale)
}
return new PointClass(result);
}
}
// Define the parameter type of the animatable attribute API and implement the addition, subtraction, multiplication, and equivalence judgment functions in the AnimtableArithmetic<T> API.
// Template T supports nested implementation of the AnimtableArithmetic<T> type.
class PointVector extends Array<PointClass> implements AnimatableArithmetic<Array<Point>> {
constructor(initialValue: Array<Point>) {
super();
if (initialValue.length) {
initialValue.forEach(p => this.push(new PointClass(p)))
}
}
// implement the IAnimatableArithmetic interface
plus(rhs: PointVector): PointVector {
let result = new PointVector([]);
const len = Math.min(this.length, rhs.length)
for (let i = 0; i < len; i++) {
result.push(this[i].add(rhs[i]))
}
return result;
}
subtract(rhs: PointVector): PointVector {
let result = new PointVector([]);
const len = Math.min(this.length, rhs.length)
for (let i = 0; i < len; i++) {
result.push(this[i].subtract(rhs[i]))
}
return result;
}
multiply(scale: number): PointVector {
let result = new PointVector([]);
for (let i = 0; i < this.length; i++) {
result.push(this[i].multiply(scale))
}
return result;
}
equals(rhs: PointVector): boolean {
if (this.length !== rhs.length) {
return false;
}
for (let index = 0, size = this.length; index < size; ++index) {
if (this[index][0] !== rhs[index][0] || this[index][1] !== rhs[index][1]) {
return false;
}
}
return true;
}
}
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
// Define a custom animatable attribute API.
@AnimatableExtend(Polyline) function animatablePoints(points: PointVector) {
.points(points)
}
// Define a custom animatable attribute API.
@AnimatableExtend(Text) function animatableFontSize(size: number) {
.fontSize(size)
}
@Entry
@Component
struct AnimatedShape {
@State pointVec1: PointVector = new PointVector([
[50, randomInt(0, 200)],
[100, randomInt(0, 200)],
[150, randomInt(0, 200)],
[250, randomInt(0, 200)],
[350, randomInt(0, 200)]
]);
@State pointVec2: PointVector = new PointVector([
[70, randomInt(0, 200)],
[120, randomInt(0, 200)],
[180, randomInt(0, 200)],
[220, randomInt(0, 200)],
[320, randomInt(0, 200)]
]);
@State color: Color = Color.Green;
@State fontSize: number = 20.0;
@State polyline1Vec: PointVector = this.pointVec1;
@State polyline2Vec: PointVector = this.pointVec2;
build() {
Column() {
Text("AnimatableExtend test")
.width(400)
.height(30)
.margin(1)
.fontSize(25)
.textAlign(TextAlign.Center)
.backgroundColor("#ffee44")
.border({ width: '1vp', color: "#88ff00", radius: 20, style: BorderStyle.Solid })
Polyline()
.width(400)
.height(240)
.backgroundColor("#eeaacc")
.fill(this.color)
.stroke(Color.Red)
.animatablePoints(this.polyline1Vec)
.animation({ duration: 2000, delay: 0, curve: Curve.Ease })
Polyline()
.width(400)
.height(240)
.backgroundColor("#bbffcc")
.fill(this.color)
.stroke(Color.Red)
.animatablePoints(this.polyline2Vec)
.animation({ duration: 2000, delay: 0, curve: Curve.Ease })
Text("Animatable Fontsize")
.animatableFontSize(this.fontSize)
.animation({ duration: 2000, delay: 0, curve: Curve.Ease })
.width(400)
.height(150)
.margin(5)
.textAlign(TextAlign.Center)
.backgroundColor("#ffddcc")
.border({ width: '2vp', color: "#88ff00", radius: 20, style: BorderStyle.Solid })
.onClick(() => {
console.log("Text onClick()")
})
Row() {
Button("Polyline1 default")
.width(100).height(60)
.margin({ left: 5, right: 5 })
.onClick(() => {
if (this.polyline1Vec.equals(this.pointVec1)) {
this.polyline1Vec = this.pointVec2;
} else {
this.polyline1Vec = this.pointVec1;
}
})
Button("Polyline2 ANIM")
.width(100).height(60)
.onClick(() => {
if (this.polyline2Vec.equals(this.pointVec1)) {
this.polyline2Vec = this.pointVec2;
} else {
this.polyline2Vec = this.pointVec1;
}
})
Button("FontSize")
.width(100).height(60)
.margin({ left: 5, right: 5 })
.onClick(() => {
this.fontSize = (this.fontSize == 20.0) ? 40.0 : 20.0;
})
}
.alignItems(VerticalAlign.Center)
.margin(5)
}
.width('100%')
.alignItems(HorizontalAlign.Center)
}
}
```
![en-us_image_0000001592669598](figures/en-us_image_0000001592669598.gif)
# Enter/Exit Transition
You can use [transition](../reference/arkui-ts/ts-transition-animation-component.md), a basic component transition API, to animate the appearance and disappearance of a component. You can even use it with [TransitionEffect](../reference/arkui-ts/ts-transition-animation-component.md#transitioneffect10) to up your animation game.
**Table 1** Transition effect APIs
| API | Description| Animation|
| -------- | -------- | -------- |
| IDENTITY | Disables the transition effect.| None.|
| OPACITY | Applies the default opacity transition effect.| The component appears by changing the opacity from 0 to 1 and disappears by changing the opacity from 1 to 0.|
| SLIDE | Applies a sliding transition effect.| The component appears by sliding in from the left edge of the window and disappears by sliding out from the right edge of the window.|
| translate | Applies a translation transition effect.| The component appears by moving from the position set by the **translate** API to the default position (value **0**), and disappears by moving from the default position (value **0**) to the position set by the **translate** API.|
| rotate | Applies a rotation transition effect.| The component appears by rotating from the position set by the **rotate** API to the default position (value **0**), and disappears by rotating from the default position (value **0**) to the position set by the **rotate** API.|
| opacity | Applies an opacity transition effect.| The component appears by changing the opacity from the set value to **1** (default value) and disappears by changing the opacity from **1** to the set value.|
| move | Applies a transition effect by specifying which edge the component slides in and out of through [TransitionEdge](../reference/arkui-ts/ts-appendix-enums.md#transitionedge10).| The component appears by sliding in from the edge specified by **TransitionEdge** and disappears by sliding out of the same edge.|
| asymmetric | Applies an asymmetric transition effect.<br>**appear**: transition effect for appearance.<br>**disappear**: transition effect for disappearance.| The component appears by applying the transition effect specified by **appear** and disappears by applying the transition effect specified by **disappear**.|
| combine | Combines with other transition effects.| The component appears and disappears by combing with other transition effects.|
| animation | Defines the animation settings for the transition effect.<br>- If animation settings are not specified here, the animation settings of **animateTo** will be used.<br>- Animation settings cannot be configured through the **animation** API of the component.<br>- The **onFinish** callback of the **animation** parameter in **TransitionEffect** does not take effect. | The API call sequence is from top to bottom. This means that the **animation** settings of **TransitionEffect** at the upper level also take effect on **TransitionEffect** at the lower level .|
1. Create a **TransitionEffect** object.
```ts
// The component appears by applying all transition effects for appearance and disappears by applying all transition effects for disappearance.
// Define the animation settings for each transition effect.
private effect: TransitionEffect =
TransitionEffect.OPACITY // Apply an opacity transition effect. As the animation API is not called here, the animation settings of animateTo are used.
// Apply a scaling transition effect and specify springMotion (0.6, 1.2) as the curve.
.combine(TransitionEffect.scale({ x: 0, y: 0 }).animation({curve: curves.springMotion(0.6, 1.2) }))
// Apply a rotation transition effect, whose animation settings follow TransitionEffect above, that is, springMotion (0.6, 1.2).
.combine(TransitionEffect.rotate({ angle: 90 }))
// Apply a translation transition effect, whose animation settings follow TransitionEffect above, that is, springMotion (0.6, 1.2).
.combine(TransitionEffect.translate({ x: 150, y: 150 })
// Apply a move transition effect and specify springMotion as the curve.
.combine(TransitionEffect.move(TransitionEdge.END)).animation({curve: curves.springMotion()}))
// Apply an asymmetric transition effect. As the animation API is not called here, the animation settings follow TransitionEffect above, that is, springMotion.
.combine(TransitionEffect.asymmetric(TransitionEffect.scale({ x: 0, y: 0 }), TransitionEffect.rotate({angle: 90})));
```
2. Set the transition effects to the component by calling [transition](../reference/arkui-ts/ts-transition-animation-component.md).
```ts
Text('test')
.transition(effect)
```
3. Add or delete the component to trigger transition.
```ts
@state isPresent: boolean = true;
...
if (isPresent) {
Text('test')
.transition(effect)
}
...
// Control the addition or deletion of the component.
// Method 1: Place the control variable in the animateTo closure. In this case, the transition effect for which the animation API is not call will follow the animation settings of animateTo.
animateTo({curve: curves.springMotion()}) {
this.isPresent = false;
}
// Method 2: Directly delete or add the component. In this case, the transition effects follow the animation settings specified by animation.
this.isPresent = false;
```
Below is the complete sample code and effect.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct TransitionEffectDemo {
@State isPresent: boolean = false;
// Step 1: Create a TransitionEffect object.
private effect: TransitionEffect =
// Apply the default opacity transition effect and specify springMotion (0.6, 0.8) as the curve.
TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.8) })
// Combine with a scale transition effect, whose animation settings follow TransitionEffect above, that is, springMotion(0.6, 0.8).
.combine(TransitionEffect.scale({ x: 0, y: 0 }))
// Apply a rotation transition effect, whose animation settings follow TransitionEffect above, that is, springMotion(0.6, 0.8).
.combine(TransitionEffect.rotate({ angle: 90 }))
// Apply a translation transition effect, whose animation settings are specified by animation, which is springMotion().
.combine(TransitionEffect.translate({ y: 150 }).animation({ curve: curves.springMotion() }))
// Apply a movement transition effect, whose animation settings follow TransitionEffect above, that is, springMotion().
.combine(TransitionEffect.move(TransitionEdge.END))
build() {
Stack() {
if (this.isPresent) {
Column() {
Text('ArkUI')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width(150)
.height(150)
.borderRadius(10)
.backgroundColor(0xf56c6c)
// Step 2: Set the transition effects to the component through the transition API.
.transition(this.effect)
}
// Border
Column()
.width(155)
.height(155)
.border({
width: 5,
radius: 10,
color: Color.Black,
})
// Step 3: Add or delete the component to trigger transition. Control the addition or deletion of the component.
Button('Click')
.margin({ top: 320 })
.onClick(() => {
this.isPresent = !this.isPresent;
})
}
.width('100%')
.height('60%')
}
}
```
![en-us_image_0000001599818064](figures/en-us_image_0000001599818064.gif)
# Layout Update Animation
[Explicit animation](../reference/arkui-ts/ts-explicit-animation.md) (**animateTo**) and [attribute animation](../reference/arkui-ts/ts-animatorproperty.md) (**animation**) are the most basic and common animation features provided by ArkUI. When the layout attributes (such as the [size](../reference/arkui-ts/ts-universal-attributes-size.md) and [position](../reference/arkui-ts/ts-universal-attributes-location.md)) attributes change, you can use the attribute animation or explicit animation to transit to the new layout parameter status based on the animation parameters.
| Animation Type| Description |
| ---- | ---------------------------------------- |
| Explicit animation| Triggered by changes in a closure, including component addition and deletion caused by data changes and component attribute changes.| Complex animation scenarios|
| Attribute animation| Triggered when the attribute changes. The animation setting is simple. |
## Using Explicit Animation to Create Layout Update Animation
The API for explicit animation is as follows:
```ts
animateTo(value: AnimateParam, event: () => void): void
```
The first parameter specifies the animation parameter, and the second parameter is the closure function of the animation.
The following is an example of using explicit animation to create a layout update animation. In the example, when the **\<Column>** component's **alignItems** attribute is updated, the layout of its child components changes. As long as the attribute is updated in the closure function of **animateTo**, animation is performed as configured through **animateTo** for all changes caused by the attribute toward the end value.
```ts
@Entry
@Component
struct LayoutChange {
// Used to control the alignItems attribute of a column.
@State itemAlign: HorizontalAlign = HorizontalAlign.Start;
allAlign: HorizontalAlign[] = [HorizontalAlign.Start, HorizontalAlign.Center, HorizontalAlign.End];
alignIndex: number = 0;
build() {
Column() {
Column({ space: 10 }) {
Button("1").width(100).height(50)
Button("2").width(100).height(50)
Button("3").width(100).height(50)
}
.margin(20)
.alignItems(this.itemAlign)
.borderWidth(2)
.width("90%")
.height(200)
Button("click").onClick(() => {
// The animation duration is 1000 ms, and the curve is EaseInOut.
animateTo({ duration: 1000, curve: Curve.EaseInOut }, () => {
this.alignIndex = (this.alignIndex + 1) % this.allAlign.length;
// Modify the this.itemAlign parameter in the closure function to change the layout of child elements in the <Column> container. The animation for transition to the new position is applied.
this.itemAlign = this.allAlign[this.alignIndex];
});
})
}
.width("100%")
.height("100%")
}
}
```
![layoutChange1](figures/layoutChange1.gif)
In addition to directly changing the layout, you can also change the width, height, and position of a component.
```ts
@Entry
@Component
struct LayoutChange2 {
@State myWidth: number = 100;
@State myHeight: number = 50;
// Flag. true and false correspond to a group of myWidth and myHeight values, respectively.
@State flag: boolean = false;
build() {
Column({ space: 10 }) {
Button("text")
.type(ButtonType.Normal)
.width(this.myWidth)
.height(this.myHeight)
.margin(20)
Button("area: click me")
.fontSize(12)
.margin(20)
.onClick(() => {
animateTo({ duration: 1000, curve: Curve.Ease }, () => {
// In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated.
if (this.flag) {
this.myWidth = 100;
this.myHeight = 50;
} else {
this.myWidth = 200;
this.myHeight = 100;
}
this.flag = !this.flag;
});
})
}
.width("100%")
.height("100%")
}
}
```
In the click event of the second button, the **animateTo** API is used to modify the **this.myWidth** and **this.myHeight** state variables in the closure. As these two state variables set the width and height of the first button, the width and height animation is performed for the first button. The display effect is shown below.
![layoutChange2_animateTo](figures/layoutChange2_animateTo.gif)
At the same time, the second button also produces a position animation. After the width and height of the first button are changed, the layout of other components in the column is also changed, and the second button is among those other components.
If you do not want the second button to have an animation effect, you can use either of the following methods: 1. Add a container outside the first button so that the sizes before and after the animation are within the range of the container. In this way, the position of the second button is not affected by the position of the first button. The key code is as follows:
```ts
Column({ space: 10 }) {
Column() {
// The button is placed in a container that is large enough so that it does not affect the position of the outer component.
Button("text")
.type(ButtonType.Normal)
.width(this.myWidth)
.height(this.myHeight)
}
.margin(20)
.width(200)
.height(100)
Button("area: click me")
.fontSize(12)
.onClick(() => {
animateTo({ duration: 1000, curve: Curve.Ease }, () => {
// In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated.
if (this.flag) {
this.myWidth = 100;
this.myHeight = 50;
} else {
this.myWidth = 200;
this.myHeight = 100;
}
this.flag = !this.flag;
});
})
}
.width("100%")
.height("100%")
```
![layoutChange2_animateTo_change](figures/layoutChange2_animateTo_change.gif)
2. Add layout constraints to the second button. For example, add position constraints so that the position of the second button is not affected by the width and height of the first button. The sample code is as follows:
```ts
Column({ space: 10 }) {
Button("text")
.type(ButtonType.Normal)
.width(this.myWidth)
.height(this.myHeight)
.margin(20)
Button("area: click me")
.fontSize(12)
// Set the position attribute to a fixed value so that the position of the second button is not affected by the width and height of the first button.
.position({ x: "30%", y: 200 })
.onClick(() => {
animateTo({ duration: 1000, curve: Curve.Ease }, () => {
// In the animation closure, the state variables that control the width and height of the first button are changed based on the flag settings so that the width and height of the first button are animated.
if (this.flag) {
this.myWidth = 100;
this.myHeight = 50;
} else {
this.myWidth = 200;
this.myHeight = 100;
}
this.flag = !this.flag;
});
})
}
.width("100%")
.height("100%")
```
## Using Attribute Animation to Generate Layout Update Animation
Unlike explicit animation, which requires the attribute changes for triggering animation to be placed in the closure function, attribute animation does not need to use the closure. You only need to append the **animation** attribute to the target component attribute.
The API of the attribute animation is as follows:
```ts
animation(value: AnimateParam)
```
This API accepts an animation parameter as its argument. If you want the component to generate an animation with the value change of an attribute, add this attribute before the **animation** attribute. Otherwise, you can place the attribute after the **animation** attribute. The previous example of explicit animation can be easily implemented with attribute animation. The sample code is as follows:
```ts
@Entry
@Component
struct LayoutChange2 {
@State myWidth: number = 100;
@State myHeight: number = 50;
@State flag: boolean = false;
@State myColor: Color = Color.Blue;
build() {
Column({ space: 10 }) {
Button("text")
.type(ButtonType.Normal)
.width(this.myWidth)
.height(this.myHeight)
// The animation takes effect only for the type, width, and height attributes. The duration is 1000 ms, and the curve is Ease.
.animation({ duration: 1000, curve: Curve.Ease })
// The animation does not take effect for the backgroundColor and margin attributes.
.backgroundColor(this.myColor)
.margin(20)
Button("area: click me")
.fontSize(12)
.onClick(() => {
// Change the attribute value. Animation transition is performed for attributes configured with attribute animation.
if (this.flag) {
this.myWidth = 100;
this.myHeight = 50;
this.myColor = Color.Blue;
} else {
this.myWidth = 200;
this.myHeight = 100;
this.myColor = Color.Pink;
}
this.flag = !this.flag;
})
}
}
}
```
In the preceding example, the **animation** attribute of the first button takes effect only for the **type**, **width**, and **height** attributes written before the **animation** attribute, but does not take effect for the **backgroundColor** and **margin** attributes written after. In the running result, the **width** and **height** attributes execute the animation based on the **animation** settings, while the **backgroundColor** attribute changes without any animation applied. The display effect is shown below.
![size-change-animation](figures/size-change-animation.gif)
>**NOTE**
>
> 1. Attribute animations are executed according to the configured attribute animation settings. Each component can have its own attribute animation settings.
>
> 2. Explicit animations are executed on all GUI differences caused before and after animation closures, and they share the same animation settings. Therefore, explicit animations are applicable to scenarios where animations are executed in a unified manner. Explicit animations can also be used for animations caused by non-attribute variables, such as **if/else** statements and deletion of array elements used by **ForEach**.
>
> 3. If an attribute animation is configured for an attribute and the attribute value is changed in the explicit animation closure, the attribute animation takes precedence, under the configured animation settings.
# Modal Transition
Modal transition is a type of transition achieved by a modal – a view that appears on top of the current view while the current view remains.
**Table 1** Modal transition APIs
| API| Description| Usage|
| -------- | -------- | -------- |
| [bindContentCover](../reference/arkui-ts/ts-universal-attributes-modal-transition.md) | Binds a modal to the component.| Use this API to display a custom modal. It can work with the transition animation and shared element animation to implement complex transition animation effects, for example, displaying an image in full in the modal upon the click of a thumbnail.|
| [bindSheet](../reference/arkui-ts/ts-universal-attributes-sheet-transition.md) | Binds a sheet to the component.| Use this API to display a custom sheet, for example, a sharing confirmation dialog box.|
| [bindMenu](../reference/arkui-ts/ts-universal-attributes-menu.md) | Binds a menu to the component, which is displayed when the component is clicked.| Use this API where a menu is required, for example, for the plus sign (+), a common menu indicator in applications.|
| [bindContextMenu](../reference/arkui-ts/ts-universal-attributes-menu.md) | Binds a context menu to the component, which is displayed when the user long-presses or right-clicks the component.| Use this API for components that bounce up when long-pressed, for example, home screen icons.|
| [bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md) | Binds a popup to the component.| Use this API to display a popup containing additional information about a component when the component is clicked.|
| if | Adds or deletes the component.| Use this API to display a temporary page in a certain state. In this mode, the return navigation needs to be implemented with a listener.|
## Creating Modal Transition with bindContentCover
You can bind a full-screen modal to a component through the [bindContentCover](../reference/arkui-ts/ts-universal-attributes-modal-transition.md) attribute. Better yet, with the **ModalTransition** parameter, you can apply a transition effect for when the component is inserted or deleted.
1. Define [bindContentCover](../reference/arkui-ts/ts-universal-attributes-modal-transition.md).
2. Define the modal view.
```ts
// Use @Builder to build a modal view.
@Builder MyBuilder() {
Column() {
Text('my model view')
}
// Use the transition API to implement the transition animation for component appearance and disappearance. The transition API must be added to the first component of the builder.
.transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion(0.6, 0.8) }))
}
```
3. Call the modal API to display the modal. Implement an animation by using the animation or shared element transition APIs.
```ts
// Define the state variable to control the visibility of the modal.
@State isPresent: boolean = false;
Button('Click to present model view')
// Bind the modal to the component. ModalTransition indicates the transition mode of the modal. The value None means no transition animation for the modal.
.bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.None)
.onClick(() => {
// Change the state variable to display the modal.
this.isPresent = !this.isPresent;
})
```
Below is the complete sample code and effect.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct BindContentCoverDemo {
// Step 1: Define bindContentCover.
// Define the state variable to control the visibility of the modal.
@State isPresent: boolean = false;
// Step 2: Define the modal view.
// Use @Builder to build a modal view.
@Builder MyBuilder() {
Column() {
Column() {
Column() {
Text('back')
.fontSize(24)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width(100)
.height(100)
.borderRadius(5)
.backgroundColor(0xf56c6c)
.onClick(() => {
this.isPresent = false;
})
}
.height('100%')
.width('100%')
.backgroundColor(0x909399)
.justifyContent(FlexAlign.Center)
.border({
radius: {
topLeft: 15,
topRight: 15,
}
})
}
.height('100%')
.justifyContent(FlexAlign.End)
// Use the transition API to implement the transition animation for component appearance and disappearance.
.transition(TransitionEffect.translate({ y: 1000 }).animation({ curve: curves.springMotion(0.6, 0.8) }))
}
build() {
Column() {
Column() {
Text('Click Me')
.fontSize(24)
.fontColor(Color.White)
}
// Step 3: Call the modal API to display the modal. Implement an animation by using the animation or shared element transition APIs.
.onClick(() => {
// Change the state variable to display the modal.
this.isPresent = !this.isPresent;
})
// Bind the modal to the component. ModalTransition indicates the transition mode of the modal. The value None means no transition animation for the modal.
.bindContentCover($$this.isPresent, this.MyBuilder(), ModalTransition.DEFAULT)
.justifyContent(FlexAlign.Center)
.backgroundColor(0XF56C6C)
.width(100)
.height(100)
.borderRadius(5)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001646921957](figures/en-us_image_0000001646921957.gif)
## Creating Sheet Transition with bindSheet
You can bind a sheet to a component through the [bindSheet](../reference/arkui-ts/ts-universal-attributes-sheet-transition.md) attribute. You can also set the sheet to the preset or custom height for when the component is inserted. The process of creating a sheet transition is basically the same as that of creating a modal transition.
Below is the complete sample code and effect.
```ts
@Entry
@Component
struct BindSheetDemo {
// Define the state variable to control the sheet height.
@State sheetHeight: number = 300;
// Define the state variable to control the visibility of the drag bar.
@State showDragBar: boolean = true;
// Use @Builder to build a sheet view.
@Builder myBuilder() {
Column() {
Button("change height")
.margin(10)
.fontSize(20)
.onClick(() => {
this.sheetHeight = 500;
})
Button("Set Illegal height")
.margin(10)
.fontSize(20)
.onClick(() => {
this.sheetHeight = null;
})
Button("close dragbar")
.margin(10)
.fontSize(20)
.onClick(() => {
this.showDragBar = !this.showDragBar;
})
Button("close modal 1")
.margin(10)
.fontSize(20)
.onClick(() => {
this.isPresent = false;
})
}
.width('100%')
.height('100%')
}
// Define the state variable to control the visibility of the sheet.
@State isPresent: boolean = false;
build() {
Column() {
Button("Click to present sheet view")
.onClick(() => {
// Change the state variable to display the sheet.
this.isPresent = !this.isPresent;
})
.fontSize(20)
.margin(10)
// Bind the sheet to the component. You can specify the sheet height and whether to display the drag bar.
.bindSheet($$this.isPresent, this.myBuilder(), { height: this.sheetHeight, dragBar: this.showDragBar })
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001599977924](figures/en-us_image_0000001599977924.gif)
## Creating a Menu with bindMenu
You can bind a menu to component through the [bindMenu](../reference/arkui-ts/ts-universal-attributes-menu.md) attribute. The menu can then be triggered by clicking. Below is the complete sample code and effect.
```ts
@Entry
@Component
struct BindMenuDemo {
// Step 1: Define a data array to represent menu items.
private items = [
{
value:'Menu item 1',
action: () => {
console.info('handle Menu1 select')
}
},
{
value:'Menu item 2',
action: () => {
console.info('handle Menu2 select')
}
},
]
build() {
Column() {
Button('click')
.backgroundColor(0x409eff)
.borderRadius(5)
// Step 2: Bind the menu data to the component through bindMenu.
.bindMenu(this.items)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height(437)
}
}
```
![en-us_image_0000001599643478](figures/en-us_image_0000001599643478.gif)
## Creating a Context Menu with bindContextMenu
You can bind a context menu to component through the [bindContextMenu](../reference/arkui-ts/ts-universal-attributes-menu.md) attribute. The menu can then be triggered by long-pressing or right-clicking.
Below is the complete sample code and effect.
```ts
@Entry
@Component
struct BindContextMenuDemo {
private num: number[] = [1, 2, 3, 4];
private colors: Color[] = [0x67C23A, 0xE6A23C, 0xf56c6c, 0x909399];
// Use @Builder to build custom menu items.
@Builder MyMenu() {
Row() {
Column() {
ForEach(this.num, (item: number, index: number) => {
Row() {
Text(item.toString())
.fontSize(20)
.fontColor(Color.White)
}
.backgroundColor(this.colors[index])
.width('100%')
.aspectRatio(2)
.justifyContent(FlexAlign.Center)
})
}
.width('100%')
}
.width(150)
.justifyContent(FlexAlign.Center)
.padding(5)
}
build() {
Column() {
Column() {
Text('longPress')
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width(170)
.height(50)
.bindContextMenu(this.MyMenu, ResponseType.LongPress)
.backgroundColor(0xf56c6c)
.borderRadius(5)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height(437)
}
}
```
![en-us_image_0000001600137920](figures/en-us_image_0000001600137920.gif)
## Creating a Popup with bindPopUp
You can bind a popup to a component through the [bindpopup](../reference/arkui-ts/ts-universal-attributes-popup.md) attribute, specifying its content, interaction logic, and display status.
Below is the complete sample code and effect.
```ts
@Entry
@Component
struct BindPopupDemo {
// Step 1: Define the state variable to control the visibility of the popup.
@State customPopup: boolean = false;
// Step 2: Use @Builder to build a custom popup.
@Builder popupBuilder() {
Column({ space: 2 }) {
Row().width(64)
.height(64)
.backgroundColor(0x409eff)
Text('Popup')
.fontSize(10)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.SpaceAround)
.width(100)
.height(100)
.padding(5)
}
build() {
Column() {
Button('click')
// Step 4: Add a click event to control the visibility of the popup.
.onClick(() => {
this.customPopup = !this.customPopup;
})
.backgroundColor(0xf56c6c)
// Step 5: Bind the popup to the component through bindPopup.
.bindPopup(this.customPopup, {
builder: this.popupBuilder,
placement: Placement.Top,
maskColor: 0x33000000,
popupColor: 0xf56c6c,
enableArrow: true,
onStateChange: (e) => {
if (!e.isVisible) {
this.customPopup = false;
}
}
})
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height(437)
}
}
```
![en-us_image_0000001649282285](figures/en-us_image_0000001649282285.gif)
## Creating Modal Transition with if
In addition to the preceding modal transition APIs, you can also use the **if** syntax to create a modal transition, eliminating the need for binding to the component and listening for state variable changes.
Below is the complete sample code and effect.
```ts
@Entry
@Component
struct ModalTransition1 {
// Step 1: Define a state variable to control page display.
@State isShow: boolean = false;
build() {
// Step 2: Define a stack layout to display the current view and modal view.
Stack() {
Column() {
Text('Page1')
.fontSize(40)
.fontColor(Color.White)
.fontWeight(FontWeight.Bolder)
Text('Click to transition')
.fontSize(15)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
.linearGradient({
colors: [
[0xf56c6c, 0.0],
[0xffffff, 1.0]
]
})
// Step 3: Change the state variable to display the modal view.
.onClick(() => {
animateTo({ duration: 500 }, () => {
this.isShow = !this.isShow;
})
})
// Step 4: Define the modal view in if and display it at the top layer. Use if to control the appearance and disappearance of the modal view.
if (this.isShow) {
Column() {
Text('Page2')
.fontSize(40)
.fontColor(Color.Gray)
.fontWeight(FontWeight.Bolder)
Text('Click to transition')
.fontSize(15)
.fontColor(Color.Gray)
}
.justifyContent(FlexAlign.Start)
.width('100%')
.height('100%')
.linearGradient({
colors: [
[0xffffff, 0.0],
[0x409eff, 1.0]
]
})
// Step 5: Define the mode in which the modal view disappears.
.transition(TransitionEffect.OPACITY.combine(TransitionEffect.rotate({ angle: 90, y: 1 })))
.onClick(() => {
animateTo({ duration: 500 }, () => {
this.isShow = !this.isShow;
})
})
}
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001597792146](figures/en-us_image_0000001597792146.gif)
...@@ -143,6 +143,7 @@ Tabs({ barPosition: BarPosition.Start }) { ...@@ -143,6 +143,7 @@ Tabs({ barPosition: BarPosition.Start }) {
## Restricting the Scrolling of the Navigation Bar ## Restricting the Scrolling of the Navigation Bar
By default, the navigation bar is scrollable. On some pages that require multi-level classification of content, for example, when both bottom navigation and top navigation are used, the scroll effect of the bottom navigation bar may conflict with that of the top navigation bar. In this case, the scrolling of the bottom navigation bar needs to be restricted to improve user experience. By default, the navigation bar is scrollable. On some pages that require multi-level classification of content, for example, when both bottom navigation and top navigation are used, the scroll effect of the bottom navigation bar may conflict with that of the top navigation bar. In this case, the scrolling of the bottom navigation bar needs to be restricted to improve user experience.
**Figure 6** Restricting the scrolling of the bottom navigation bar **Figure 6** Restricting the scrolling of the bottom navigation bar
![restricted-navigation](figures/restricted-navigation.gif) ![restricted-navigation](figures/restricted-navigation.gif)
...@@ -270,7 +271,7 @@ TabContent() { ...@@ -270,7 +271,7 @@ TabContent() {
## Switching to a Specified Tab ## Switching to a Specified Tab
Non-custom navigation bars follow the default system switching logic. If you are using a custom navigation bar, you must manually implement the logic for switching tabs so that when the user touches a tab, the application displays the corresponding tab page. Non-custom navigation bars follow the default system switching logic. If you are using a custom navigation bar, you must manually implement the logic for switching tabs so that when the user switches to a tab, the application displays the corresponding tab page.
**Figure 10** Switching to a specified tab in a custom navigation bar **Figure 10** Switching to a specified tab in a custom navigation bar
......
# Navigation Transition
Navigation transition is a transition animation that runs during the navigation from one view to another. The animation settings of the navigation transition are pre-defined and cannot be modified.
To implement the navigation transition, you are advised to use the [\<Navigation>](../reference/arkui-ts/ts-basic-components-navigation.md) component, complete with the [\<NavRouter>](../reference/arkui-ts/ts-basic-components-navrouter.md) and [\<NavDestination>](../reference/arkui-ts/ts-basic-components-navdestination.md) components.
Below is the complete sample code and effect.
```ts
@Entry
@Component
struct NavigationDemo {
private listArray: Array<number> = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
// Set the title bar menu, if a title bar is involved.
@Builder NavigationMenus() {
Column() {
Text('menu')
.fontColor('#182431')
.fontSize(14)
.lineHeight(19)
.opacity(0.4)
.margin({ top: 70 })
}
.alignItems(HorizontalAlign.Start)
}
build() {
Stack() {
Column() {
// Define the <Navigation> component, setting the display mode and title.
Navigation() {
// An <Input> component is defined here.
TextInput({ placeholder: 'search...' })
.width('90%')
.height(40)
.backgroundColor('#ededed')
.margin({ bottom: 10 })
// Define the level-1 navigation view through <List>.
List({ space: 12, initialIndex: 0 }) {
ForEach(this.listArray, (item) => {
ListItem() {
// Define the navigation transition through <NavRouter> and define the navigation destination through <NavDestination>. Parameters are transferred between views through state variables or regular variables between components.
// <NavRouter> must contain two child components. The first child component is the level-1 navigation view, and the second child component must be <NavDestination>, which specifies the navigation destination.
NavRouter() {
// First component: Level-1 navigation view.
Row() {
Row()
.width(40)
.height(40)
.backgroundColor('#a8a8a8')
.margin({ right: 12 })
.borderRadius(20)
Column() {
Text('Level-1 item')
.fontSize(16)
.lineHeight(21)
.fontWeight(FontWeight.Medium)
Text('Click to go to subitems')
.fontSize(13)
.lineHeight(21)
.fontColor('#a8a8a8')
}
.alignItems(HorizontalAlign.Start)
Blank()
Row()
.width(15)
.height(15)
.margin({ right: 12 })
.border({
width: { top: 2, right: 2 },
color: 0xcccccc
})
.rotate({ angle: 45 })
}
.borderRadius(15)
.shadow({ radius: 100, color: '#ededed' })
.width('90%')
.alignItems(VerticalAlign.Center)
.padding({ left: 16, top: 12, bottom: 12 })
.height(80)
// Second component: navigation destination
NavDestination() {
// Content of the destination view, which is generally a custom component.
Column() {
Text("Destination"+ item +" content ")
.fontSize(20)
.fontColor(Color.Black)
.textAlign(TextAlign.Center)
.width('100%')
.height('100%')
}
.width('100%')
.height('100%')
.backgroundColor(0xf5f5f5)
}
.title('Destination page') // Title of the level-2 page.
}
}
.width('100%')
}, item => item)
}
.listDirection(Axis.Vertical)
.edgeEffect(EdgeEffect.Spring)
.sticky(StickyStyle.Header)
.chainAnimation(false)
.borderRadius(15)
.width('100%')
.height('100%')
}
.width('100%')
.mode(NavigationMode.Auto) // Set the display mode of the navigation bar to Auto.
.title('Navigation transition') // Set the title text.
.titleMode(NavigationTitleMode.Full) // Set the display mode of the page title bar.
.menus(this.NavigationMenus) // Set the title bar menu.
}
.width('100%')
}
}
}
```
![en-us_image_0000001588458252](figures/en-us_image_0000001588458252.gif)
# Page Transition Animation
During page redirection, one page disappears and the other page appears. You can customize the [page transition effects](../reference/arkui-ts/ts-page-transition-animation.md) for these pages through the **pageTransition** API. Specifically, **PageTransitionEnter** defines the page entrance animation, while **PageTransitionExit** defines the page exit animation.
API of **PageTransitionEnter**:
```ts
PageTransitionEnter({type?: RouteType,duration?: number,curve?: Curve | string,delay?: number})
```
API of **PageTransitionExit**:
```ts
PageTransitionExit({type?: RouteType,duration?: number,curve?: Curve | string,delay?: number})
```
Both **PageTransitionEnter** and **PageTransitionExit** contain the **slide**, **translate**, **scale**, and **opacity** attributes. For **PageTransitionEnter**, these attributes indicate the start values for page entrance. For **PageTransitionExit**, these attributes indicate the end values for page exit. In this sense, configuration of page transition is similar to that of component transition. **PageTransitionEnter** provides the **onEnter** callback, and **PageTransitionExit** provides the **onExit** callback.
In the preceding APIs, the **type** parameter indicates the route type used in page navigation. Each page transition involves exit of one page and entrance of the other. If you switch from page A to page B through the **router.pushUrl** operation, page A exits, with the exit animation applied; and page B enters, with the entrance animation applied. If you switch from page B back to page A through the **router.back** operation, page B exits, , with the exit animation applied; and page A enters, with the entrance animation applied. That is, **PageTransitionEnter** of a page may be an entrance animation of a new page (pushed to the stack) or of an existing page (popped from the stack). To distinguish these two types of entrance animations, the **type** parameter is provided.
## Setting type to RouteType.None
When **type** is set to **RouteType.None** (default value), the page transition animations work for both the push and pop operations in the page stack.
```ts
// pageA
pageTransition() {
// Configure the page entrance animation to sliding in from the left, with the duration of 1200 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.None, duration: 1200 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the left, with the duration of 1000 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.None, duration: 1000 })
.slide(SlideEffect.Left)
}
```
```ts
// pageB
pageTransition() {
// Configure the page entrance animation to sliding in from the right, with the duration of 1000 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.None, duration: 1000 })
.slide(SlideEffect.Right)
// Configure the page exit animation to sliding out from the right, with the duration of 1200 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.None, duration: 1200 })
.slide(SlideEffect.Right)
}
```
Assume that the page stack is in the multi-instance mode, that is, duplicate pages are allowed in the page stack. There may be four scenarios. The following table lists the page transition effects.
| Route Operation | Page A Transition Effect | Page B Transition Effect |
| ---------------------------- | ---------------------------------- | ---------------------------------- |
| **router.pushUrl** – redirection from page A to new page B.| The page exits. The animation defined by **PageTransitionExit** is applied. In the example, the page slides out from the left of the screen. | The page enters. The animation defined by **PageTransitionEnter** is applied. In the example, the page slides in from the right of the screen.|
| **router.back** – redirection from page B back to page A. | The page enters. The animation defined by **PageTransitionEnter** is applied. In the example, the page slides in from the left of the screen.| The page exits. The animation defined by **PageTransitionExit** is applied. In the example, the page slides out from the right of the screen. |
| **router.pushUrl** – redirection from page B to new page A.| The page enters. The animation defined by **PageTransitionEnter** is applied. In the example, the page slides in from the left of the screen.| The page exits. The animation defined by **PageTransitionExit** is applied. In the example, the page slides out from the right of the screen. |
| **router.back** – redirection from page A back to page B. | The page exits. The animation defined by **PageTransitionExit** is applied. In the example, the page slides out from the left of the screen. | The page enters. The animation defined by **PageTransitionEnter** is applied. In the example, the page slides in from the right of the screen.|
If you want the page accessed by **router.pushUrl** to always slide in from the right and the page exited by **router.back** to always slide out from the right, the third and fourth cases in the preceding table do not meet the requirements. In this case, you need to define four page transition effects.
## Setting type to RouteType.Push or RouteType.Pop
When **type** is set to **RouteType.Push**, the page transition animations work for only both the push operations in the page stack. When **type** is set to **RouteType.Pop**, the page transition animations work for only both the pop operations in the page stack.
```ts
// pageA
pageTransition() {
// Configure the page entrance animation to sliding in from the right, with the duration of 1200 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Push, duration: 1200 })
.slide(SlideEffect.Right)
// Configure the page entrance animation to sliding in from the left, with the duration of 1200 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Pop, duration: 1200 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the left, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the right, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Right)
}
```
```ts
// pageB
pageTransition() {
// Configure the page entrance animation to sliding in from the right, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Right)
// Configure the page entrance animation to sliding in from the left, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the left, with the duration of 1200 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Push, duration: 1200 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the right, with the duration of 1200 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Pop, duration: 1200 })
.slide(SlideEffect.Right)
}
```
The preceding code defines page transition effects for all possibles scenarios. Assume that the page stack is in the multi-instance mode, that is, duplicate pages are allowed in the page stack. There may be four scenarios. The following table lists the page transition effects.
| Route Operation | Page A Transition Effect | Page B Transition Effect |
| ---------------------------- | ---------------------------------------- | ---------------------------------------- |
| **router.pushUrl** – redirection from page A to new page B.| The page exits. The transition style of **PageTransitionExit** whose **type** is **RouteType.Push** takes effect. The page slides out from the left of the screen.| The page enters. The transition style of **PageTransitionEnter** whose **type** is **RouteType.Push** takes effect. The page slides in from the right of the screen.|
| **router.back** – redirection from page B back to page A. | The page enters. The transition style of **PageTransitionEnter** whose **type** is **RouteType.Pop** takes effect. The page slides in from the left of the screen.| The page exits. The transition style of **PageTransitionExit** whose **type** is **RouteType.Pop** takes effect. The page slides out from the right of the screen.|
| **router.pushUrl** – redirection from page B to new page A.| The page enters. The transition style of **PageTransitionEnter** whose **type** is **RouteType.Push** takes effect. The page slides in from the right of the screen.| The page exits. The transition style of **PageTransitionExit** whose **type** is **RouteType.Push** takes effect. The page slides out from the left of the screen.|
| **router.back** – redirection from page A back to page B. | The page exits. The transition style of **PageTransitionExit** whose **type** is **RouteType.Pop** takes effect. The page slides out from the right of the screen.| The page enters. The transition style of **PageTransitionEnter** whose **type** is **RouteType.Pop** takes effect. The page slides in from the left of the screen.|
>**NOTE**
>
> 1. The transition style of each page can be independently configured. However, as each transition involves two pages, take into account the smoothness between page transitions, for example, the transition duration.
>
> 2. If no page transition style is defined, a page uses the default page transition style.
## Disabling Page Transition
```ts
pageTransition() {
PageTransitionEnter({ type: RouteType.None, duration: 0 })
PageTransitionExit({ type: RouteType.None, duration: 0 })
}
```
You can disable the transition animation of a page by setting the page transition duration to 0.
## Example
In the following example, page transition animations are defined for all four page transition scenarios.
```ts
// PageTransitionSrc1
import router from '@ohos.router';
@Entry
@Component
struct PageTransitionSrc1 {
build() {
Column() {
Image($r('app.media.mountain'))
.width('90%')
.height('80%')
.objectFit(ImageFit.Fill)
.syncLoad(true) // Load the image synchronously so that the image has been loaded when the page is displayed.
.margin(30)
Row({ space: 10 }) {
Button("pushUrl")
.onClick(() => {
// Navigate to the next page, which is a push operation.
router.pushUrl({ url: 'pages/myTest/PageTransitionDst1' });
})
Button("back")
.onClick(() => {
// Return to the previous page, which is equivalent to the pop operation.
router.back();
})
}.justifyContent(FlexAlign.Center)
}
.width("100%").height("100%")
.alignItems(HorizontalAlign.Center)
}
pageTransition() {
// Configure the page entrance animation to sliding in from the right, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Right)
// Configure the page entrance animation to sliding in from the left, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the left, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the right, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Right)
}
}
```
```ts
// PageTransitionDst1
import router from '@ohos.router';
@Entry
@Component
struct PageTransitionDst1 {
build() {
Column() {
Image($r('app.media.forest'))
.width('90%')
.height('80%')
.objectFit(ImageFit.Fill)
.syncLoad(true) // Load the image synchronously so that the image has been loaded when the page is displayed.
.margin(30)
Row({ space: 10 }) {
Button("pushUrl")
.onClick(() => {
// Navigate to the next page, which is a push operation.
router.pushUrl({ url: 'pages/myTest/PageTransitionSrc1' });
})
Button("back")
.onClick(() => {
// Return to the previous page, which is equivalent to the pop operation.
router.back();
})
}.justifyContent(FlexAlign.Center)
}
.width("100%").height("100%")
.alignItems(HorizontalAlign.Center)
}
pageTransition() {
// Configure the page entrance animation to sliding in from the right, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Right)
// Configure the page entrance animation to sliding in from the left, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionEnter({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the left, with the duration of 1000 ms. The settings take effect only when the push operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Push, duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to sliding out from the right, with the duration of 1000 ms. The settings take effect only when the pop operation is performed on the page stack.
PageTransitionExit({ type: RouteType.Pop, duration: 1000 })
.slide(SlideEffect.Right)
}
}
```
![pageTransition_PushPop](figures/pageTransition_PushPop.gif)
In the following example, **type** is set to **RouteType.None**.
```ts
// PageTransitionSrc2
import router from '@ohos.router';
@Entry
@Component
struct PageTransitionSrc2 {
build() {
Column() {
Image($r('app.media.mountain'))
.width('90%')
.height('80%')
.objectFit(ImageFit.Fill)
.syncLoad(true) // Load the image synchronously so that the image has been loaded when the page is displayed.
.margin(30)
Row({ space: 10 }) {
Button("pushUrl")
.onClick(() => {
// Navigate to the next page, which is a push operation.
router.pushUrl({ url: 'pages/myTest/pageTransitionDst2' });
})
Button("back")
.onClick(() => {
// Return to the previous page, which is equivalent to the pop operation.
router.back();
})
}.justifyContent(FlexAlign.Center)
}
.width("100%").height("100%")
.alignItems(HorizontalAlign.Center)
}
pageTransition() {
// Configure the page entrance animation to sliding in from the left, with the duration of 1000 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionEnter({ duration: 1000 })
.slide(SlideEffect.Left)
// Configure the page exit animation to translating by 100 vp along the x- and y-axes and changing the opacity to 0, with the duration of 1200 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionExit({ duration: 1200 })
.translate({ x: 100.0, y: 100.0 })
.opacity(0)
}
}
```
```ts
// PageTransitionDst2
import router from '@ohos.router';
@Entry
@Component
struct PageTransitionDst2 {
build() {
Column() {
Image($r('app.media.forest'))
.width('90%')
.height('80%')
.objectFit(ImageFit.Fill)
.syncLoad(true) // Load the image synchronously so that the image has been loaded when the page is displayed.
.margin(30)
Row({ space: 10 }) {
Button("pushUrl")
.onClick(() => {
// Navigate to the next page, which is a push operation.
router.pushUrl({ url: 'pages/myTest/pageTransitionSrc2' });
})
Button("back")
.onClick(() => {
// Return to the previous page, which is equivalent to the pop operation.
router.back();
})
}.justifyContent(FlexAlign.Center)
}
.width("100%").height("100%")
.alignItems(HorizontalAlign.Center)
}
pageTransition() {
// Configure the page entrance animation to sliding in from the left, with the duration of 1200 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionEnter({ duration: 1200 })
.slide(SlideEffect.Left)
// Configure the page exit animation to translating by 100 vp along the x- and y-axes and changing the opacity to 0, with the duration of 1000 ms. The settings take effect no matter whether the push or pop operation is performed on the page stack.
PageTransitionExit({ duration: 1000 })
.translate({ x: 100.0, y: 100.0 })
.opacity(0)
}
}
```
![pageTransition_None](figures/pageTransition_None.gif)
# Shadow Effect
You can use the [shadow](../reference/arkui-ts/ts-universal-attributes-image-effect.md) API to apply a shadow effect to a component. Even better, you can set the parameter of this API to [ShadowOptions](../reference/arkui-ts/ts-universal-attributes-image-effect.md#shadowoptions) to customize the shadow effect. When the radius or color opacity in **ShadowOptions** is set to **0**, there is no shadow effect.
```ts
@Entry
@Component
struct ShadowOptionDemo {
build() {
Row() {
Column() {
Column() {
Text('shadowOption').fontSize(12)
}
.width(100)
.aspectRatio(1)
.margin(10)
.justifyContent(FlexAlign.Center)
.backgroundColor(Color.White)
.borderRadius(20)
.shadow({ radius: 10, color: Color.Gray })
Column() {
Text('shadowOption').fontSize(12)
}
.width(100)
.aspectRatio(1)
.margin(10)
.justifyContent(FlexAlign.Center)
.backgroundColor('#a8a888')
.borderRadius(20)
.shadow({ radius: 10, color: Color.Gray, offsetX: 20, offsetY: 20 })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.height('100%')
}
}
```
![en-us_image_0000001598502322](figures/en-us_image_0000001598502322.png)
# Shared Element Transition
Shared element transition is a type of transition achieved by animating the size and position between styles of the same or similar elements during page switching. It is typically used with the modal transition for combined effects. When used with transition and attribute animations, it can make its way into a wider range of use cases.
## Implementation with transition and Attribute Animation
This example implements a shared element transition for the scenario where, as a component is expanded, sibling components in the same container disappear or appear. Specifically, attribute animations are applied to width and height changes of a component before and after the expansion; enter/exit animations are applied to the sibling components as they disappear or disappear.
1. Build the component to be expanded, and build two pages for it through state variables: one for the normal state and one for the expanded state.
```ts
// Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
@Component
export struct MyExtendView {
// Declare the isExpand variable to be synced with the parent component.
@Link isExpand: boolean;
@State cardList: Array<CardData> = xxxx;
build() {
List() {
// Customize the expanded component as required.
if (this.isExpand) {
Text('expand')
.transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion(0.6, 0.8) }))
}
ForEach(this.cardList, (item: CradData) => {
MyCard({ cardData: item })
})
}
.width(this.isExpand ? 200 : 500) // Define the attributes of the expanded component.
.animation({ curve: curves.springMotion()}) // Bind an animation to component attributes.
}
}
```
2. Expand the component to be expanded. Use state variables to control the disappearance or appearance of sibling components, and apply the enter/exit transition to the disappearance and appearance.
```ts
@State isExpand: boolean = false
...
List() {
// Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
if (!this.isExpand) {
Text ('I appear in normal state')
.transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion(0.6, 0.9) }))
}
MyExtendView({ isExpand: $isExpand })
.onClick(() => {
this.isExpand = !this.isExpand;
})
// Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
if (this.isExpand) {
Text ('I appear in expanded state')
.transition(TransitionEffect.translate(y:300).animation({ curve: curves.springMotion() }))
}
}
...
```
Below is the complete sample code and effect.
```ts
// utils.ets
import curves from '@ohos.curves';
// Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
@Component
export struct share_transition_expand {
// Declare the isExpand variable to be synced with the parent component.
// Expand the component.
@Link isExpand: boolean;
// Currently expanded component.
@State curIndex: number = 0;
private listArray: Array<number> = [1, 2, 3, 4, 5, 6];
build() {
Column() {
List() {
ForEach(this.listArray, (item, index) => {
// Customize the expanded component as required.
if (!this.isExpand || this.curIndex == index) {
ListItem() {
Column() {
Row() {
Row()
.backgroundColor(Color.Pink)
.borderRadius(20)
.width(80)
.height(80)
Column() {
Text ('Click to expand Item' + item)
.fontSize(20)
Text ('Shared element transition')
.fontSize(12)
.fontColor(0x909399)
}
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.SpaceAround)
.margin({ left: 10 })
.height(80)
}
.width('90%')
.height(100)
if (this.isExpand) {
Row() {
Text('Expanded state')
.fontSize(28)
.fontColor(0x909399)
.textAlign(TextAlign.Center)
.transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.9) }))
}
.width('90%')
.justifyContent(FlexAlign.Center)
}
}
.onClick(() => {
// Define the animation parameters for expanding and collapsing.
animateTo({ curve: curves.springMotion(0.6, 0.9) }, () => {
this.curIndex = index;
this.isExpand = !this.isExpand;
})
})
.width('90%')
.height(this.isExpand && this.curIndex == index ? '85%' : 100) // Define the attributes of the expanded component as required.
.alignItems(HorizontalAlign.Center)
.borderRadius(10)
.margin({ top: 15 })
.backgroundColor(Color.White)
.shadow({ radius: 20, color: 0x909399, offsetX: 20, offsetY: 10 })
// Control the appearance or disappearance of sibling components through the isExpand variable, and configure the enter/exit transition.
.transition(TransitionEffect.scale({ x: 0, y: 0 }).animation({ curve: curves.springMotion(0.3, 1.5) }))
}
.zIndex(this.curIndex == index ? 1 : 0)
}
})
}
.height('100%')
.alignListItem(ListItemAlign.Center)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
}
}
```
```ts
// Index.ets
import { share_transition_expand } from './utils';
@Entry
@Component
struct ShareTransitionDemo {
@State isExpand: boolean = false;
build() {
Column() {
Text('Sibling nodes appear and disappear.')
.fontWeight(FontWeight.Bold)
.fontSize(30)
.fontColor(Color.Black)
.margin(10)
share_transition_expand({ isExpand: $isExpand })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
}
}
```
![en-us_image_0000001600653160](figures/en-us_image_0000001600653160.gif)
## Implementation with transition and zIndex
This example implements a shared element transition for the scenario where, as a component is expanded, it is displayed on the top of the container while sibling components in the same container stay. This is achieved with the use of **zIndex**. Specifically:
- Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
- Change the display level of components through the **zIndex** attribute. Set this attribute to **1** for the component in the expanded state and retain the default value **0** for other sibling components. In this way, the component in the expanded state will be displayed over the sibling components.
- With the **translate** attribute, move the component to the top of the parent container when it is expanded.
- Use a placeholder container so that the location of the sibling components remains unchanged. The outer container is placed as a placeholder, and the internal container changes the size.
Below is the complete sample code and effect.
```ts
// utils.ets
import curves from '@ohos.curves';
// Build two pages for the normal and expanded states of the same component, which are then used based on the declared state variables.
@Component
export struct share_zIndex_expand {
// Declare the isExpand variable to be synced with the parent component.
@Link isExpand: boolean;
@Link curIndex: number;
@State listArray: Array<number> = [1, 2, 3, 4, 5, 6];
private parentScroller: Scroller; // Upper-layer scroller controller.
build() {
Column() {
List() {
ForEach(this.listArray, (item, index) => {
// Customize the expanded component as required.
if (!this.isExpand || this.curIndex == index) {
ListItem() {
Column() {
Row() {
Row()
.backgroundColor(Color.Pink)
.borderRadius(20)
.width(80)
.height(80)
Column() {
Text ('Click to expand Item' + item)
.fontSize(20)
Text ('Shared element transition')
.fontSize(12)
.fontColor(0x909399)
}
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.SpaceAround)
.margin({ left: 10 })
.height(80)
}
.width('90%')
.height(100)
if (this.isExpand && this.curIndex == index) {
Row() {
Text('Expanded state')
.fontSize(28)
.fontColor(0x909399)
.textAlign(TextAlign.Center)
.transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 0.9) }))
}
.width('90%')
.justifyContent(FlexAlign.Center)
}
}
.width('90%')
.height(this.isExpand && this.curIndex == index ? 750 : 100)
.alignItems(HorizontalAlign.Center)
.borderRadius(10)
.margin({ top: 15 })
.backgroundColor(Color.White)
.shadow({ radius: 20, color: 0x909399, offsetX: 20, offsetY: 10 })
}
.onClick(() => {
// Define the animation parameters for expanding and collapsing.
animateTo({ curve: curves.springMotion(0.6, 0.9) }, () => {
this.curIndex = index;
this.isExpand = !this.isExpand;
})
})
.zIndex(this.curIndex == index? 1: 0) // When the current list item is selected, its zIndex attribute is set to 1, and it is displayed over other sibling components whose zIndex is 0.
.translate({ // Move the list item to the top of the parent container through translate.
y: this.isExpand && this.curIndex == index ? -60 - this.parentScroller.currentOffset()['yOffset'] : 0
})
}
})
}
.clip(false)
.height('100%') // Fixed size of the placeholder container.
.alignListItem(ListItemAlign.Center)
}
.zIndex(1)
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
}
}
```
```ts
// Index.ets
import { share_zIndex_expand } from './utils'
@Entry
@Component
struct ShareZIndexDemo {
@State isExpand: boolean = false;
@State curIndex: number = 0;
scroller: Scroller = new Scroller();
build() {
Scroll(this.scroller) {
Column() {
Text ('zIndex changes z-axis')
.fontWeight(FontWeight.Bold)
.fontSize(30)
.fontColor(Color.Black)
.zIndex(0)
.margin(10)
share_zIndex_expand({ isExpand: $isExpand, curIndex: $curIndex, parentScroller: this.scroller })
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
}
}
}
```
![en-us_image_0000001600332176](figures/en-us_image_0000001600332176.gif)
## Implementation with geometryTransition
This example implements a shared element transition with [geometryTransition](../reference/arkui-ts/ts-transition-animation-geometrytransition.md), which is used for implicit shared element transitions during component switching.
Below is the complete sample code and effect for using **geometryTransition** and the **if/else** syntax to implement a shared element transition:
```ts
@Entry
@Component
struct IfElseGeometryTransition {
@State isShow: boolean = false;
build() {
Stack({ alignContent: Alignment.Center }) {
if (this.isShow) {
Image($r('app.media.test'))
.autoResize(false)
.clip(true)
.width(300)
.height(400)
.offset({ y: 100 })
.geometryTransition("picture")
.transition(TransitionEffect.OPACITY)
} else {
// geometryTransition is bound to a container. Therefore, a relative layout must be configured for the child components of the container.
// The multiple levels of containers here are used to demonstrate passing of relative layout constraints.
Column() {
Column() {
Image($r('app.media.icon'))
.width('100%').height('100%')
}.width('100%').height('100%')
}
.width(80)
.height(80)
// geometryTransition synchronizes rounded corner settings, but only for the bound component, which is the container in this example.
// In other words, rounded corner settings of the container are synchronized, and those of the child components are not.
.borderRadius(20)
.clip(true)
.geometryTransition("picture")
// transition ensures that the component is not destructed immediately when it exits. You can customize the transition effect.
.transition(TransitionEffect.OPACITY)
}
}
.onClick(() => {
animateTo({ duration: 1000 }, () => {
this.isShow = !this.isShow;
})
})
}
}
```
![en-us_image_0000001599644878](figures/en-us_image_0000001599644878.gif)
Below is the sample code and effect for using **geometryTransition** and a modal transition API to implement a shared element transition:
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct GeometryTransitionDemo {
// Define the state variable used to control modal transition.
@State isPresent: boolean = false;
// Use @Builder to build the modal.
@Builder
MyBuilder() {
Column() {
Text(this.isPresent ? 'Page 2' : 'Page 1')
.fontWeight(FontWeight.Bold)
.fontSize(30)
.fontColor(Color.Black)
.margin(20)
Row() {
Text('Shared component 1')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.backgroundColor(0xf56c6c)
.width('100%')
.aspectRatio(1)
.margin({ bottom: 20 })
// New shared element, <Row, whose ID is share1.
.geometryTransition('share1')
Column() {
Text ('Expanded page')
.textAlign(TextAlign.Center)
.fontSize(15)
.fontColor(this.isPresent ? Color.White : Color.Transparent)
.margin(20)
Text('Click anywhere to return')
.textAlign(TextAlign.Center)
.fontSize(15)
.fontColor(this.isPresent ? Color.White : Color.Transparent)
}
.width('100%')
.transition(TransitionEffect.OPACITY.animation({ curve: curves.springMotion(0.6, 1.2) }))
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
.transition(TransitionEffect.opacity(0.99))
.backgroundColor(this.isPresent ? 0x909399 : Color.Transparent)
.clip(true)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
this.isPresent = !this.isPresent;
})
})
}
build() {
Column() {
Text('Page 1')
.fontWeight(FontWeight.Bold)
.fontSize(30)
.fontColor(Color.Black)
.margin(20)
Row() {
Text('Shared component 1')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
}
.justifyContent(FlexAlign.Center)
.borderRadius(10)
.backgroundColor(0xf56c6c)
.width(150)
.height(150)
.margin(20)
// Modal transition component
.bindContentCover($$this.isPresent, this.MyBuilder, ModalTransition.NONE)
// The <Row> component is assigned the ID share1 and configured to have the shared element effect.
.geometryTransition('share1')
.onClick(() => {
animateTo({ curve: curves.springMotion(0.6, 1.2) }, () => {
// Change the state variable in the closure to display the modal.
this.isPresent = !this.isPresent;
})
})
Text('Component 2')
.fontWeight(FontWeight.Bold)
.fontSize(20)
.fontColor(Color.White)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(0x67C23A)
.width(150)
.height(150)
.margin(20)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Start)
.backgroundColor(Color.White)
}
}
```
![en-us_image_0000001597320326](figures/en-us_image_0000001597320326.gif)
## Implementation with Attribute Animation
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct AutoAchieveShareTransitionDemo {
private items: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'];
// Specify whether the component is expanded.
@State expand: boolean = false;
// Attributes related to the shared element.
@State rect_top: number = 0; // Position of the shared element.
@State rect_bottom: number = 0;
@State rect_left: number = 0;
@State rect_right: number = 0;
// Attributes related to the newly created element.
@State item: string = ''; // Record the expanded element.
@State cardHeight: number = 300; // Widget height.
@State cardOpacity: number = 1; // Widget opacity.
@State layoutHeight: number = 300; // Height of the expanded page.
@State layoutWidth: string = '90%'; // Width of the expanded page.
@State layoutOffset: number = 0; // Offset of the expanded page.
@State layoutOpacity: number = 0; // Opacity of the expanded page.
// In the callback invoked when the transition is complete.
@State count: number = 0;
build() {
Stack() {
Scroll() {
Column({ space: 20 }) {
ForEach(this.items, (item, index) => {
Row() {
Column() {
Text('Shared element ' + item)
.fontSize(30)
.fontColor(Color.Black)
.fontWeight(FontWeight.Bolder)
Text ('Expand widget')
.fontSize(20)
.fontColor(0x909399)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.width('90%')
.height(this.cardHeight)
.padding(20)
.backgroundColor(Color.Pink)
.borderRadius(10)
.shadow({ radius: 10, color: 0x909399, offsetX: 10, offsetY: 10 })
.opacity(this.expand && this.item == item ? 0 : 1)
// Set a unique ID and obtain the attribute information of the component corresponding to the ID.
.id(item)
.onClick(() => {
// Obtain the position and size of the corresponding component.
let strJson = getInspectorByKey(item);
let obj = JSON.parse(strJson);
let rectInfo = JSON.parse('[' + obj.$rect + ']');
let rect_left = JSON.parse('[' + rectInfo[0] + ']')[0];
let rect_top = JSON.parse('[' + rectInfo[0] + ']')[1];
let rect_right = JSON.parse('[' + rectInfo[1] + ']')[0];
let rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1];
let rect_value = {
"left": rect_left, "top": rect_top, "right": rect_right, "bottom": rect_bottom
};
// Set the location, content, and status of the shared element.
this.rect_top = rect_top;
this.item = item;
this.expand = true;
this.count += 1;
animateTo({ curve: curves.springMotion() }, () => {
this.layoutHeight = 2772 / 3.5;
this.layoutWidth = '100%';
this.layoutOffset = -((rect_top - 136) / 3.5);
})
})
})
}
.width('100%')
.margin({ top: 20 })
}
.height('100%')
// Create an element that is the same as the component based on the obtained component information.
if (this.expand) {
Column() {
// Share element.
Row() {
Column() {
Text('Shared element ' + this.item)
.fontSize(30)
.fontColor(Color.Black)
.fontWeight(FontWeight.Bolder)
Text ('Expand widget')
.fontSize(20)
.fontColor(0x909399)
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
.width('100%')
.height(this.cardHeight)
.padding(20)
.backgroundColor(Color.Pink)
// New element.
Text('Expanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page\n\nExpanded page')
.fontSize(20)
.fontColor(0xcccccc)
.margin({ top: 20 })
}
.borderRadius(this.layoutWidth == '100%' ? 0 : 10)
.shadow({ radius: 10, color: 0x909399, offsetX: 10, offsetY: 10 })
.width(this.layoutWidth)
.height(this.layoutHeight)
.clip(true)
.backgroundColor(Color.White)
// Work out the absolute position of the new element.
.position({
x: this.layoutWidth == '90%' ? '5%' : 0,
y: (this.rect_top - 136) / 3.5
})
.translate({
y: this.layoutOffset
})
.onClick(() => {
this.count -= 1;
animateTo({
curve: curves.springMotion(),
onFinish: (() => {
if (this.count == 0) {
this.expand = false;
}
})
}, () => {
this.layoutHeight = this.cardHeight;
this.layoutWidth = '90%';
this.layoutOffset = 0;
})
})
}
}
}
}
```
![en-us_image_0000001599374166](figures/en-us_image_0000001599374166.gif)
# Spring Curve Animation
ArkUI provides [preset animation curves](../reference/arkui-ts/ts-appendix-enums.md#curve), which specifies the change rule of animation attributes from the start value to the end value, such as Linear, Ease, and EaseIn. At the same time, ArkUI also provides spring curves generated by the physical model of spring oscillators. Through the spring curve, developers can set the end value to be exceeded and oscillate around the end value until the end value stops. The animation effect of spring curve is more interactive and playable than other curves.
There are two types of interfaces for spring curves: [springCurve](../reference/apis/js-apis-curve.md#curvesspringcurve9) and [springMotion](../reference/apis/js-apis-curve.md#curvesspringmotion9) and [responsiveSpringMotion](../reference/apis/js-apis-curve.md#curvesresponsivespringmotion9). Spring curves can be generated in both modes.
## Using springCurve
The **springCurve** API is as follows:
```ts
springCurve(velocity: number, mass: number, stiffness: number, damping: number)
```
The structural parameters include the initial velocity, the mass, stiffness and damping of the spring system. When building springCurve, you can set the quality to 1. Adjust the stiffness and damping parameters based on the parameter description in springCurve to achieve the desired oscillation effect.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct SpringTest {
@State translateX: number = 0;
private jumpWithSpeed(speed: number) {
this.translateX = -1;
animateTo({ duration: 2000, curve: curves.springCurve(speed, 1, 1, 1.2) }, () => {
//Spring animation for translation in the x direction at the specified initial speed
this.translateX = 0;
})
}
build() {
Column() {
Button("button")
.fontSize(14)
.width(100)
.height(50)
.margin(30)
.translate({ x: this.translateX })
Row({space:50}) {
Button("jump 50").fontSize(14)
.onClick(() => {
//Translate the spring curve with an initial speed of 50.
this.jumpWithSpeed(50);
})
Button("jump 200").fontSize(14)
.onClick(() => {
//Translate the spring curve with an initial speed of 200.
this.jumpWithSpeed(200);
})
}.margin(30)
}.height('100%').width('100%')
}
}
```
![springCurve](figures/springCurve.gif)
In the preceding example, when different buttons are clicked and different initial speeds of springCurve are given, the buttons reach the specified positions elastically, and the amplitude of the buttons increases with the speed. In addition, you can modify the mass, stiffness, and damping parameters of springCurve to achieve the desired elasticity.
>**NOTE**
>
>The speed only amplifies the oscillation effect, but whether the system can produce the oscillation effect depends on the physical parameters of the spring oscillator, that is, mass, stiffness, and damping. The smaller the stiffness and the larger the damping, the weaker the "elasticity" of springCurve and the weaker the oscillation effect. With the decrease of stiffness or the increase of damping, no matter how large the velocity is, there will be no oscillation near the end value.
## Using springMotion and responsiveSpringMotion
The interfaces of the [springMotion](../reference/apis/js-apis-curve.md#curvesspringmotion9) are as follows:
```ts
springMotion(response?: number, dampingFraction?: number, overlapDuration?: number)
```
The interfaces of the [responsiveSpringMotion](../reference/apis/js-apis-curve.md#curvesresponsivespringmotion9) are as follows:
```ts
responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number)
```
Their construction parameters include three optional parameters: spring natural vibration period, damping coefficient, and elastic animation connection duration. For details about the parameters, see their documents.
When the springMotion and responsiveSpringMotion curves are used, the duration parameter does not take effect. This parameter is applicable to hand animation.
```ts
import curves from '@ohos.curves';
@Entry
@Component
struct SpringMotionTest {
@State positionX: number = 100;
@State positionY: number = 100;
diameter: number = 50;
build() {
Column() {
Row() {
Circle({ width: this.diameter, height: this.diameter })
.fill(Color.Blue)
.position({ x: this.positionX, y: this.positionY })
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Move) {
// Follow-up process. Use the responsiveSpringMotion curve.
animateTo({ curve: curves.responsiveSpringMotion() }, () => {
//subtract the radius so that the center of the ball moves to the finger position
this.positionX = event.touches[0].screenX - this.diameter / 2;
this.positionY = event.touches[0].screenY - this.diameter / 2;
console.info(`move, animateTo x:${this.positionX}, y:${this.positionY}`);
})
} else if (event.type === TouchType.Up) {
//Use the springMotion curve when you leave your hand.
animateTo({ curve: curves.springMotion() }, () => {
this.positionX = 100;
this.positionY = 100;
console.info(`touchUp, animateTo x:100, y:100`);
})
}
})
}
.width("100%").height("80%")
.clip(true) //If the ball exceeds the range of the parent component, the ball is invisible.
.backgroundColor(Color.Orange)
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Center }) {
Text("Drag the ball").fontSize(16)
}
.width("100%")
Row() {
Text('Click position: [x:' + Math.round(this.positionX) +', y:' + Math.round(this.positionY) + ']').fontSize(16)
}
.padding(10)
.width("100%")
}.height('100%').width('100%')
}
}
```
The preceding code is an example of hand animation. In the onTouch event, the touch position is captured and the translate or position attribute of the component is changed so that the component moves to the touch position when following the hand. After the hand is released, the component returns to the original position. The following figure shows the effect of the follower animation.
![springMotion](figures/springMotion.gif)
The responsiveSpringMotion curve is recommended for the follow-up process, and the springMotion curve is recommended for the release process. The follow-up process is triggered for multiple times as the position of the hand changes. Therefore, the responsiveSpringMotion animation is started for multiple times. When the hand is released, the springMotion animation is started once. During the follow-up and release processes, an animation is executed on the same attribute of the same object, and the springMotion or responsiveSpringMotion curve is used. Each time the animation is started, the speed used by the last animation is inherited, implementing smooth transition.
>**NOTE**
>
> 1. SpringCurve can be used to set the initial speed. If a single attribute has multiple animations, the animations do not affect each other. The effects of multiple animations are superimposed.
>
> 2. Although springMotion has an internal speed mechanism, it cannot be set by developers. When multiple animations exist for a single attribute, the later animation replaces the previous animation and inherits the speed of the previous animation.
# Spring Curve
In a damped spring system corresponding to a damped spring curve (spring curve for short), an object that deviates from the equilibrium position is forced to oscillate due to a reverse force generated by spring deformation; this oscillation is resisted by the damping force. Except for the special case where the damping is 0, the oscillation gradually decays in amplitude towards 0, and the resultant animation curve is naturally continuous.
An animation using the spring curve slows down toward the end where the velocity of 0, instead of stopping abruptly.
ArkUI provides four types of damped spring curve APIs:
- [springMotion](../reference/apis/js-apis-curve.md#curvesspringmotion9): creates a spring animation curve. The animation duration is automatically calculated based on the curve parameters, attribute change values, and initial spring velocity. Manually set animation duration values do not take effect.
**springMotion** does not provide any API for setting the velocity, as the velocity is obtained through inheritance. For an attribute, if there is already a springMotion or responsiveSpringMotion animation running, a new spring animation will stop the running animation and inherit the attribute values and velocity of that animation as its initial values. This spring curve API provides default parameters, which you can directly use when appropriate.
```ts
function springMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve;
```
- [responsiveSpringMotion](../reference/apis/js-apis-curve.md#curvesresponsivespringmotion9): creates a responsive spring animation curve. It is a special case of **springMotion**, with the only difference in the default values. It is typically used to create an animation with a gesture on the screen. You can use **springMotion** to create an animation for when the user lifts their finger off the screen. The created animation automatically inherits the previous velocity for animation transition.
When the **overlapDuration** parameter of the new animation is not **0** and the previous spring animation of the current attribute is not yet complete, **response** and **dampingFracion** transit from the values of the previous animation to that of the new animation within the period specified by **overlapDuration**.
```ts
function responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve;
```
- [interpolatingSpring](../reference/apis/js-apis-curve.md#curvesinterpolatingspring10): creates an interpolating spring curve animated from 0 to 1. It applies to scenarios where the initial animation velocity needs to be specified. The animation duration is automatically calculated, and the manually specified animation duration does not take effect.
The actual animation value is calculated based on the curve. Therefore, the velocity should be the normalized speed, which is equal to the absolute speed of the animation attribute change divided by the amount of the animation attribute change. In light of this, this API is not applicable to the scenario where the attribute value of the animation start point is the same as that of the animation end point, since under this scenario, the amount of the animation attribute change is 0, and the normalized speed does not exist.
```ts
function interpolatingSpring(velocity: number, mass: number, stiffness: number, damping: number): ICurve;
```
- [springCurve](../reference/apis/js-apis-curve.md#curvesspringcurve9): creates a spring curve with the specified animation duration. This API is almost the same as **interpolatingSpring**. However, for an animation that uses **springCurve**, the physical duration of the curve is mapped to the specified duration, which is equivalent to stretching or compressing the curve on the time axis and violating the original physical rule of the curve. Whenever possible, avoid using this API.
```ts
function springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve;
```
The following shows a complete example and effect of spring curves. For details about how to connect gestures and animations, see [Animation Smoothing](arkts-animation-smoothing.md).
```ts
import curves from '@ohos.curves';
class Spring {
public title: string;
public subTitle: string;
public iCurve: ICurve;
constructor(title: string, subTitle: string, iCurve: ICurve) {
this.title = title;
this.iCurve = iCurve;
this.subTitle = subTitle;
}
}
// Spring component
@Component
struct Motion {
@Prop dRotate: number
private title: string
private subTitle: string
private iCurve: ICurve
build() {
Row() {
Column() {
Text(this.title)
.fontColor(Color.Black)
.fontSize(16)
Text(this.subTitle)
.fontColor(0xcccccc)
.fontSize(12)
}
.width(200)
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Center)
.height(100)
Stack({ alignContent: Alignment.Top }) {
// Circle
Column()
.width(100)
.height(100)
.border({
width: 10,
color: 0xf56c6c,
radius: 50
})
.backgroundColor(Color.White)
// Mask layer
Column() {
Row()
.width(100)
.height(100)
.border({
width: 10,
color: 0x909399,
radius: 50
})
.backgroundColor(0xf56c6c)
}
.width(100)
.height(50)
.clip(true)
.rotate({ angle: this.dRotate, centerX: 50, centerY: 50 })
.animation({ curve: this.iCurve, iterations: -1 })
}
.width(100)
.height(100)
}
.height(110)
.borderWidth({ bottom: 1 })
.borderColor(0xf5f5f5)
.margin({ bottom: 5 })
.alignItems(VerticalAlign.Top)
}
}
@Entry
@Component
export struct SpringDemo {
@State dRotate: number = 0;
private springs: Spring[] = [
new Spring('springMotion()', '(springMotion(1, 0.25): \n\nCycle: 2; damping: 0.25)', curves.springMotion(1, 0.25)),
new Spring('responsiveSpringMotion()', 'responsiveSpringMotion(1, 0.25): \n\nDefault responsive spring curve', curves.responsiveSpringMotion(1, 0.25)),
new Spring('interpolatingSpring()', '(interpolatingSpring(10, 1, 228, 30): \n\nInitial velocity: 100; quality: 1; stiffness: 228; damping: 30)', curves.interpolatingSpring(10, 1, 228, 30)),
new Spring('springCurve()', '(springCurve(10, 1, 228, 30): \n\nInitial velocity: 100; quality: 1; stiffness: 228; damping: 30)', curves.springCurve(10, 1, 228, 30))
];
build() {
Column() {
ForEach(this.springs, (item: Spring) => {
Motion({ title: item.title, subTitle: item.subTitle, iCurve: item.iCurve, dRotate: this.dRotate })
})
}
.justifyContent(FlexAlign.Center)
.width('100%')
.height(437)
.margin({ top: 20 })
.onClick(() => {
this.dRotate = 360;
})
}
}
```
![en-us_image_0000001649089041](figures/en-us_image_0000001649089041.gif)
# Traditional Curve
The animation curve, defined by a timing function, is a speed curve that controls the time consumed by an animation on attribute changes. The slope of the animation curve at a certain moment indicates the animation velocity and corresponds to the attribute change speed. A well-designed animation curve should be continuously smooth, in line with the user's intent, and consistent with the real world. When designing animation curves for your animations and transitions, take into account use cases and user intents. Animation curves can be classified into physics-based curves (ArkUI provides multiple physics-based spring curves) and traditional curves based on whether they model the real world. Compared with the traditional curve, the movement trajectory generated by the physics-based curve would feel more natural to users and help create a more engaging experience. In light of this, you are advised to use the physics-based curve when possible.
Traditional curves are mathematically described curves. A typical representative is the cubic Bezier curve. You define the curve shape with a set of control points, to bring out the expected animation effect, such as ease in and ease out. As aforementioned, a traditional curve is not based on the real-world behavior. This means that it does not change its shape to respond to user behavior, and lacks the natural and engaging feel given by a physics-based curve. When creating animations, prioritize physics-based curves and use traditional curves only in rare cases.
ArkUI provides APIs for traditional curves such as Bezier and step curves. For details, see [Interpolation Calculation](../reference/apis/js-apis-curve.md).
The following is an example of a traditional curve.
```ts
class MyCurve {
public title: string;
public curve: Curve;
public color: Color | string;
constructor(title: string, curve: Curve, color: Color | string = '') {
this.title = title;
this.curve = curve;
this.color = color;
}
}
const myCurves: MyCurve[] = [
new MyCurve(' Linear', Curve.Linear, 0x409EFF),
new MyCurve(' Ease', Curve.Ease, 0x67C23A),
new MyCurve(' EaseIn', Curve.EaseIn, 0xE6A23C),
new MyCurve(' EaseOut', Curve.EaseOut, 0xF56C6C),
new MyCurve(' EaseInOut', Curve.EaseInOut, 0xFFB6C1),
new MyCurve(' FastOutSlowIn', Curve.FastOutSlowIn, 0xDC143C),
new MyCurve(' LinearOutSlowIn', Curve.LinearOutSlowIn, 0xFF00FF),
new MyCurve(' FastOutLinearIn', Curve.FastOutLinearIn, 0x00BFFF),
new MyCurve(' ExtremeDeceleration', Curve.ExtremeDeceleration, 0x5F9EA0),
new MyCurve(' Sharp', Curve.Sharp, 0x00FFFF),
new MyCurve(' Rhythm', Curve.Rhythm, 0x66CDAA),
new MyCurve(' Smooth', Curve.Smooth, 0x7CFC00),
new MyCurve(' Friction', Curve.Friction, 0xFFA500)
]
@Entry
@Component
export struct CurveDemo {
@State dRotate: number = 0; // Rotation angle.
build() {
Column() {
// Curve example
Grid() {
ForEach(myCurves, (item: MyCurve) => {
GridItem() {
Column() {
Row()
.width(20)
.height(20)
.borderRadius(10)
.backgroundColor(item.color)
Text(item.title)
.fontSize(10)
.fontColor(0x909399)
}
.width('100%')
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.rowsTemplate('1fr 1fr 1fr 1fr 1fr')
.padding(10)
.width('100%')
.height(300)
Stack() {
// Swing pipe
Row()
.width(290)
.height(290)
.border({
width: 10,
color: 0xE6E8EB,
radius: 145
})
ForEach(myCurves, (item: MyCurve) => {
// Balls
Column() {
Row()
.width(20)
.height(20)
.borderRadius(10)
.backgroundColor(item.color)
}
.width(20)
.height(300)
.rotate({ angle: this.dRotate })
.animation({ duration: 2000, iterations: -1, curve: item.curve, delay: 100 })
})
}
.width('100%')
.height(437)
.onClick(() => {
this.dRotate ? null : this.dRotate = 360;
})
}
.width('100%')
}
}
```
![en-us_image_0000001641260233](figures/en-us_image_0000001641260233.gif)
# Transition Animation Within the Component
The process of inserting and deleting a component is the transition process of the component. The animation of inserting and deleting a component is called the transition animation in the component. You can define the appearance and disappearance effects of a component through the transition animation in the component.
The interface of the transition animation in the component is as follows:
```ts
transition(value: TransitionOptions)
```
The input parameter of the [transition](../reference/arkui-ts/ts-transition-animation-component.md) API defines the transition effect in the component. You can define the transition effect of one or more transition styles such as translation, opacity, rotation, and scaling. **transition** must be used together with [animateTo](arkts-layout-update-animation.md#using-explicit-animation-to-create-layout-update-animation).
## Common Usage of Transition
The type parameter is used to specify the gadget change scenario where the current transition dynamic effect takes effect. The type is [TransitionType](../reference/arkui-ts/ts-appendix-enums.md#transitiontype).
- The same animation effect is used for inserting and deleting components.
```ts
Button()
.transition({ type: TransitionType.All, scale: { x: 0, y: 0 } })
```
When the type attribute is TransitionType.All, the specified transition effect takes effect in all change (insertion and deletion) scenarios of the component. In this case, deleting the animation and inserting the animation are reverse processes, and deleting the animation is reverse playing of inserting the animation. For example, the preceding code defines a Button control. When a component is inserted, the component changes from the state where x and y of the scale are both 0 to the default state where x and y of the scale are both 1 (complete display). The component is gradually zoomed in. When a component is deleted, the component changes from the default state where x and y of the scale are 1 to the state where x and y of the specified scale are 0 and gradually shrinks to 0.
- Different animation effects are used for inserting and deleting components.
```ts
Button()
.transition({ type: TransitionType.Insert, translate: { x: 200, y: -200 }, opacity: 0 })
.transition({ type: TransitionType.Delete, rotate: { x: 0, y: 0, z: 1, angle: 360 } })
```
When different transition animation effects need to be implemented for component insertion and deletion, you can call the transition function twice to set the type attribute to TransitionType.Insert and TransitionType.Delete respectively. For example, the preceding code defines a Button control. When the component is inserted, the component changes from an initial state in which the position is translated by 200 vp in the x direction and the position is translated by –200 vp in the y direction relative to the normal layout position of the component, and the transparency is 0 in the x and y directions to a default state in which the translation amount is 0 and the transparency is 1. The inserted animation is a combination of a translation animation and a transparency animation. When the component is deleted, the component changes from the default state in which the rotation angle is 0 to the end state in which the component rotates 360 degrees around the z axis, that is, rotates around the z axis for one week.
- Define only one of the animation effects of inserting or deleting a component.
```ts
Button()
.transition({ type: TransitionType.Delete, translate: { x: 200, y: -200 } })
```
If only the transition animation effect of component insertion or deletion is required, you only need to set the transition effect whose **type** attribute is **TransitionType.Insert** or **TransitionType.Delete**. For example, the preceding code defines a Button control. When a component is deleted, the component is moved from the normal position without translation to the position of 200 vp in the x direction and -200 vp in the y direction relative to the normal layout position. Inserting the component does not generate a transition animation for the component.
## if/else: generates transition animations in components.
The if/else statement can control the insertion and deletion of components. The following code can be used to control whether the if condition is met through the button click event to control whether to display the Image component under if.
```ts
@Entry
@Component
struct IfElseTransition {
@State flag: boolean = true;
@State show: string = 'show';
build() {
Column() {
Button(this.show).width(80).height(30).margin(30)
.onClick(() => {
if (this.flag) {
this.show = 'hide';
} else {
this.show = 'show';
}
//Click the button to control the display and disappearance of the image.
this.flag = !this.flag;
})
if (this.flag) {
Image($r('app.media.mountain')).width(200).height(200)
}
}.height('100%').width('100%')
}
}
```
No animation is configured in the preceding code. Next, we'll add the in-component transition effect to the above code. The Image component is controlled by if. You need to add the transition parameter to the Image component to specify the transition effect in the component. For example, you can add the translation effect when inserting the file, and add the scaling and transparency effects when deleting the file.
```ts
if (this.flag) {
Image($r('app.media.mountain')).width(200).height(200)
.transition({ type: TransitionType.Insert, translate: { x: 200, y: -200 } })
.transition({ type: TransitionType.Delete, opacity: 0, scale: { x: 0, y: 0 } })
}
```
Although the preceding code specifies the animation style, the animation parameters are not specified. Therefore, you do not know how long and how to use the curve to complete the animation. Transition must be used together with animateTo. In the closure of animateTo, transition controls the insertion and deletion of components. The preceding sample code is used to change the value of flag in the animateTo closure. The code is as follows: Set the animation duration to 1000 ms, use the default curve of the animateTo function, and change the value of flag. Animation is generated based on the animation parameter for all changes caused by flag changes. Here, the flag affects the appearance and disappearance of the image.
```ts
animateTo({ duration: 1000 }, () => {
this.flag = !this.flag;
})
```
After the preceding process, when animateTo and transition are used together, the transition animation in the component is generated. The complete sample code is as follows:
```ts
@Entry
@Component
struct IfElseTransition {
@State flag: boolean = true;
@State show: string = 'show';
build() {
Column() {
Button(this.show).width(80).height(30).margin(30)
.onClick(() => {
if (this.flag) {
this.show = 'hide';
} else {
this.show = 'show';
}
animateTo({ duration: 1000 }, () => {
//Control the appearance and disappearance of the Image component in the animation closure.
this.flag = !this.flag;
})
})
if (this.flag) {
//The appearance and disappearance of the image are configured as different transition effects.
Image($r('app.media.mountain')).width(200).height(200)
.transition({ type: TransitionType.Insert, translate: { x: 200, y: -200 } })
.transition({ type: TransitionType.Delete, opacity: 0, scale: { x: 0, y: 0 } })
}
}.height('100%').width('100%')
}
}
```
![ifElseTransition](figures/ifElseTransition.gif)
>**NOTE**
>
>When the transition effect is set to translate or scale, the animation process may exceed the range of the parent component after the translation or magnification is overlaid on the position. If you want the child component to be completely displayed when the parent component is beyond the range of the parent component, you can set the clip attribute of the parent component to false so that the parent component does not tailor the child component. If you want the excess child components not to be displayed when the parent component is exceeded, you can set the clip attribute of the parent component to true to tailor the excess child components.
## Forach generates transition animations in components.
Similar to if/else, Forach can control the insertion and deletion of components by controlling the number of elements in an array. To use Forach to generate an intra-component transition animation, the following conditions must be met:
- The transition effect is configured for the component in Forach.
- Controls the insertion or deletion of components in the closure of animateTo, that is, controls the addition and deletion of array elements.
The following code is an example of using Forach to generate an in-component transition animation.
```ts
@Entry
@Component
struct ForEachTransition {
@State numbers: string[] = ["1", "2", "3", "4", "5"]
startNumber: number = 6;
build() {
Column({ space: 10 }) {
Column() {
ForEach(this.numbers, (item) => {
// The transition effect needs to be configured for the direct component under Forach.
Text(item)
.width(240)
.height(60)
.fontSize(18)
.borderWidth(1)
.backgroundColor(Color.Orange)
.textAlign(TextAlign.Center)
.transition({ type: TransitionType.All, translate: { x: 200 }, scale: { x: 0, y: 0 } })
}, item => item)
}
.margin(10)
.justifyContent(FlexAlign.Start)
.alignItems(HorizontalAlign.Center)
.width("90%")
.height("70%")
Button ('Add element to header')
.fontSize(16)
.width(160)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
//Insert an element to the array header. As a result, Forach adds the corresponding component to the header.
this.numbers.unshift(this.startNumber.toString());
this.startNumber++;
})
})
Button ('Add element to tail')
.width(160)
.fontSize(16)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
//Insert an element to the end of the array. As a result, Forach adds the corresponding component to the end.
this.numbers.push(this.startNumber.toString());
this.startNumber++;
})
})
Button ('Delete Header Element')
.width(160)
.fontSize(16)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
//Delete the header element of the array. As a result, Forach deletes the header component.
this.numbers.shift();
})
})
Button ('Delete Tail Element')
.width(160)
.fontSize(16)
.onClick(() => {
animateTo({ duration: 1000 }, () => {
//Delete the tail element of the array. As a result, Forach deletes the header component.
this.numbers.pop();
})
})
}
.width('100%')
.height('100%')
}
}
```
The display effect is shown below.
![forEachTransition2](figures/forEachTransition2.gif)
The column layout mode is set to FlexAlign.Start, that is, the vertical layout starts from the head. Therefore, when an element is added to the end of an array, the position of the component corresponding to the existing element in the array is not affected, and only the insertion animation of the new component is triggered. When an element is added to the array header, the subscripts of all elements in the original array are added. Although the addition or deletion of the element is not triggered, the location of the corresponding component is affected. Therefore, in addition to the transition animation for new components, the position animation is also performed for components in Forach.
>**NOTE**
>
>If/else and ForEach are syntax nodes. The component for configuring the transition effect in the component should be directly used as the child of the syntax node. If a component is added or deleted due to the addition or deletion of a syntax node, only the intra-component transition animation of the direct child component can be triggered. Developers should not expect the component transition animation to be generated for deeper components.
# Transition Animation Overview
Compared with [attribute animations](arkts-attribute-animation-overview.md), which work for components that are always present, transition animations are applied to animate the appearing or disappearing components. With transition animations, you are freed from the burdensome tasks of disappearing component management, which are unavoidable if you used attribute animations instead: deleting the component in the callback invoked when the animation is complete; checking the component status in the callback, in case that the component that has been deleted appears again before the animation ends.
Transition animations are classified into basic transition animations and advanced template-based transition animations. They come in any of the following types:
- [Enter/Exit transition](arkts-enter-exit-transition.md): used on appearing and disappearing components. It is a basic type of transition.
- [Navigation transition](arkts-navigation-transition.md): used during page navigation, where one page disappears and another page appears. For example, it can be used for switching from a level-1 menu page to a level-2 details page.
- [Modal transition](arkts-modal-transition.md): achieved by a modal – a view that appears on top of the current view while the current view remains. The dialog box is a typical type of modal.
- [Shared element transition](arkts-shared-element-transition.md): achieved by animating the size and position between styles of the same or similar elements during page switching.
...@@ -84,8 +84,8 @@ The table below lists the main tasks involved in UI development with ArkUI. You ...@@ -84,8 +84,8 @@ The table below lists the main tasks involved in UI development with ArkUI. You
| Develop the layout | Understand the common layouts and how to improve layout performance. | - [Layout Overview](arkts-layout-development-overview.md)<br>- [Improving Layout Performance](arkts-layout-development-performance-boost.md)| | Develop the layout | Understand the common layouts and how to improve layout performance. | - [Layout Overview](arkts-layout-development-overview.md)<br>- [Improving Layout Performance](arkts-layout-development-performance-boost.md)|
| Add components | Learn the usage of common built-in components, custom components, and GUI elements supported by APIs.| - [Common Components](arkts-common-components-button.md)<br>- [Custom Components](../quick-start/arkts-create-custom-components.md)<br>- [Popup and Menu](arkts-popup-and-menu-components-popup.md)| | Add components | Learn the usage of common built-in components, custom components, and GUI elements supported by APIs.| - [Common Components](arkts-common-components-button.md)<br>- [Custom Components](../quick-start/arkts-create-custom-components.md)<br>- [Popup and Menu](arkts-popup-and-menu-components-popup.md)|
| Set page routing and component navigation| Learn how to set page routes and navigation between components. | - [Page Routing](arkts-routing.md)<br>- [Navigation](arkts-navigation-navigation.md)| | Set page routing and component navigation| Learn how to set page routes and navigation between components. | - [Page Routing](arkts-routing.md)<br>- [Navigation](arkts-navigation-navigation.md)|
| Use graphics | Understand how to display images, draw custom geometry, and make custom graphics on the canvas. | - [Displaying Images](arkts-graphics-display.md)<br>- [Drawing Geometric Shapes](arkts-geometric-shape-drawing.md)<br>- [Drawing Custom Graphics Using the Canvas](arkts-drawing-customization-on-canvas.md) | | Use graphics | Understand how to display images, draw custom geometry, and make custom graphics on the canvas. | - [Displaying Images](arkts-graphics-display.md)<br>- [Drawing Geometric Shapes](arkts-geometric-shape-drawing.md)<br>- [Drawing Custom Graphics Using the Canvas](arkts-drawing-customization-on-canvas.md)|
| Apply animations | Learn the typical scenarios of applying animations on components and pages. | - [Animation Within a Page](arkts-layout-update-animation.md)<br>- [Animation Between Pages](arkts-zoom-animation.md)| | Apply animations | Learn the typical scenarios of applying animations on components and pages. | - [Attribute Animation](arkts-attribute-animation-overview.md)<br>- [Transition Animation](arkts-transition-overview.md)<br>- [Component Animation](arkts-component-animation.md)<br>- [Animated Curve](arkts-traditional-curve.md)<br>- [Animation Smoothing](arkts-animation-smoothing.md)<br>- [Animation Effects](arkts-blur-effect.md)|
| Bind events | Learn the basic concepts of events and how to use common events and gesture events. | - [Universal Events](arkts-common-events-touch-screen-event.md)<br>- [Gesture Events](arkts-gesture-events-binding.md)| | Bind events | Learn the basic concepts of events and how to use common events and gesture events. | - [Universal Events](arkts-common-events-touch-screen-event.md)<br>- [Gesture Events](arkts-gesture-events-binding.md)|
## ##
......
# Zoom Animation
If the same element (for example, the same image) is used on different pages, you can use the Shared Element Transition (../reference/arkui-ts/ts-transition-animation-shared-elements.md) animation to connect the elements. To highlight the association of the same elements between different pages, you can add shared element transition animations for them. If the sizes of the same element on different pages are obviously different, the view can be zoomed in or out.
The interface for shared element transition is as follows:
```ts
sharedTransition(id: string, options?: sharedTransitionOptions)
```
Based on the type parameter in sharedTransitionOptions, shared element transitions are classified into Exchange shared element transitions and Static shared element transitions.
## Transition of Shared Elements of the Exchange Type
The transition of shared elements of the exchange type requires that components with the same ID configured through the sharedTransition function exist on two pages. These components are called shared elements. This type of shared element transition is applicable to the connection of the same element between two pages, and transits from the position and size of the shared element on the start page to the position and size of the shared element on the target page. If type is not specified, the shared element transition of the Exchange type is used by default, which is the most common shared element transition mode. When the shared element transition of the Exchange type is used, the animation parameters of the shared element transition are determined by the animation parameters in options on the target page.
## Transition of Shared Elements of the Static Type
Static shared element transition is usually used in the scenario where the title gradually appears or is hidden during page switching. Static shared elements only need to exist on one page. Static shared elements with the same ID cannot exist on two pages. When the page (target page) is displayed, the transparency of the sharedTransition component of the Static type is changed from 0 to the transparency set by the component, and the position remains unchanged. When the page (that is, the start page) disappears, an animation in which the transparency gradually changes to 0 is performed, and the position remains unchanged.
The animation parameters of the shared element transition are determined by the animation parameters in the sharedTransition attribute of the component.
## Example Scenario
The following describes an example of using a shared element transition to zoom in or zoom out an image.
```ts
// src page
import router from '@ohos.router';
@Entry
@Component
struct SharedTransitionSrc {
build() {
Column() {
//Configure the transition of the shared element of the Exchange type. The ID of the shared element is sharedImage1.
Image($r('app.media.mountain')).width(50).height(50)
.sharedTransition('sharedImage1', { duration: 1000, curve: Curve.Linear })
.onClick(() => {
//When a small image is clicked, the route jumps to the next page.
router.pushUrl({ url: 'pages/myTest/sharedTransitionDst' });
})
}
.padding(10)
.width("100%")
.alignItems(HorizontalAlign.Start)
}
}
```
```ts
// dest page
import router from '@ohos.router';
@Entry
@Component
struct SharedTransitionDest {
build() {
Column() {
//Configure the transition of shared elements of the Static type.
Text("SharedTransition dest page")
.fontSize(16)
.sharedTransition('text', { duration: 500, curve: Curve.Linear, type: SharedTransitionEffectType.Static })
.margin({ top: 10 })
//Configure the transition of the shared element of the Exchange type. The ID of the shared element is sharedImage1.
Image($r('app.media.mountain'))
.width(150)
.height(150)
.sharedTransition('sharedImage1', { duration: 500, curve: Curve.Linear })
.onClick(() => {
// Return to the previous page when a user clicks an image.
router.back();
})
}
.width("100%")
.alignItems(HorizontalAlign.Center)
}
}
```
In the preceding example, the shared element transition whose ID is sharedImage1 is configured on both the first page (src page) and the second page (dest page) so that the two pages can match the group of shared elements. When you jump from the first page to the second page, the first page is the start page, and the second page is the target page. Configure the component whose ID is sharedImage1 to perform shared element transition based on the duration of 500 ms on the target page to zoom in the view. Configure the component whose ID is text to perform shared element transition based on the duration of 500 ms in the sharedTransition parameter of the Static type, the headline gradually appears. When you return from the second page to the first page, the second page is the start page, and the first page is the target page. Configure the component whose ID is sharedImage1 to perform shared element transition based on the duration of 1000 ms on the target page and zoom out to the original view. Configure the component whose ID is text to perform shared element transition based on the duration of 500 ms in the sharedTransition parameter of the Static type, the title is gradually hidden.
![sharedTransition](figures/sharedTransition.gif)
...@@ -90,7 +90,14 @@ In the following example, **createWebMessagePorts** is used to create message po ...@@ -90,7 +90,14 @@ In the following example, **createWebMessagePorts** is used to create message po
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebView Message Port Demo</title> <title>WebView Message Port Demo</title>
</head> </head>
<body>
<h1>WebView Message Port Demo</h1>
<div>
<input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
<script> <script>
var h5Port; var h5Port;
var output = document.querySelector('.output'); var output = document.querySelector('.output');
...@@ -107,7 +114,7 @@ In the following example, **createWebMessagePorts** is used to create message po ...@@ -107,7 +114,7 @@ In the following example, **createWebMessagePorts** is used to create message po
msg = msg + result; msg = msg + result;
} else if (typeof(result) === 'object') { } else if (typeof(result) === 'object') {
if (result instanceof ArrayBuffer) { if (result instanceof ArrayBuffer) {
console.info(`received arraybuffer from html5, length is:` ${result.byteLength}`); console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
msg = msg + 'lenght is ' + result.byteLength; msg = msg + 'lenght is ' + result.byteLength;
} else { } else {
console.info('not support'); console.info('not support');
...@@ -130,14 +137,5 @@ In the following example, **createWebMessagePorts** is used to create message po ...@@ -130,14 +137,5 @@ In the following example, **createWebMessagePorts** is used to create message po
} }
} }
</script> </script>
<body>
<h1>WebView Message Port Demo</h1>
<div>
<input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
</html> </html>
``` ```
...@@ -43,41 +43,44 @@ ...@@ -43,41 +43,44 @@
- [Resource Categories and Access](quick-start/resource-categories-and-access.md) - [Resource Categories and Access](quick-start/resource-categories-and-access.md)
- Learning ArkTS - Learning ArkTS
- [Getting Started with ArkTS](quick-start/arkts-get-started.md) - [Getting Started with ArkTS](quick-start/arkts-get-started.md)
- Basic Syntax - [Introduction to ArkTS]quick-start/arkts/introduction-to-arkts.md)
- [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md) - [TypeScript to ArkTS Migration](quick-start/arkts/typescript-to-arkts-migration-guide.md)
- [Declarative UI Description](quick-start/arkts-declarative-ui-description.md) - UI Paradigm
- Custom Component - Basic Syntax
- [Creating a Custom Component](quick-start/arkts-create-custom-components.md) - [Basic Syntax Overview](quick-start/arkts-basic-syntax-overview.md)
- [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md) - [Declarative UI Description](quick-start/arkts-declarative-ui-description.md)
- [\@Builder Decorator: Custom Builder Function](quick-start/arkts-builder.md) - Custom Component
- [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md) - [Creating a Custom Component](quick-start/arkts-create-custom-components.md)
- [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md) - [Page and Custom Component Lifecycle](quick-start/arkts-page-custom-components-lifecycle.md)
- [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md) - [\@Builder Decorator: Custom Builder Function](quick-start/arkts-builder.md)
- [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md) - [\@BuilderParam Decorator: \@Builder Function Reference](quick-start/arkts-builderparam.md)
- [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md) - [\@Styles Decorator: Definition of Resusable Styles](quick-start/arkts-style.md)
- State Management - [\@Extend Decorator: Extension of Built-in Components](quick-start/arkts-extend.md)
- [State Management Overview](quick-start/arkts-state-management-overview.md) - [stateStyles: Polymorphic Style](quick-start/arkts-statestyles.md)
- Component State Management - [\@AnimatableExtend Decorator: Definition of Animatable Attributes](quick-start/arkts-animatable-extend.md)
- [\@State Decorator: State Owned by Component](quick-start/arkts-state.md) - State Management
- [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md) - [State Management Overview](quick-start/arkts-state-management-overview.md)
- [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md) - Component State Management
- [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md) - [\@State Decorator: State Owned by Component](quick-start/arkts-state.md)
- [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md) - [\@Prop Decorator: One-Way Synchronization from Parent to Child Components](quick-start/arkts-prop.md)
- Application State Management - [\@Link Decorator: Two-Way Synchronization Between Parent and Child Components](quick-start/arkts-link.md)
- [Application State Management Overview](quick-start/arkts-application-state-management-overview.md) - [\@Provide and \@Consume Decorators: Two-Way Synchronization with Descendant Components](quick-start/arkts-provide-and-consume.md)
- [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md) - [\@Observed and \@ObjectLink Decorators: Observing Attribute Changes in Nested Class Objects](quick-start/arkts-observed-and-objectlink.md)
- [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md) - Application State Management
- [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md) - [Application State Management Overview](quick-start/arkts-application-state-management-overview.md)
- [Environment: Device Environment Query](quick-start/arkts-environment.md) - [LocalStorage: UI State Storage](quick-start/arkts-localstorage.md)
- Other State Management Features - [AppStorage: Application-wide UI State Storage](quick-start/arkts-appstorage.md)
- [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md) - [PersistentStorage: Application State Persistence](quick-start/arkts-persiststorage.md)
- [\@Watch Decorator: Getting Notified of State Variable Changes](quick-start/arkts-watch.md) - [Environment: Device Environment Query](quick-start/arkts-environment.md)
- [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md) - Other State Management Features
- Rendering Control - [Overview of Other State Management Features](quick-start/arkts-other-state-mgmt-functions-overview.md)
- [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md) - [\@Watch Decorator: Getting Notified of State Variable Changes](quick-start/arkts-watch.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md) - [$$ Syntax: Two-Way Synchronization of Built-in Components](quick-start/arkts-two-way-sync.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md) - Rendering Control
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md) - [Overview of Rendering Control](quick-start/arkts-rendering-control-overview.md)
- [if/else: Conditional Rendering](quick-start/arkts-rendering-control-ifelse.md)
- [ForEach: Rendering of Repeated Content](quick-start/arkts-rendering-control-foreach.md)
- [LazyForEach: Lazy Data Loading](quick-start/arkts-rendering-control-lazyforeach.md)
- Development - Development
- Application Models - Application Models
- Application Model Overview - Application Model Overview
...@@ -528,7 +531,9 @@ ...@@ -528,7 +531,9 @@
- [hapsigner Guide](security/hapsigntool-guidelines.md) - [hapsigner Guide](security/hapsigntool-guidelines.md)
- [HarmonyAppProvision Configuration File](security/app-provision-structure.md) - [HarmonyAppProvision Configuration File](security/app-provision-structure.md)
- AI - AI
- [Using MindSpore Lite for Model Inference (JS)](ai/mindspore-lite-js-guidelines.md) - [AI Development](./ai/ai-overview.md)
- [Using MindSpore Lite JavaScript APIs to Develop AI Applications](./ai/mindspore-guidelines-based-js.md)
- [Using MindSpore Lite Native APIs to Develop AI Applications](./ai/mindspore-guidelines-based-native.md)
- Connectivity - Connectivity
- Network Management - Network Management
- [Network Management Overview](connectivity/net-mgmt-overview.md) - [Network Management Overview](connectivity/net-mgmt-overview.md)
...@@ -564,10 +569,14 @@ ...@@ -564,10 +569,14 @@
- [Database Backup and Restoration](database/data-backup-and-restore.md) - [Database Backup and Restoration](database/data-backup-and-restore.md)
- [Database Encryption](database/data-encryption.md) - [Database Encryption](database/data-encryption.md)
- [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md) - [Access Control by Device and Data Level](database/access-control-by-device-and-data-level.md)
- Cross-Application Data Sharing (for System Applications Only) - Cross-Application Data Sharing
- [Cross-Application Data Sharing Overview](database/share-device-data-across-apps-overview.md) - [Data Sharing Overview](database/data-share-overview.md)
- [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md) - [Unified Data Definition](database/unified-data-definition.md)
- [Data Sharing Through Silent Access](database/share-data-by-silent-access.md) - One-to-Many Data Sharing (for System Applications Only)
- [Sharing Data Using DataShareExtensionAbility](database/share-data-by-datashareextensionability.md)
- [Data Sharing Through Silent Access](database/share-data-by-silent-access.md)
- Many-to-Many Data Sharing
- [Sharing Data via Unified Data Channels](database/unified-data-channels.md)
- File Management - File Management
- [File Management Overview](file-management/file-management-overview.md) - [File Management Overview](file-management/file-management-overview.md)
- Application File - Application File
...@@ -601,16 +610,12 @@ ...@@ -601,16 +610,12 @@
- [Setting the Security Level of a Distributed File](file-management/set-security-label.md) - [Setting the Security Level of a Distributed File](file-management/set-security-label.md)
- [Accessing Files Across Devices](file-management/file-access-across-devices.md) - [Accessing Files Across Devices](file-management/file-access-across-devices.md)
- Background Task Management - Background Task Management
- Background Task - [Background Task Overview](task-management/background-task-overview.md)
- [Background Task Management Overview](task-management/background-task-overview.md) - [Transient Task](task-management/transient-task.md)
- [Transient Task Development](task-management/transient-task-dev-guide.md) - [Continuous Task](task-management/continuous-task.md)
- [Continuous Task Development](task-management/continuous-task-dev-guide.md) - [Deferred Task](task-management/work-scheduler.md)
- [Work Scheduler Development](task-management/work-scheduler-dev-guide.md) - [Agent-powered Reminder](task-management/agent-powered-reminder.md)
- [WorkSchedulerExtensionAbility Development](task-management/workscheduler-extensionability.md) - [Requesting Efficiency Resources (for Privileged System Applications Only)](task-management/efficiency-resource-request.md)
- [Efficiency Resource Request Development](task-management/efficiency-resources-apply-dev-guide.md)
- Agent-Powered Reminder
- [Agent-Powered Reminder Overview](task-management/reminder-agent-overview.md)
- [Agent-Powered Reminder Development](task-management/reminder-agent-development.md)
- Device Management - Device Management
- USB Service - USB Service
- [USB Service Overview](device/usb-overview.md) - [USB Service Overview](device/usb-overview.md)
...@@ -930,9 +935,9 @@ ...@@ -930,9 +935,9 @@
- [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md) - [@ohos.distributedMissionManager (Distributed Mission Management)](reference/apis/js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (reminderAgentManager)](reference/apis/js-apis-reminderAgentManager.md) - [@ohos.reminderAgentManager (reminderAgentManager)](reference/apis/js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md) - [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](reference/apis/js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](reference/apis/js-apis-resourceschedule-workScheduler.md) - [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](reference/apis/js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](reference/apis/js-apis-WorkSchedulerExtensionAbility.md)
- application - application
- [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md) - [WorkSchedulerExtensionContext](reference/apis/js-apis-inner-application-WorkSchedulerExtensionContext.md)
- Security - Security
......
...@@ -111,7 +111,7 @@ Grid组件根据rowsTemplate、columnsTemplate属性的设置情况,可分为 ...@@ -111,7 +111,7 @@ Grid组件根据rowsTemplate、columnsTemplate属性的设置情况,可分为
| 名称 | 功能描述 | | 名称 | 功能描述 |
| -------- | -------- | | -------- | -------- |
| onScrollIndex(event: (first: number) => void) | 当前网格显示的起始位置item发生变化时触发。列表初始化时会触发一次。<br/>- first: 当前显示的网格起始位置的索引值。<br/>Grid显示区域上第一个子组件的索引值有变化就会触发。 | | onScrollIndex(event: (first: number) => void) | 当前网格显示的起始位置item发生变化时触发。列表初始化时会触发一次。<br/>- first: 当前显示的网格起始位置的索引值。<br/>Grid显示区域上第一个子组件的索引值有变化就会触发。 |
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | 开始拖拽网格元素时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 被拖拽网格元素索引值。<br/>**说明:** <br/>返回void表示不能拖拽。<br/>手指长按GridItem时触发该事件。 | | onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => (() => any) \| void) | 开始拖拽网格元素时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 被拖拽网格元素索引值。<br/>**说明:** <br/>返回void表示不能拖拽。<br/>手指长按GridItem时触发该事件。<br/>由于拖拽检测也需要长按,且事件处理机制优先触发子组件事件,GridItem上绑定LongPressGesture时无法触发拖拽;如有长按和拖拽同时使用的需求可以使用通用拖拽事件。 |
| onItemDragEnter(event: (event: ItemDragInfo) => void) | 拖拽进入网格元素范围内时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。 | | onItemDragEnter(event: (event: ItemDragInfo) => void) | 拖拽进入网格元素范围内时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。 |
| onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | 拖拽在网格元素范围内移动时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 拖拽起始位置。<br/>- insertIndex: 拖拽插入位置。 | | onItemDragMove(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number) => void) | 拖拽在网格元素范围内移动时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 拖拽起始位置。<br/>- insertIndex: 拖拽插入位置。 |
| onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | 拖拽离开网格元素时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 拖拽离开的网格元素索引值。 | | onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | 拖拽离开网格元素时触发。<br/>- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)<br/>- itemIndex: 拖拽离开的网格元素索引值。 |
...@@ -278,6 +278,10 @@ struct GridExample { ...@@ -278,6 +278,10 @@ struct GridExample {
return this.pixelMapBuilder() //设置拖拽过程中显示的图片。 return this.pixelMapBuilder() //设置拖拽过程中显示的图片。
}) })
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。 .onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { //绑定此事件的组件可作为拖拽释放目标,当在本组件范围内停止拖拽行为时,触发回调。
// isSuccess=false时,说明drop的位置在grid外部;insertIndex > length时,说明有新增元素的事件发生
if (!isSuccess || insertIndex >= this.numbers.length) {
return
}
console.info('beixiang' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置 console.info('beixiang' + itemIndex + '', insertIndex + '') //itemIndex拖拽起始位置,insertIndex拖拽插入位置
this.changeIndex(itemIndex, insertIndex) this.changeIndex(itemIndex, insertIndex)
}) })
......
# Native接口文档注释
> **说明:**
>
> Native API文档由中文头文件生成,中文头文件应遵循以下注释规范才能生成对应文档。
## Module的注释
```
/**
* @addtogroup 模块名
* @{
*
* @brief 一句话描述该库的作用。(请使用动宾结构,如:实现XX功能。)
*
* 详细描述该模块的主要功能、使用场景和使用建议。尤其对这个模块中涉及的逻辑概念,相互关系,在应用中的作用进行说明。
* 比如AOSP中的Choreographer,介绍下这个概念的功能;然后介绍下简单的使用方法
* Choreographer,负责编排帧渲染时间,是java版本的C实现,应用可以利用这个机制安排帧的合理绘制时间点。接口使用
* 1. 注册一个回调函数到这个Choreographer,下一帧的时候调用
* 2. 在下一帧开始的时候,回调被调用,参数会带一个系统返回的FrameCallbackData
* 3. 回调中可以做的处理
* 4. sf根据回调的返回值,进行转换处理
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
*
* @since OS的版本号
*/
...
/** @} */ (如果需要将头文件中具体函数划分到该模块中,则在文件最后加上/** @} */ )
```
## 文件File的注释
```
/**
* @file 头文件名
*
* @brief 一句话简要描述该头文件的作用。
*
* 详细描述该类或接口的主要功能、使用场景和使用建议。覆盖该类的主要功能、使用场景和使用建议。尤其对这个类涉及的逻辑概念,相互关系,在应用中的作用进行说明。\n
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
* @library 引用头文件接口,需要链接的so名字
* @since OS的版本号
*/
```
## 宏定义/变量/常量的注释
```
/**
* @brief 一句话简要描述该宏定义/常量/变量的含义。
*
* 详细描述该宏定义/常量/变量的作用、使用限制和建议、取值范围,以及取到边界值、非法值的后果。\n
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
*
* @deprecated (可选)标记位废弃的接口,需要加上这个标记,并写明从什么版本开发废弃,使用什么接口代替
* @since OS的版本号
*/
```
## 结构体Struct和联合体Union的注释
```
/**
* @brief 一句话简述该结构体或联合体的作用。
*
* 详细描述该结构体或联合体的作用、使用场合和建议等。\n
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
*
* @deprecated (可选)标记位废弃的接口,需要加上这个标记,并写明从什么版本开发废弃,使用什么接口代替
* @since OS的版本号
*/
struct StructName {
/** 描述成员1的含义。 */
unsigned long StructMember1;
/** 描述成员2的含义。 */
unsigned long StructMember2;
};
```
## 枚举Enum的注释
```
/**
* @brief 一句话简述该枚举的作用。
*
* 详细描述该枚举的主要功能、使用场景和使用建议。\n
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
*
* @deprecated (可选)标记位废弃的接口,需要加上这个标记,并写明从什么版本开发废弃,使用什么接口代替
* @since OS的版本号
*/
enum EnumName {
/** 描述枚举值1的含义 */
EnumMermber1,
/** 描述枚举值2的含义 */
EnumMermber2,
/** 描述枚举值3的含义 */
EnumMermber3
};
```
## 函数Function的注释
```
/**
* @brief 一句话简述该函数的作用。
*
* 详细描述该函数的主要功能、使用场景和使用建议。\n
* 详细描述中,如果有多个段落,每段必须以“\n”结束。\n
*
* @param (可选)后接参数名和参数描述,一个参数使用一个@param标记。参数描述写作要点:1.参数的作用、使用限制和建议;2.参数的取值范围,以及取到边界值、非法值的后果;3.如果存在参数设置方面的建议值或经验值,请描述。如果该方法没有参数,则请删除该标记。
* @return (可选)后接返回描述。如果该函数没有返回值,则请删除该标记。
* @see (可选)当存在与该函数相关联的函数时(功能相近或者存在关系),可以通过@see建立到参考函数的链接。如果需要链接多个函数,每个函数使用一个@see标记。如果不涉及,则请删除该标记。
* @permission (可选)对权限有要求的接口需要写
* @deprecated (可选)标记位废弃的接口,需要加上这个标记,并写明从什么版本开发废弃,使用什么接口代替
* @since OS的版本号
*/
```
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册