提交 89b9f2ee 编写于 作者: E esterzhou

update doc (12902)

Signed-off-by: Nesterzhou <ester.zhou@huawei.com>
上级 ce1bfb11
# ArkUI (ArkTS) Development
## What are the restrictions on using generator functions in TypeScript?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Below are the restrictions on using generator functions in TypeScript:
- Expressions can be used only in character strings (in the ${expression} format), **if** conditions, **ForEach** parameters, and component parameters.
- No expressions should cause any application state variables (including **\@State**, **\@Link**, and **\@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur.
- The generator function cannot contain local variables.
None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**).
Negative example:
```
build() {
let a: number = 1 // invalid: variable declaration not allowed
Column() {
Text('Hello ${this.myName.toUpperCase()}') // ok.
ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place
}
buildSpecial() // invalid: no function calls
Text(this.calcTextValue()) // this function call is ok.
}
```
## How do I use router to implement page redirection in the stage model?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file.
1. To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file.
2. Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase.
Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase.
Reference: [Page Routing](../reference/apis/js-apis-router.md)
## Will a page pushed into the stack through router.push be reclaimed?
......@@ -45,82 +16,6 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
After being pushed to the stack through **router.push**, a page can be reclaimed only when it is popped from the stack through **router.back**.
## How do I dynamically replace the %s placeholder in a resource file?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
In an application, you can replace the %s placeholder by using the second parameter in `$r('app.string.xx')`, which is used to reference application resources.
Example:
```
build() {
//do something
// The second parameter indicates the referenced string resource, which can be used to replace the %s placeholder.
Text($r('app.string.entry_desc','aaa'))
.fontSize(100)
.fontColor(Color.Black)
//do something
}
```
## How do I read an XML file in Resource and convert data in it to the string type?
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
1. Obtain data in Uint8Array format by calling the **RawFile** API of **resourceManager**.
2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API.
Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md)
Example:
```
resourceManager.getRawFile(path, (error, value) => {
if (error != null) {
console.log("error is " + error);
} else {
let rawFile = value;
let xml = String.fromCharCode.apply(null, rawFile)
}
});
```
## How do I convert a Resource object to the string type?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Use the **resourceManager.getString()** API of the **\@ohos.resourceManager** module.
Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md#getstring)
## What should I do if the global static variables of a class do not work?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables.
## How do I obtain resources in the stage model?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model.
Example:
```
const context = getContext(this) as any
context
.resourceManager
.getString($r('app.string.entry_desc').id)
.then(value => {
this.message = value.toString()
})
```
## How do I position a container component to the bottom of the screen?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
......@@ -152,7 +47,7 @@ build() {
Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
No. Currently, **CustomDialog** can be used only on ArkTS pages.
No. **CustomDialog** can be used only on ArkTS pages.
Reference: [Custom Dialog Box](../reference/arkui-ts/ts-methods-custom-dialog-box.md)
......@@ -166,32 +61,70 @@ Example:
```
// CustomDialog component
// Dialog box component
@CustomDialog
struct MyDialog {
controller: CustomDialogController
title: string
data: string
cancel: () => void
confirm: (data: string) => void
Button('confirm')
.onClick(() => {
this.controller.close()
this.data = 'test'
this.confirm(this.data)
}).backgroundColor(0xffffff).fontColor(Color.Red)
// Page
data: string = ''
build() {
Row() {
Column({ space: 10 }) {
Text(this.title)
.fontSize(30)
.fontColor(Color.Blue)
TextInput({ placeholder: "Enter content", text: this.data })
.onChange((data) => {
this.data = data // Obtain the data in the text box.
})
Button('confirm')
.onClick(() => {
this.confirm(this.data) // Transfer the data in the text box to the main page through the callback.
this.controller.close()
}).backgroundColor(0xffffff).fontColor(Color.Red)
}.width("50%")
}.height("50%")
}
}
// Main page
@Entry
@Component
struct DialogTest {
@State dialogTitle: string = ''
@State dialogData: string = ''
dialogController: CustomDialogController = new CustomDialogController({
builder: MyDialog({ title:'Custom Title',cancel: this.onCancel,
confirm: this.onAccept.bind(this)}), // Bind the custom callback to the button.
cancel: this.existApp,
autoCancel: true
builder: MyDialog({
title: this.dialogTitle, // Bind data.
data: this.dialogData,
confirm: this.confirm.bind(this) // Bind the custom callback. Change the direction of this here.
})
})
onAccept(data:string) {
console.info('Callback when the second button is clicked ' + data)
confirm(data: string) {
this.dialogData = data
console.info(`recv dialog data: ${data}`) // Obtain the information entered in the dialog box.
}
build() {
Row() {
Column({ space: 10 }) {
Button ('Open Dialog Box')
.onClick(() => {
this.dialogTitle ='Dialog Box'
this.dialogController.open()
})
Text(`Accept pop-up window data:`)
.fontSize(20)
TextInput ({ placeholder: "Input", text: this.dialogData })
.width("50%")
.onChange((data) => {
this.dialogData = data //Obtain the data in the text box.
})
}.width("100%")
}.height("100%")
}
}
```
......@@ -210,7 +143,7 @@ By default, child components in a **\<GridContainer>** are horizontally aligned
Nest a **\<Row>** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](../reference/arkui-ts/ts-container-gridcontainer.md).
Example:
Example:
```
GridContainer({ sizeType: SizeType.SM, columns: 12 }) {
......@@ -247,7 +180,7 @@ async function enterImmersion(mainWindow: window.Window) {
})
await mainWindow.setFullScreen(true)
await mainWindow.setSystemBarEnable(["status", "navigation"])
await mainWindow.setSystemBarProperties({
await mainWindow.sArkTSystemBarProperties({
navigationBarColor: "#00000000",
statusBarColor: "#00000000",
navigationBarContentColor: "#FF0000",
......@@ -265,16 +198,459 @@ export default class MainAbility extends Ability {
}
```
## How do I execute JavaScript functions in the \<Web> component in ArkTS code?
## How do I fix misidentification of the pan gesture where container nesting is involved?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**.
## How do I obtain the height of a component?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
You can obtain the changes in the width and height of a component through **onAreaChange**.
Example:
```
Column() {
Text(this.value)
.backgroundColor(Color.Green).margin(30).fontSize(20)
.onClick(() => {
this.value = this.value + 'Text'
})
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`)
this.size = JSON.stringify(newValue)
})
```
## How do I obtain the offset of the \<List> component?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Call the **runJavaScript** API in the **WebController** to asynchronously execute JavaScript scripts. This API uses a callback to return the execution result. Note: **runJavaScript** can only be called after **loadUrl** has been completed. For example, it can be called in **onPageEnd**.
Bind the **\<List>** component to a **Scoller** object and obtain the offset through **currentOffset**.
Reference: [Web](../reference/arkui-ts/ts-basic-components-web.md)
Example:
## How do I fix misidentification of the pan gesture where container nesting is involved?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
```
Column() {
List({ space: 20, initialIndex: 0,scroller: this.scroller}) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.editable(true)
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.editMode(this.editFlag)
.onScroll((xOffset: number, yOffset: number) => {
console.info("yOffset======="+this.scroller.currentOffset().yOffset)
})
}.width('100%')
```
Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**.
## How do I obtain the value of param for the target page of redirection implemented using router?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
```
// In versions earlier than 3.1.5.5, obtain the value through router.getParams().key.
private value: string = router.getParams().value;
// In 3.1.6.5 and later versions, obtain the value through router.getParams()['key'].
private value: string = router.getParams()['value'];
```
## Does the \<RichText> component support redirection to a local page?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
No. This feature is not supported.
## How do I disable the transition effect for pages switched using router or navigator?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
1. Define the **pageTransition** method for the current and target pages, by following instructions in [Example](../reference/arkui-ts/ts-page-transition-animation.md#example).
2. Set the **duration** parameter of both **PageTransitionEnter** and **PageTransitionExit** to **0**.
## How do I select the pixel unit during UI development?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
It depends.
The vp unit ensures consistency of visual effects across resolutions. For example, it ensures that an icon is displayed consistently under different resolutions.
The lpx unit produces a visual effect where items are zoomed in or out proportionally.
If you are concerned about visual effect consistency of items, for example, buttons, texts, and lists, use the vp unit. If your focus is on the layout, for example, 1/2 grid, the lpx is a better choice.
## What color formats are used in ArkTS?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
The color can be represented in two formats, for example, 0x7F000000 or '\#7F000000'. The first two digits indicate opacity, and the last six digits indicate RGB.
```
fontColor(0x7F000000)
fontColor( '#7F000000' )
```
## How do I listen for the return operation on a page?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
When a return operation is performed on a page, the system calls the **onBackPress()** callback of the **@Entry** decorated custom component. You can implement related service logic in the callback.
Reference: [Custom Component Lifecycle Callbacks](../ui/ui-ts-custom-component-lifecycle-callbacks.md)
## Can I customize the eye icon for the \<TextInput> component in password mode?
Applicable to: OpenHarmony SDK 3.0, stage model of API version 9
No. The eye icon can be shown or hidden through **showPasswordIcon** when **type** of the **\<TextInput>** component is set to **InputType.Password**. It cannot be customized.
Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md)
## Why can't images be loaded over HTTP?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
HTTP is insecure and HTTP sources will be filtered out by the trustlist. For security purposes, use HTTPS.
## What should I do if the spacing set for the TextView layout does not fit the UI?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
By default, the **align** attribute of **TextView** is set to **Center**. To display the text from left to right, set the **align** attribute to **Start**.
## Why do the constraintSize settings fail to take effect?
Applicable to: OpenHarmony SDK 3.0, stage model of API version 9
If **constraintSize** is set for a component and the width of its child component is set to a percentage, for example, **width('100%')**, **constraintSize** takes effect by multiplying the maximum width by the percentage. As a result, the child component may overflow, in which case it looks like the **constraintSize** settings fail to take effect.
## How do I set the background color to transparent?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Set **backgroundColor** to **'\#00000000'**.
## What should I do if the \<Scroll> component cannot scroll to the bottom?
Applicable to: OpenHarmony SDK 3.0, stage model of API version 9
Unless otherwise specified, the height of the **\<Scroll>** component is equal to the window height. In this case, the component's bottom area will be blocked by components (if any) outside of it. To fix this issue, set the height of the **\<Scroll>** component or use the flex layout to limit this height.
## How do I use the onSubmit event of the \<TextInput> component?
Applicable to: OpenHarmony SDK 3.0, stage model of API version 9
The **onSubmit** event is triggered when the Enter key is pressed and accepts the current Enter key type as its input parameter. You can set the Enter key type for the **\<TextInput>** component through the **enterKeyType** attribute. The Enter key style of the soft keyboard requires the support of the input method.
Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md)
## What is the maximum number of pages allowed during page routing?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The maximum number of pages supported by the page stack is 32. When this limit is reached, the **router.push** API cannot be used for page redirection.
## Does ArkUI allow components to be dynamically created in code?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Yes. You can dynamically creaete components using [conditional rendering](../quick-start/arkts-rendering-control.md#conditional-rendering) and [loop rendering](../quick-start/arkts-rendering-control.md#loop-rendering).
## What should I do if the PixelMap object carried in page routing cannot be obtained from the target page?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Page routing supports only the common object type and common JSON data structure. To pass a **PixelMap** object to the target page, store it in the **localStorage**.
## How do I use .caretPosition(0) to move the caret to the start of the text area when onEditChange is triggered for the \<TextInput> component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The **onEditChange** event is triggered when the input box gains focus. Under this scenario, the caret position is related to the position where the gesture is when the event is triggered, and **caretPosition** cannot be used to change the caret position. Call **setTimeout** for asynchronous processing first.
## Is there any method for selecting all items in the \<TextInput> component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
No. This feature is not supported yet.
## Why can't I select a date when the type attribute of the input text box is set to date?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Setting the **type** attribute of the input component to **date** means that the component accepts dates as input and the user will be notified of the valid input format. It does not display a date picker. To display a date picker, use the **\<DatePicker>** component.
## What should I do if the displayed input keyboard gets squeezed when using the **\<TextInput>** component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
This issue may occur when the flex layout is used. To fix it, switch to the column layout.
## How does the parent component pass values to a @Link decorated member variable in its child component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
To pass a value from the parent component to the **@Link** decorated member variable in a child component, add **"$"** in front of the value.
Example:
```
@Component
struct FoodImageDisplay {
@Link imageSrc: Resource
build() {
Stack({ alignContent: Alignment.BottomStart }) {
Image(this.imageSrc)
.objectFit(ImageFit.Contain)
Text('Tomato')
.fontSize(26)
.fontWeight(500)
.margin({ left: 26, bottom: 17.4 })
}
.backgroundColor('#FFedf2f5')
.height(357)
}
}
@Entry
@Component
struct FoodDetail {
@State imageSrc: Resource = $r('app.media.Tomato')
build() {
Column() {
FoodImageDisplay({imageSrc:$imageSrc})
}
.alignItems(HorizontalAlign.Center)
}
}
```
## How do I share variables between Page abilities?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
1. Use a lightweight database.
2. Use persistent data management.
3. Use the emitter event communication mechanism.
## How do I customize the control bar style of the \<Video> component?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
1. Set **controls** to **false** to disable the default control bar.
2. Set **controller** for the **\<Video>** component.
3. Implement a custom control bar in ArkTS and use **VideoController** to control video playback.
## How do I optimize the performance when an ArkTS component is to be updated for multiple times?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Extract the ArkTS component to be updated into a custom component and update the **@State** decorated variables in the custom component to implement partial refresh.
## How do I optimize the \<Tab> component performance?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
When the **\<Tab>** component is on a tab page, other tab pages are not unloaded by the system and still occupy some memory. To improve performance, you can use **if** to check whether the current tab page is being displayed and unload it if it is not. In this way, the tab pages not being displayed can be unloaded and the memory occupied by them can be released.
## How do I set state-specific styles for a component?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
You can use the polymorphic style attribute to set styles of the component for different states (being stateless, in pressed state, in disabled state, in focused state, or in clicked state).
Reference: [Polymorphic Style](../reference/arkui-ts/ts-universal-attributes-polymorphic-style.md)
## Why can't the onBlur or onFocus callback be triggered?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Only the Tab button and arrow buttons on the connected keyboard can be used to trigger the focus event. In addition, to trigger a focus event by a touch, the **focusOnTouch** attribute must be added for the component.
Reference: [Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md)
## What should I do if the flex width and height in the \<Scroll> component conflicts with the scrolling?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The **\<Scroll>** component supports a single child component, whose height is subject to the content height. If the scrolling layout is abnormal due to asynchronous loading of an image within the content, you can set the minimum height for the child component through **constraintSize({ minHeight: '100%' })**.
## How do I block the page router from returning to the previous page?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Call **router.clear()** to remove all historical pages in the page stack and retain the current page at the top of the stack.
Reference: [Page Routing](../reference/apis/js-apis-router.md)
## How do I clear the content of the \<TextInput> component at once?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Refer to the following:
```
struct Index {
@State text: string = 'Hello World'
controller: TextInputController = new TextInputController()
build() {
Row() {
Column() {
TextInput({ placeholder: 'Please input your words.', text: this.text,
controller:this.controller}).onChange((value) => {
this.text = value
})
Button("Clear TextInput").onClick(() => {
this.text = "";
})
}
.width('100%')
}
.height('100%')
}
}
```
## Can tab switching be disabled for the \<Tabs> component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
No. This feature is not supported.
## An error is reported when @state is used to decorate the id member variable: "TypeError: cannot read property 'get' of undefined." Why?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The ID has been added as a unique value and becomes a keyword.
## Can I use the fontFamily attribute to set different fonts for OpenHarmony applications?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
No. For applications developed based on OpenHarmony, the default font and also the only supported font is HarmonyOS Sans.
## What is the recommended data interaction mode between an ability and UI page?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
[LocalStorage](../quick-start/arkts-state-mgmt-application-level.md#localstorage) is recommended.
## How does a parent component synchronize status with its grandchild components?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
- Method 1 (recommended): Use the **@Provide** and **@Consume** decorators. Specifically, use **@Provide** in the parent component and **@Consume** in the grandchild component to implement two-way data binding between the components.
- Method 2: Use the **@State** and **@Link** decorators. Specifically, use **@State** in the parent component, and **@Link** in all involved child and grandchild components.
## How do I display an ellipsis in cases when the string is too long to display in full?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
Example:
```
beautySub(str,len) {
var reg = /[\u4e00-\u9fa5]/g;
// Reduce characters whenever possible.
var slice = str.substring(0,len)
var charNum = (~~(slice.match(reg) && slice.match(reg).length))
// The purpose of charNum-1 is to process the string that exceeds the maximum value. If the string exceeds the maximum value, the character that is not in current language is not displayed.
var realen = slice.length*2 - charNum-1
return str.substr(0,realen) + (realen < str.length ? "..." : "") +str.substr(str.length-realen,str.length)
}
```
## How do I add a scrollbar to the \<richText> component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
The **\<RichText>** component is underpinned by web. To add a scrollbar, you can refer to the HTML syntax and add the **overflow: auto** style to **div**.
## How do I disable the scroll event of a grid in the \<Scroll> component?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
You can use the **onScrollBegin** event and the **scrollBy** method to implement nested scrolling of the containers.
Reference: [Scroll](../reference/arkui-ts/ts-container-scroll.md#example-2)
## Can the white background of the custom dialog box be removed?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
No. This feature is not supported. The UI style is hardcoded in the framework and cannot be changed.
## Does the **backgroundImage** API support the SVG image format?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
No. This image format is not supported.
## How do I set the position for a custom dialog box?
Applicable to: OpenHarmony SDK 3.2.7.5, stage model of API version 9
You can set the position for a custom dialog box through the **alignment** parameter. For example, to set the custom dialog box to show at the bottom, set **alignment** to **DialogAlignment.Bottom**.
Reference: [Custom Dialog Box](../reference/arkui-ts/ts-methods-custom-dialog-box.md)
## How does the scroller determine the end error of the rebound animation?
Applicable to: OpenHarmony SDK 3.2.5.3, FA model of API version 8
After the touch ends, a change in the same direction may be calculated. If the change is in the opposite direction, it indicates that a rebound occurs, and no processing is performed.
## How do I implement persistent storage of application data?
Use the **PersistentStorage** class to manage persistent application data. Persistent data with specific tags can be linked to the **AppStorage** and accessed through the **AppStorage** APIs.
Reference: [PersistentStorage](../quick-start/arkts-state-mgmt-application-level.md#persistentstorage)
Example:
```
AppStorage.Link('varA')
PersistentStorage.PersistProp("varA", "111");
@Entry
@Componentstruct Index {
@StorageLink('varA') varA: string = ''
build() {
Column() {
Text('varA: ' + this.varA).fontSize(20)
Button('Set').width(100).height(100).onClick(() => {
this.varA += '333'
})
}
.width('100%')
.height('100%')
}
}
```
# Screen Lock Management
# @ohos.screenLock
The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set.
......@@ -12,445 +12,450 @@ The **screenlock** module is a system module in OpenHarmony. It provides APIs fo
import screenlock from '@ohos.screenLock';
```
## screenlock.isScreenLocked
isScreenLocked(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the screen is locked. This API uses an asynchronous callback to return the result.
## EventType
> **NOTE**
>
>This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked<sup>9+</sup>](#screenlockislocked9) instead.
Defines the system event type.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Parameters**
| Event Type | Description |
| ------------------ | ------------------------ |
| beginWakeUp | Wakeup starts.|
| endWakeUp | Wakeup ends.|
| beginScreenOn | Screen turn-on starts.|
| endScreenOn | Screen turn-on ends.|
| beginScreenOff | Screen turn-off starts.|
| endScreenOff | Screen turn-off ends.|
| unlockScreen | The screen is unlocked. |
| lockScreen | The screen is locked. |
| beginExitAnimation | Exit animation starts. |
| beginSleep | The device enters sleep mode. |
| endSleep | The device exits sleep mode. |
| changeUser | The user is switched. |
| screenlockEnabled | Screen lock is enabled. |
| serviceRestart | The screen lock service is restarted. |
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ----------------------------------------------------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.|
## SystemEvent
**Example**
Defines the structure of the system event callback.
```js
screenlock.isScreenLocked((err, data)=>{
if (err) {
console.error('isScreenLocked callback error -> ${JSON.stringify(err)}');
return;
}
console.info('isScreenLocked callback success data -> ${JSON.stringify(data)}');
});
```
**System capability**: SystemCapability.MiscServices.ScreenLock
## screenlock.isScreenLocked
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------- |
| eventType | [EventType](#eventtype) | Yes | System event type.|
| params | string | Yes | System event parameters.|
isScreenLocked(): Promise&lt;boolean&gt;
## screenlock.isLocked<sup>9+</sup>
Checks whether the screen is locked. This API uses a promise to return the result.
isLocked(): boolean
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked<sup>9+</sup>](#screenlockislocked9) instead.
Checks whether the screen is locked.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.|
| Type | Description |
| ------- | ------------------------------------------------- |
| boolean | Returns **true** if the screen is locked; returns **false** otherwise.|
**Example**
```js
screenlock.isScreenLocked().then((data) => {
console.log('isScreenLocked success: data -> ${JSON.stringify(data)}');
}).catch((err) => {
console.error('isScreenLocked fail, promise: err -> ${JSON.stringify(err)}');
});
let isLocked = screenlock.isLocked();
```
## screenlock.isLocked<sup>9+</sup>
## screenlock.isSecure<sup>9+</sup>
isLocked(): boolean
isSecure(): boolean
Checks whether the screen is locked. This API returns the result synchronously.
Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ------- | ------------------------------------------------- |
| boolean | Returns **true** if the screen is locked; returns **false** otherwise.|
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the device is in secure mode; returns **false** otherwise.|
**Example**
```js
let isLocked = screenlock.isLocked();
let isSecure = screenlock.isSecure();
```
## screenlock.isSecureMode
isSecureMode(callback: AsyncCallback&lt;boolean&gt;): void
## screenlock.unlock<sup>9+</sup>
Checks whether the device is in secure mode. This API uses an asynchronous callback to return the result.
unlock(callback: AsyncCallback&lt;boolean&gt;): void
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure<sup>9+</sup>](#screenlockissecure9) instead.
Unlocks the screen. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.|
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.|
**Example**
```js
screenlock.isSecureMode((err, data)=>{
screenlock.unlock((err, data) => {
if (err) {
console.error('isSecureMode callback error -> ${JSON.stringify(err)}');
console.error(`Failed to unlock the screen, because: ${err.message}`);
return;
}
console.info('isSecureMode callback success data -> ${JSON.stringify(err)}');
console.info(`unlock the screen successfully. result: ${data}`);
});
```
## screenlock.isSecureMode
isSecureMode(): Promise&lt;boolean&gt;
## screenlock.unlock<sup>9+</sup>
Checks whether the device is in secure mode. This API uses a promise to return the result.
unlock(): Promise&lt;boolean&gt;
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure<sup>9+</sup>](#screenlockissecure9) instead.
Unlocks the screen. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.|
| Type | Description |
| ------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.|
**Example**
```js
screenlock.isSecureMode().then((data) => {
console.log('isSecureMode success: data->${JSON.stringify(data)}');
screenlock.unlock().then((data) => {
console.info(`unlock the screen successfully. result: ${data}`);
}).catch((err) => {
console.error('isSecureMode fail, promise: err->${JSON.stringify(err)}');
console.error(`Failed to unlock the screen, because: ${err.message}`);
});
```
## screenlock.isSecure<sup>9+</sup>
## screenlock.lock<sup>9+</sup>
isSecure(): boolean
lock(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the device is in secure mode.
Locks the screen. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
**System API**: This is a system API.
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | The value **true** means that the device is in secure mode, and **false** means the opposite.|
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.|
**Example**
```js
let isSecure = screenlock.isSecure();
screenlock.lock((err, data) => {
if (err) {
console.error(`Failed to lock the screen, because: ${err.message}`);
return;
}
console.info(`lock the screen successfully. result: ${data}`);
});
```
## screenlock.unlockScreen
unlockScreen(callback: AsyncCallback&lt;void&gt;): void
## screenlock.lock<sup>9+</sup>
Unlocks the screen. This API uses an asynchronous callback to return the result.
lock(): Promise&lt;boolean&gt;
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock<sup>9+</sup>](#screenlockunlock9) instead.
Locks the screen. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Parameters**
**System API**: This is a system API.
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | --------------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation fails, an error message is returned.|
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.|
**Example**
```js
screenlock.unlockScreen((err) => {
if (err) {
console.error('unlockScreen callback error -> ${JSON.stringify(err)}');
return;
}
console.info('unlockScreen callback success');
screenlock.lock().then((data) => {
console.info(`lock the screen successfully. result: ${data}`);
}).catch((err) => {
console.error(`Failed to lock the screen, because: ${err.message}`);
});
```
## screenlock.unlockScreen
## screenlock.onSystemEvent<sup>9+</sup>
unlockScreen(): Promise&lt;void&gt;
onSystemEvent(callback: Callback&lt;SystemEvent&gt;): boolean
Unlocks the screen. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock<sup>9+</sup>](#screenlockunlock9) instead.
Registers a callback for system events related to screen locking.
**System capability**: SystemCapability.MiscServices.ScreenLock
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ----------------- |
| callback | Callback\<[SystemEvent](#systemevent)> | Yes | Callback for system events related to screen locking.|
**Return value**
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
| Type | Description |
| ------- | ------------------------------------------------- |
| boolean | Returns **true** if the callback is registered successfully; returns **false** otherwise.|
**Example**
```js
screenlock.unlockScreen().then(() => {
console.log('unlockScreen success');
}).catch((err) => {
console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}');
});
try {
let isSuccess = screenlock.onSystemEvent((event) => {
console.log(`Register the system event which related to screenlock successfully. eventType: ${event.eventType}`)
});
} catch (err) {
console.error(`Failed to register the system event which related to screenlock, because: ${err.message}`)
}
```
## screenlock.unlock<sup>9+</sup>
## screenlock.sendScreenLockEvent<sup>9+</sup>
unlock(callback: AsyncCallback&lt;boolean&gt;): void
sendScreenLockEvent(event: string, parameter: number, callback: AsyncCallback&lt;boolean&gt;): void
Unlocks the screen. This API uses an asynchronous callback to return the result.
Sends an event to the screen lock service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.|
| Name | Type | Mandatory| Description |
| --------- | ------------------------ | ---- | -------------------- |
| event | string | Yes | Event type.<br>- **"unlockScreenResult"**: Screen unlock result.<br>- **"lockScreenResult"**: Screen lock result.<br>- **"screenDrawDone"**: Screen drawing is complete.|
| parameter | number | Yes | Result.<br>- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.<br>- **1**, the operation fails. For example, screen locking or unlocking fails.<br>- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite. |
**Example**
```js
screenlock.unlock((err,data) => {
screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => {
if (err) {
console.error('unlock error -> ${JSON.stringify(err)}');
return;
console.error(`Failed to send screenlock event, because: ${err.message}`);
return;
}
console.info('unlock success data -> ${JSON.stringify(data)}');
console.info(`Send screenlock event successfully. result: ${result}`);
});
```
## screenlock.unlock<sup>9+</sup>
## screenlock.sendScreenLockEvent<sup>9+</sup>
unlock(): Promise&lt;boolean&gt;
sendScreenLockEvent(event: string, parameter: number): Promise&lt;boolean&gt;
Unlocks the screen. This API uses a promise to return the result.
Sends an event to the screen lock service. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | --------------------------------------- |
| event | string | Yes | Event type.<br>- **"unlockScreenResult"**: Screen unlock result.<br>- **"lockScreenResult"**: Screen lock result.<br>- **"screenDrawDone"**: Screen drawing is complete.|
| parameter | number | Yes | Result.<br>- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.<br>- **1**, the operation fails. For example, screen locking or unlocking fails.<br>- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.|
**Return value**
| Type | Description |
| ------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.|
| Type | Description |
| ----------------- | ---------------------------------------------- |
| Promise\<boolean> | Promise used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite.|
**Example**
```js
screenlock.unlock().then((data) => {
console.log('unlock success');
screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => {
console.info(`Send screenlock event successfully. result: ${result}`);
}).catch((err) => {
console.error('unlock fail, : err->${JSON.stringify(err)}');
console.error(`Failed to send screenlock event, because: ${err.message}`);
});
```
## screenlock.lock<sup>9+</sup>
## screenlock.isScreenLocked<sup>(deprecated)</sup>
lock(callback: AsyncCallback&lt;boolean&gt;): void
isScreenLocked(callback: AsyncCallback&lt;boolean&gt;): void
Locks the screen. This API uses an asynchronous callback to return the result.
Checks whether the screen is locked. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked<sup>9+</sup>](#screenlockislocked9) instead.
**System API**: This is a system API.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ---------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.|
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ----------------------------------------------------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.|
**Example**
```js
screenlock.lock((err,data) => {
screenlock.isScreenLocked((err, data)=>{
if (err) {
console.error('lock callback error -> ${JSON.stringify(err)}');
console.error(`Failed to obtain whether the screen is locked, because: ${err.message}`);
return;
}
console.info('lock callback success');
console.info(`Obtain whether the screen is locked successfully. result: ${data}`);
});
```
## screenlock.lock<sup>9+</sup>
## screenlock.isScreenLocked<sup>(deprecated)</sup>
lock(): Promise&lt;boolean&gt;
isScreenLocked(): Promise&lt;boolean&gt;
Locks the screen. This API uses a promise to return the result.
Checks whether the screen is locked. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked<sup>9+</sup>](#screenlockislocked9) instead.
**System API**: This is a system API.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.|
| Type | Description |
| ---------------------- | ------------------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.|
**Example**
```js
screenlock.lock().then((data) => {
console.log('lock success');
screenlock.isScreenLocked().then((data) => {
console.info(`Obtain whether the screen is locked successfully. result: ${data}`);
}).catch((err) => {
console.error('lock fail, promise: err->${JSON.stringify(err)}');
console.error(`Failed to obtain whether the screen is locked, because: ${err.message}`);
});
```
## EventType
Defines the system event type.
**System capability**: SystemCapability.MiscServices.ScreenLock
| Event Type | Description |
| ------------------ | ------------------------ |
| beginWakeUp | Wakeup starts when the event starts.|
| endWakeUp | Wakeup ends when the event ends.|
| beginScreenOn | Screen turn-on starts when the event starts.|
| endScreenOn | Screen turn-on ends when the event ends.|
| beginScreenOff | Screen turn-off starts when the event starts.|
| endScreenOff | Screen turn-off ends when the event ends.|
| unlockScreen | The screen is unlocked. |
| lockScreen | The screen is locked. |
| beginExitAnimation | Animation starts to exit. |
| beginSleep | The screen enters sleep mode. |
| endSleep | The screen exits sleep mode. |
| changeUser | The user is switched. |
| screenlockEnabled | Screen lock is enabled. |
| serviceRestart | The screen lock service is restarted. |
## screenlock.isSecureMode<sup>(deprecated)</sup>
isSecureMode(callback: AsyncCallback&lt;boolean&gt;): void
## SystemEvent
Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. This API uses an asynchronous callback to return the result.
Defines the structure of the system event callback.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure<sup>9+</sup>](#screenlockissecure9) instead.
**System capability**: SystemCapability.MiscServices.ScreenLock
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------- |
| eventType | [EventType](#eventtype) | Yes | System event type.|
| params | string | Yes | System event parameters.|
**Parameters**
## screenlock.onSystemEvent<sup>9+</sup>
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.|
onSystemEvent(callback: Callback\<SystemEvent\>): boolean
**Example**
Registers a callback for system events related to screen locking.
```js
screenlock.isSecureMode((err, data)=>{
if (err) {
console.error(`Failed to obtain whether the device is in secure mode, because: ${err.message}`);
return;
}
console.info(`Obtain whether the device is in secure mode successfully. result: ${data}`);
});
```
**System capability**: SystemCapability.MiscServices.ScreenLock
## screenlock.isSecureMode<sup>(deprecated)</sup>
**System API**: This is a system API.
isSecureMode(): Promise&lt;boolean&gt;
**Parameters**
Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ---------------------------- |
| callback | Callback\<[SystemEvent](#systemevent)> | Yes | Callback for system events related to screen locking.|
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure<sup>9+</sup>](#screenlockissecure9) instead.
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ------- | ------------------------------------------------- |
| boolean | Returns **true** if the callback is registered successfully; returns **false** otherwise.|
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.|
**Example**
```js
let isSuccess = screenlock.onSystemEvent((event)=>{
console.log(`onSystemEvent:callback:${event.eventType}`)
screenlock.isSecureMode().then((data) => {
console.info(`Obtain whether the device is in secure mode successfully. result: ${data}`);
}).catch((err) => {
console.error(`Failed to obtain whether the device is in secure mode, because: ${err.message}`);
});
if (!isSuccess) {
console.log(`onSystemEvent result is false`)
}
```
## screenlock.unlockScreen<sup>(deprecated)</sup>
## screenlock.sendScreenLockEvent<sup>9+</sup>
unlockScreen(callback: AsyncCallback&lt;void&gt;): void
sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback\<boolean>): void
Unlocks the screen. This API uses an asynchronous callback to return the result.
Sends an event to the screen lock service. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock<sup>9+</sup>](#screenlockunlock9) instead.
**System capability**: SystemCapability.MiscServices.ScreenLock
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory| Description |
| --------- | ------------------------ | ---- | -------------------- |
| event | String | Yes | Event type.<br>- **"unlockScreenResult"**: Screen unlock result.<br>- **"screenDrawDone"**: Screen drawing is complete.|
| parameter | number | Yes | Screen unlock status.<br>- **0**: The unlock is successful.<br>- **1**: The unlock failed.<br>- **2**: The unlock was canceled.|
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. The value **true** means that the operation is successful, and **false** means the opposite. |
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | --------------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the screen is unlocked successfully, **err** is **undefined**; otherwise, **err** is an error object.|
**Example**
```js
screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => {
console.log('sending result:' + result);
screenlock.unlockScreen((err) => {
if (err) {
console.error(`Failed to unlock the screen, because: ${err.message}`);
return;
}
console.info('unlock the screen successfully.');
});
```
## screenlock.sendScreenLockEvent<sup>9+</sup>
sendScreenLockEvent(event: String, parameter: number): Promise\<boolean>
Sends an event to the screen lock service. This API uses a promise to return the result.
## screenlock.unlockScreen<sup>(deprecated)</sup>
**System capability**: SystemCapability.MiscServices.ScreenLock
unlockScreen(): Promise&lt;void&gt;
**System API**: This is a system API.
Unlocks the screen. This API uses a promise to return the result.
**Parameters**
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock<sup>9+</sup>](#screenlockunlock9) instead.
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | --------------------------------------- |
| event | String | Yes | Event type.<br>- **"unlockScreenResult"**: Screen unlock result.<br>- **"screenDrawDone"**: Screen drawing is complete.|
| parameter | number | Yes | Screen unlock status.<br>- **0**: The unlock is successful.<br>- **1**: The unlock failed.<br>- **2**: The unlock was canceled.|
**System capability**: SystemCapability.MiscServices.ScreenLock
**Return value**
| Type | Description |
| ------------------ | ------------------------------------------------------------ |
| Promise\<boolean> | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.|
| Type | Description |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => {
console.log('sending result:' + result);
screenlock.unlockScreen().then(() => {
console.info('unlock the screen successfully.');
}).catch((err) => {
console.error(`Failed to unlock the screen, because: ${err.message}`);
});
```
# @ohos.wallpaper
The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers.
The **wallpaper** module is a system service module in OpenHarmony that provides the wallpaper management service. You can use the APIs of this module to show, set, and switch between wallpapers.
> **NOTE**
>
......@@ -63,7 +63,12 @@ Obtains the main color information of the wallpaper of the specified type.
**Example**
```js
let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
try {
let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
console.log(`success to getColorsSync: ${JSON.stringify(colors)}`);
} catch (error) {
console.error(`failed to getColorsSync because: ${JSON.stringify(error)}`);
}
```
## wallpaper.getIdSync<sup>9+</sup>
......@@ -84,12 +89,17 @@ Obtains the ID of the wallpaper of the specified type.
| Type| Description|
| -------- | -------- |
| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).|
**Example**
```js
let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
try {
let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
console.log(`success to getIdSync: ${JSON.stringify(id)}`);
} catch (error) {
console.error(`failed to getIdSync because: ${JSON.stringify(error)}`);
}
```
## wallpaper.getMinHeightSync<sup>9+</sup>
......@@ -187,7 +197,7 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the wallpaper is reset, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
......@@ -247,14 +257,14 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
```js
//The source type is string.
// The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
......@@ -300,7 +310,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
......@@ -312,7 +322,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
**Example**
```js
//The source type is string.
// The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setImage.`);
......@@ -365,7 +375,12 @@ Obtains the wallpaper of the specified type.
**Example**
```js
let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
try {
let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
console.log(`success to getFileSync: ${JSON.stringify(file)}`);
} catch (error) {
console.error(`failed to getFileSync because: ${JSON.stringify(error)}`);
}
```
## wallpaper.getImage<sup>9+</sup>
......@@ -385,7 +400,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.|
**Example**
......@@ -422,7 +437,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p
| Type| Description|
| -------- | -------- |
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.|
**Example**
......@@ -452,10 +467,14 @@ Subscribes to the wallpaper color change event.
**Example**
```js
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
try {
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
} catch (error) {
console.error(`failed to on because: ${JSON.stringify(error)}`);
}
```
## wallpaper.off('colorChange')<sup>9+</sup>
......@@ -479,11 +498,25 @@ Unsubscribes from the wallpaper color change event.
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
// Unsubscribe from the listener.
wallpaper.off('colorChange', listener);
// Unsubscribe from all subscriptions of the colorChange type.
wallpaper.off('colorChange');
try {
wallpaper.on('colorChange', listener);
} catch (error) {
console.error(`failed to on because: ${JSON.stringify(error)}`);
}
try {
// Unsubscribe from the listener.
wallpaper.off('colorChange', listener);
} catch (error) {
console.error(`failed to off because: ${JSON.stringify(error)}`);
}
try {
// Unsubscribe from all subscriptions of the colorChange type.
wallpaper.off('colorChange');
} catch (error) {
console.error(`failed to off because: ${JSON.stringify(error)}`);
}
```
## wallpaper.getColors<sup>(deprecated)</sup>
......@@ -568,7 +601,7 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).|
**Example**
......@@ -604,7 +637,7 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| Promise&lt;number&gt; | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).|
**Example**
......@@ -867,7 +900,7 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the wallpaper is reset, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
......@@ -935,14 +968,14 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
```js
//The source type is string.
// The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
......@@ -992,7 +1025,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
......@@ -1004,7 +1037,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
**Example**
```js
//The source type is string.
// The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setWallpaper.`);
......@@ -1123,7 +1156,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
| callback | AsyncCallback&lt;image.PixelMap&gt; | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.|
**Example**
......@@ -1163,7 +1196,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p
| Type| Description|
| -------- | -------- |
| Promise&lt;image.PixelMap&gt; | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
| Promise&lt;image.PixelMap&gt; | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.|
**Example**
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册