提交 35ee0f06 编写于 作者: G ge-yafang

update docs

Signed-off-by: Nge-yafang <geyafang@huawei.com>
上级 9a68d11f
# Basics
- Getting Started
- [Preparations](start-overview.md)
- [Getting Started with eTS](start-with-ets.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md)
- Development Fundamentals
- [Directory Structure](package-structure.md)
- [Resource File](basic-resource-file-categories.md)
......
因为 它太大了无法显示 image diff 。你可以改为 查看blob
因为 它太大了无法显示 image diff 。你可以改为 查看blob
因为 它太大了无法显示 image diff 。你可以改为 查看blob
因为 它太大了无法显示 image diff 。你可以改为 查看blob
# Preparations
This document is intended for novices at developing OpenHarmony applications. It will introduce you to the OpenHarmony project directory structure and application development process, by walking you through a stripped-down, real-world example – building two pages and implementing redirection between pages. The following figure shows how the pages look on the DevEco Studio Previewer.
![en-us_image_0000001261809595](figures/en-us_image_0000001261809595.png)
Before you begin, there are some basic concepts that will help you better understand OpenHarmony: UI framework and ability.
## Basic Concepts
### UI Framework
OpenHarmony provides a UI development framework, known as ArkUI. ArkUI provides capabilities you may need for application UI development, including a wide array of components, layout calculation, animation, UI interaction, and drawing capabilities.
ArkUI comes with two development paradigms: JavaScript-based web-like development paradigm (web-like development paradigm for short) and TypeScript-based declarative development paradigm (declarative development paradigm for short). You can choose whichever development paradigm that aligns with your practice.
| **Development&nbsp;Paradigm** | **Language** | **UI&nbsp;Update&nbsp;Mode** | **Applicable&nbsp;To** | **Intended&nbsp;Audience** |
| -------- | -------- | -------- | -------- | -------- |
| Web-like&nbsp;development&nbsp;paradigm | JavaScript | Data-driven | Applications&nbsp;and&nbsp;service&nbsp;widgets&nbsp;with&nbsp;simple&nbsp;UIs | Frontend&nbsp;web&nbsp;developers |
| Declarative&nbsp;development&nbsp;paradigm | Extended&nbsp;TypeScript&nbsp;(eTS) | Data-driven | Applications&nbsp;involving&nbsp;technological&nbsp;sophistication&nbsp;and&nbsp;teamwork | Mobile&nbsp;application&nbsp;and&nbsp;system&nbsp;application&nbsp;developers |
For DevEco Studio V2.2 Beta1 and later versions, both the traditional coding mode and the low-code mode are supported when the JS language is used for development. On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features complying with [JS Development Specifications](../reference/apis).
### Ability
An ability is an abstraction of a capability that an application can provide. The **Ability** class is an essential component to OpenHarmony applications. An application may provide various capabilities, and so it can have multiple abilities. These abilities can be deployed together or independently from each other.
Abilities are classified into two types: [Feature Ability (FA)](../../glossary.md#f) and [Particle Ability (PA)](../../glossary.md#p). Each type has their respective templates for different capabilities. FAs support only the Page template (also called the [Page ability](../ability/fa-pageability.md)), which is used to provide the capability of interacting with users. A Page ability consists of one or more pages. The figure below shows the relationship between a Page ability and pages.
![en-us_image_0000001215206886](figures/en-us_image_0000001215206886.png)
This document provides a Page ability instance with two pages. For more information about ability development, see [Ability Development](../ability/ability-brief.md).
## Tool Preparation
1. Install the latest version of [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta).
2. Install DevEco Studio and configure the development environment. For details, see [Configuring the OpenHarmony SDK](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-setting-up-environment-0000001263160443).
When you are done, follow the instructions in [Getting Started with eTS](start-with-ets.md),[Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md), and [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md).
# Getting Started with eTS
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> To use eTS, your DevEco Studio must be V3.0.0.601 Beta1 or later.
>
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
## Creating an eTS Project
1. Open DevEco Studio, choose **File** &gt; **New** &gt; **Create Project**, select **Empty Ability**, and click **Next**.
![en-us_image_0000001223556342](figures/en-us_image_0000001223556342.png)
2. On the project configuration page, set **UI Syntax** to **eTS** and retain the default values for other parameters.
![en-us_image_0000001223716826](figures/en-us_image_0000001223716826.png)
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## eTS Project Files
- **entry** : OpenHarmony project module, which can be built into an ability package (HAP).
- **src &gt; main &gt; ets** : a collection of eTS source code.
- **src &gt; main &gt; ets &gt; MainAbility** : entry to your application/service.
- **src &gt; main &gt; ets &gt; MainAbility &gt; pages** : pages contained in **MainAbility**.
- **src &gt; main &gt; ets &gt; MainAbility &gt; app.ets** : ability lifecycle file.
- **src &gt; main &gt; resources** : a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files.
- **src &gt; main &gt; config.json** : module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file.
- **build-profile.json5** : module information and build configuration options, including **buildOption target**.
- **hvigorfile.js** : module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5** : application-level configuration information, including the signature and product configuration.
- **hvigorfile.js** : application-level compilation and build task script.
## Building the First Page
1. Use the **Text** component.
After the project synchronization is complete, choose **entry** &gt; **src** &gt; **main** &gt; **ets** &gt; **MainAbility** &gt; **pages** in the **Project** window and open the **index.ets** file. You can see that the file contains a **&lt;Text&gt;** component. The sample code in the **index.ets** file is shown below:
```
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
2. Add a **&lt;Button&gt;** component.
On the default page, add a **&lt;Button&gt;** component to accept user clicks and implement redirection to another page. The sample code in the **index.ets** file is shown below:
```
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Add a button to accept user clicks.
Button() {
Text('Next')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
}
.width('100%')
}
.height('100%')
}
}
```
3. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. Below is how the first page looks on the Previewer.
![en-us_image_0000001216239356](figures/en-us_image_0000001216239356.png)
## Building the Second Page
1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **ets** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Page**, name the page **second**, and click **Finish**. Below is the structure of the **pages** folder:
![en-us_image_0000001223397122](figures/en-us_image_0000001223397122.png)
2. Add **&lt;Text&gt;** and **&lt;Button&gt;** components.
Add **&lt;Text&gt;** and **&lt;Button&gt;** components and set their styles, as you do for the first page. The sample code in the **second.ets** file is shown below:
```
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Back')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
}
.width('100%')
}
.height('100%')
}
}
```
## Implementing Page Redirection
You can implement page redirection through the page router, which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the **index.ets** file of the first page, bind the **onClick** event to the **Next** button so that clicking the button redirects the user to the second page. The sample code in the **index.ets** file is shown below:
```
import router from '@system.router';
@Entry
@Component
struct Index {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
// Add a button to accept user clicks.
Button() {
Text('Next')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
// Bind the onClick event to the Next button so that clicking the button redirects the user to the second page.
.onClick(() => {
router.push({ uri: 'pages/second' })
})
}
.width('100%')
}
.height('100%')
}
}
```
2. Implement redirection from the second page to the first page.
In the **second.ets** file of the second page, bind the **onClick** event to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.ets** file is shown below:
```
import router from '@system.router';
@Entry
@Component
struct Second {
@State message: string = 'Hi there'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
Button() {
Text('Back')
.fontSize(25)
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.width('40%')
.height('5%')
// Bind the onClick event to the Back button so that clicking the button redirects the user back to the first page.
.onClick(() => {
router.back()
})
}
.width('100%')
}
.height('100%')
}
}
```
3. Open the **index.ets** file and click ![en-us_image_0000001262219043](figures/en-us_image_0000001262219043.png) in the Previewer to refresh the file. The figure below shows the effect.
![en-us_image_0000001260684127](figures/en-us_image_0000001260684127.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below.
![en-us_image_0000001268077317](figures/en-us_image_0000001268077317.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001262206247](figures/en-us_image_0000001262206247.png). The display effect is shown in the figure below.
![en-us_image_0000001217526428](figures/en-us_image_0000001217526428.png)
Congratulations! You have finished developing your OpenHarmony application in eTS. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md)
# Getting Started with JavaScript in the Low-Code Approach
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> This feature will be available in DevEco Studio V2.2 Beta1 and later versions.
>
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
On the OpenHarmony low-code development pages, you can design your app UI in an efficient, intuitive manner, with a wide array of UI editing features complying with [JS Development Specifications](../reference/apis).
You can develop applications or services in the low-code approach using either of the following methods:
- Create a project that supports low-code development. This method is used as an example in this topic.
- In an existing project, create a Visual file for development.
## Creating a Project That Supports Low-Code Development
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> This feature is available in DevEco Studio 3.0 Beta2 and later versions and works with compileSdkVersion 7 or later.
1. Open DevEco Studio, choose **File** &gt; **New** &gt; **Create Project**, select **Empty Ability**, and click **Next**.
![en-us_image_0000001268198893](figures/en-us_image_0000001268198893.png)
2. Go to the project configuration page, select **Enable Super Visual**, set **UI Syntax** to **JS**, and retain the default values for other parameters.
![en-us_image_0000001223717294](figures/en-us_image_0000001223717294.png)
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## Low-code Project Files
After the project synchronization is complete, a low-code directory structure is automatically generated in the project, as shown below.
![en-us_image_0000001223558810](figures/en-us_image_0000001223558810.png)
- **entry &gt; src &gt; main &gt; js &gt; MainAbility &gt; pages &gt; index &gt; index.js** : defines logical relationships, such as data and events, used on low-code pages. For details, see [JavaScript](../ui/js-framework-syntax-js.md). If multiple low-code development pages are created, a page folder and the corresponding **.js** file will be created for each of these pages.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> To avoid build errors when using the low-code development page, make sure the directory where the corresponding **.js** file is located does not contain **.hml** or **.css** files. For example, in the preceding example, no **.hml** or **.css** file is allowed in **js** &gt; **MainAbility** &gt; **pages** &gt; **index**.
- **entry &gt; src &gt; main &gt; supervisual &gt; MainAbility &gt; pages &gt; index &gt; index.visual** : stores the data model of the low-code development page. You can double-click the file to open the low-code development page. If multiple low-code development pages are created, a page folder and the corresponding **.visual** file will be created for each of these pages.
## Building the First Page
After the project synchronization is complete, the default first page contains the **Div** and **Text** (**Hello World**) components. To better understand low-code development, we'll delete these template components from the canvas and set the page from scratch.
Add **Div**, **Text**, and **Button** components to the first page.
1. Delete the existing template components from the canvas.<a name= delete_origin_content></a>
Open the index.visual file, right-click the existing template components on the canvas, and choose **Delete** from the shortcut menu to delete them. Below is an illustration of the operations.
![en-us_image_0000001216600980](figures/en-us_image_0000001216600980.gif)
2. Add a **Div** component and set its styles and attributes.<a name = add_container></a>
Drag the **Div** component from the **UI Control** area to the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001260226691](figures/en-us_image_0000001260226691.png)**General** and set **Height** to **100%** so that the component fills the entire screen. Click ![en-us_image_0000001215226858](figures/en-us_image_0000001215226858.png)**Flex**, set **FlexDirection** to **column** so that the main axis of the component is vertical, and set both **JustifyContent** and **AlignItems** to **center** so that the child components of the **Div** component are centered along the main axis and cross axis. Below is an illustration of the operations.
![en-us_image_0000001216448880](figures/en-us_image_0000001216448880.gif)
3. Add a **Text** component.
Drag the **Text** component from the **UI Control** area to the center area of the **Div** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215066868](figures/en-us_image_0000001215066868.png)**Properties** and set **Content** of the **Text** component to **Hello World**. Click ![en-us_image_0000001215386842](figures/en-us_image_0000001215386842.png)**Feature**, and set **FontSize** to **60px** and **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001216446670](figures/en-us_image_0000001216446670.gif)
4. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to a position under the **Text** component on the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001260106745](figures/en-us_image_0000001260106745.png)**Properties** and set **Value** of the **Button** component to **Next**. Click ![en-us_image_0000001259866741](figures/en-us_image_0000001259866741.png)**Feature** and set **FontSize** to **40px**. Then, select the **Button** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001260928361](figures/en-us_image_0000001260928361.gif)
5. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. Below is how the first page looks on the Previewer.
![en-us_image_0000001216288558](figures/en-us_image_0000001216288558.png)
## Building the Second Page
1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Visual**, name the page **second**, and click **Finish**. Below is the structure of the **pages** folder:
![en-us_image_0000001223882030](figures/en-us_image_0000001223882030.png)
2. [Delete the existing template components from the canvas.](#delete_origin_content)
3. [Add a Div component and set its styles and attributes.](#add_container)
4. Add a **Text** component.
Drag the **Text** component from the **UI Control** area to the center area of the **Div** component. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001260227453](figures/en-us_image_0000001260227453.png)**Properties** and set **Content** of the **Text** component to **Hi there**. Click ![en-us_image_0000001260107497](figures/en-us_image_0000001260107497.png)**Feature**, and set **FontSize** to **60px** and **TextAlign** to **center**. Then, select the **Text** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001216614132](figures/en-us_image_0000001216614132.gif)
5. Add a **Button** component.
Drag the **Button** component from the **UI Control** area to a position under the **Text** component on the canvas. In the **Attributes &amp; Styles** area on the right, click ![en-us_image_0000001215227618](figures/en-us_image_0000001215227618.png)**Properties** and set **Value** of the **Button** component to **Back**. Click ![en-us_image_0000001259987441](figures/en-us_image_0000001259987441.png)**Feature** and set **FontSize** to **40px**. Then, select the **Button** component on the canvas and drag its corners to fully display the text. Below is an illustration of the operations.
![en-us_image_0000001261017331](figures/en-us_image_0000001261017331.gif)
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the files of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. This operation needs to be completed in both .js and .visual files.
- In the **index.js** file:
```
import router from '@system.router';
export default {
onclick() {
router.push({
uri:'pages/second/second', // Specify the page to be redirected to.
})
}
}
```
- In the index.visual file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215388136](figures/en-us_image_0000001215388136.png)**Events** and set **Click** to **onclick**.
![en-us_image_0000001223722586](figures/en-us_image_0000001223722586.png)
2. Implement redirection from the second page to the first page.
In the files of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page.
This operation needs to be completed in both .js and .visual files.
- In the **second.js** file:
```
import router from '@system.router';
export default {
back() {
router.back()
}
}
```
- In the second.visual file, select the **Button** component on the canvas. In the **Attributes &amp; Styles** area, click ![en-us_image_0000001215388262](figures/en-us_image_0000001215388262.png)**Events** and set **Click** to **back**.
![en-us_image_0000001268082945](figures/en-us_image_0000001268082945.png)
3. Open the **index.visual** or **index.js** file and click ![en-us_image_0000001261979271](figures/en-us_image_0000001261979271.png) in the Previewer to refresh the file. The figure below shows the effect.
![en-us_image_0000001261142799](figures/en-us_image_0000001261142799.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below.
![en-us_image_0000001268283201](figures/en-us_image_0000001268283201.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001262207811](figures/en-us_image_0000001262207811.png). The display effect is shown in the figure below.
![en-us_image_0000001262127855](figures/en-us_image_0000001262127855.png)
Congratulations! You have finished developing your OpenHarmony app in JavaScript in the low-code approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md)
# Getting Started with JavaScript in the Traditional Coding Approach
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> For best possible results, use [DevEco Studio V3.0.0.900 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta) for your development.
## Creating a JavaScript Project
1. Open DevEco Studio, choose **File** &gt; **New** &gt; **Create Project**, select **Empty Ability**, and click **Next**.
![en-us_image_0000001223558814](figures/en-us_image_0000001223558814.png)
2. On the project configuration page, set **UI Syntax** to **JS** and retain the default values for other parameters.
![en-us_image_0000001223877162](figures/en-us_image_0000001223877162.png)
3. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created.
## JavaScript Project Files
- **entry** : OpenHarmony project module, which can be built into an ability package (HAP).
- **src &gt; main &gt; js** : a collection of JS source code.
- **src &gt; main &gt; js &gt; MainAbility** : entry to your application/service.
- **src &gt; main &gt; js &gt; MainAbility &gt; i18n** : resources in different languages, for example, UI strings and image paths.
- **src &gt; main &gt; js &gt; MainAbility &gt; pages** : pages contained in **MainAbility**.
- **src &gt; main &gt; js &gt; MainAbility &gt; app.js** : ability lifecycle file.
- **src &gt; main &gt; resources** : a collection of resource files used by your application/service, such as graphics, multimedia, character strings, and layout files.
- **src &gt; main &gt; config.json** : module configuration file. This file describes the global configuration information of the application/service, the device-specific configuration information, and the configuration information of the HAP file.
- **build-profile.json5** : module information and build configuration options, including **buildOption target**.
- **hvigorfile.js** : module-level compilation and build task script. You can customize related tasks and code implementation.
- **build-profile.json5** : application-level configuration information, including the signature and product configuration.
- **hvigorfile.js** : application-level compilation and build task script.
## Building the First Page
1. Use the **Text** component.
After the project synchronization is complete, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility** &gt; **pages** &gt; **index** in the **Project** window and open the **index.hml** file. You can see that the file contains a **&lt;Text&gt;** component. The sample code in the **index.hml** file is shown below:
```
<div class="container">
<text class="title">
Hello World
</text>
</div>
```
2. Add a button and bind the **onclick** method to this button.
On the default page, add an **&lt;input&gt;** component of the button type to accept user clicks and implement redirection to another page. The sample code in the **index.hml** file is shown below:
```
<div class="container">
<text class="title">
Hello World
</text>
<!-- Add a button, set its value to Next, and bind the onclick method to the button. -->
<input class="btn" type="button" value="Next" onclick="onclick"></input>
</div>
```
3. Set the page style in the **index.css** file.
From the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility** &gt; **pages** &gt; **index**, open the **index.css** file, and set the page styles, such as the width, height, font size, and spacing. The sample code in the **index.css** file is shown below:
```
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
}
.title {
font-size: 100px;
font-weight: bold;
text-align: center;
width: 100%;
margin: 10px;
}
.btn {
font-size: 60px;
font-weight: bold;
text-align: center;
width: 40%;
height: 5%;
margin-top: 20px;
}
```
4. On the toolbar in the upper right corner of the editing window, click **Previewer** to open the Previewer. Below is how the first page looks on the Previewer.
![en-us_image_0000001216084724](figures/en-us_image_0000001216084724.png)
## Building the Second Page
1. Create the second page.
In the **Project** window, choose **entry** &gt; **src** &gt; **main** &gt; **js** &gt; **MainAbility**, right-click the **pages** folder, choose **New** &gt; **Page**, name the page **second**, and click **Finish**. Below is the structure of the **second** folder:
![en-us_image_0000001223877210](figures/en-us_image_0000001223877210.png)
2. Add **&lt;Text&gt;** and **&lt;Button&gt;** components.
Add **&lt;Text&gt;** and **&lt;Button&gt;** components and set their styles, as you do for the first page. The sample code in the **second.hml** file is shown below:
```
<div class="container">
<text class="title">
Hi there
</text>
<!-- Add a button, set the value to Back, and bind the back method to the button.-->
<input class="btn" type="button" value="Back" onclick="back"></input>
</div>
```
3. Set the page style in the **second.css** file. The sample code in the **second.css** file is shown below:
```
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
}
.title {
font-size: 100px;
font-weight: bold;
text-align: center;
width: 100%;
margin: 10px;
}
.btn {
font-size: 60px;
font-weight: bold;
text-align: center;
width: 40%;
height: 5%;
margin-top: 20px;
}
```
## Implementing Page Redirection
You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URI. Import the **router** module and then perform the steps below:
1. Implement redirection from the first page to the second page.
In the **index.js** file of the first page, bind the **onclick** method to the button so that clicking the button redirects the user to the second page. The sample code in the **index.js** file is shown below:
```
import router from '@system.router';
export default {
onclick: function () {
router.push({
uri: "pages/second/second"
})
}
}
```
2. Implement redirection from the second page to the first page.
In the **second.ets** file of the second page, bind the **back** method to the **Back** button so that clicking the button redirects the user back to the first page. The sample code in the **second.js** file is shown below:
```
import router from '@system.router';
export default {
back: function () {
router.back()
}
}
```
3. Open any file in the **index** folder and click ![en-us_image_0000001262339067](figures/en-us_image_0000001262339067.png) in the Previewer to refresh the file. The figure below shows the effect.
![en-us_image_0000001216269940](figures/en-us_image_0000001216269940.png)
## Running the Application on a Real Device
1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** &gt; **Project Structure** &gt; **Project** &gt; **Signing Configs**, select **Automatically generate signing**, wait until the automatic signing is complete, and click **OK**, as shown below.
![en-us_image_0000001223557290](figures/en-us_image_0000001223557290.png)
3. On the toolbar in the upper right corner of the editing window, click ![en-us_image_0000001217047316](figures/en-us_image_0000001217047316.png). The display effect is shown in the figure below.
![en-us_image_0000001217527892](figures/en-us_image_0000001217527892.png)
Congratulations! You have finished developing your OpenHarmony application in JavaScript in the traditional coding approach. To learn more about OpenHarmony, see [OpenHarmony Overview](../application-dev-guide.md)
......@@ -24,7 +24,6 @@
- [User Authentication](js-apis-useriam-userauth.md)
- [Access Control](js-apis-abilityAccessCtrl.md)
- Data Management
- [Lightweight Storage<sup>9+</sup>](js-apis-data-preferences.md)
- [Lightweight Storage](js-apis-data-storage.md)
- [Distributed Data Management](js-apis-distributed-data.md)
- [Relational Database](js-apis-data-rdb.md)
......@@ -80,6 +79,7 @@
- [Console Logs](js-apis-basic-features-logs.md)
- [Page Routing](js-apis-basic-features-routes.md)
- [Timer](js-apis-basic-features-timer.md)
- [Screen Lock Management](js-apis-screen-lock.md)
- [Setting the System Time](js-apis-system-time.md)
- [Wallpaper](js-apis-wallpaper.md)
- [Pasteboard](js-apis-pasteboard.md)
......
# Lightweight Storage
Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> 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.
## Modules to Import
```
import data_Preferences from '@ohos.data.preferences'
```
## Attributes
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It is 80 bytes.|
| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value of the string type. It is 8192 bytes.|
## data_Preferences.getPreferences
getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void
Reads a file and loads the data to the **Preferences** instance. This method uses an asynchronous callback to return the execution result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes| Callback used to return the execution result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
var path = this.context.getDataBaseDir()
data_Preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
console.info("Get the preferences failed, path: " + path + '/mystore')
return;
}
preferences.putSync('startup', 'auto')
preferences.flushSync()
})
```
## data_Preferences.getPreferences
getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
Reads a file and loads the data to the **Preferences** instance. This method uses a promise to return the execution result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise used to return the result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
var path = this.context.getDataBaseDir()
let promisePre = data_Preferences.getPreferences(this.context, 'mystore')
promisePre.then((preferences) => {
preferences.putSync('startup', 'auto')
preferences.flushSync()
}).catch((err) => {
console.info("Get the preferences failed, path: " + path + '/mystore')
})
```
## data_Preferences.deletePreferences
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Removes the singleton **Preferences** instance of the specified file from the memory, and deletes the specified file, its backup file, and corrupted files. After the specified files are deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This method uses an asynchronous callback to return the execution result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
data_Preferences.deletePreferences(this.context, 'mystore', function (err) {
if (err) {
console.info("Deleted failed with err: " + err)
return
}
console.info("Deleted successfully.")
})
```
## data_Preferences.deletePreferences
deletePreferences(context: Context, name: string): Promise&lt;void&gt;
Removes the singleton **Preferences** instance of the specified file from the memory, and deletes the specified file, its backup file, and corrupted files. After the specified files are deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This method uses a promise to return the execution result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
let promisedelPre = data_Preferences.deletePreferences(this.context, 'mystore')
promisedelPre.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)
})
```
## data_Preferences.removePreferencesFromCache
removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
Removes the singleton **Preferences** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
data_Preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
if (err) {
console.info("Removed preferences from cache failed with err: " + err)
return
}
console.info("Removed preferences from cache successfully.")
})
```
## data_Preferences.removePreferencesFromCache
removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
Removes the singleton **Preferences** instance of a file from the cache. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the app or functionality.|
| name | string | Yes| Name of the app's internal data storage.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
let promiserevPre = data_Preferences.removePreferencesFromCache(this.context, 'mystore')
promiserevPre.then(() => {
console.info("Removed preferences from cache successfully.")
}).catch((err) => {
console.info("Removed preferences from cache failed with err: " + err)
})
```
## Preferences
Provides APIs for obtaining and modifying storage data.
### get
get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void
Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| defValue | ValueType | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;ValueType&gt; | Yes| Callback used to return the execution result.|
- Example
```
preferences.get('startup', 'default', function(err, value) {
if (err) {
console.info("Get the value of startup failed with err: " + err)
return
}
console.info("The value of startup is " + value)
})
```
### get
get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| defValue | ValueType | Yes| Default value to be returned. It can be a number, string, or Boolean value.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise used to return the result.|
- Example
```
let promiseget = preferences.get('startup', 'default')
promiseget.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
})
```
### put
put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
Obtains the **Preferences** instance corresponding to the specified file, writes data to the **Preferences** instance using a **Preferences** API, and saves data to the file using **flush()** or **flushSync()**.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to modify. It cannot be empty.|
| value | ValueType | Yes| New value to store. It can be a number, string, or Boolean value.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Put the value of startup failed with err: " + err)
return
}
console.info("Put the value of startup successfully.")
})
```
### put
put(key: string, value: ValueType): Promise&lt;void&gt;
Obtains the **Preferences** instance corresponding to the specified file, writes data to the **Preferences** instance using a **Preferences** API, and saves data to the file using **flush()** or **flushSync()**.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data to modify. It cannot be empty.|
| value | ValueType | Yes| New value to store. It can be a number, string, or Boolean value.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
let promiseput = preferences.put('startup', 'auto')
promiseput.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
})
```
### has
has(key: string, callback: AsyncCallback&lt;boolean&gt;): boolean
Checks whether the **Preference** object contains data with a given key.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the execution result.|
- Return value
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the **Preference** object contains data with the specified key; returns **false** otherwise.|
- Example
```
preferences.has('startup', function (err, isExist) {
if (err) {
console.info("Check the key of startup failed with err: " + err)
return
}
if (isExist) {
console.info("The key of startup is contained.")
}
})
```
### has
has(key: string): Promise&lt;boolean&gt;
Checks whether the **Preference** object contains data with a given key.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
- Example
```
let promisehas = preferences.has('startup')
promisehas.then((isExist) => {
if (isExist) {
console.info("The key of startup is contained.")
}
}).catch((err) => {
console.info("Check the key of startup failed with err: " + err)
})
```
### delete
delete(key: string, callback: AsyncCallback&lt;void&gt;): void
Deletes data with the specified key from this **Preference** object.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data. It cannot be empty.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
preferences.delete('startup', function (err) {
if (err) {
console.info("Delete startup key failed with err: " + err)
return
}
console.info("Deleted startup key successfully.")
})
```
### delete
delete(key: string): Promise&lt;void&gt;
Deletes data with the specified key from this **Preference** object.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| key | string | Yes| Key of the data.|
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
let promisedel = preferences.delete('startup')
promisedel.then(() => {
console.info("Deleted startup key successfully.")
}).catch((err) => {
console.info("Delete startup key failed with err: " + err)
})
```
### flush
flush(callback: AsyncCallback&lt;void&gt;): void
Saves the modification of this object to the **Preferences** instance and synchronizes the modification to the file.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
preferences.flush(function (err) {
if (err) {
console.info("Flush to file failed with err: " + err)
return
}
console.info("Flushed to file successfully.")
})
```
### flush
flush(): Promise&lt;void&gt;
Saves the modification of this object to the **Preferences** instance and synchronizes the modification to the file.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
let promiseflush = preferences.flush()
promiseflush.then(() => {
console.info("Flushed to file successfully.")
}).catch((err) => {
console.info("Flush to file failed with err: " + err)
})
```
### clear
clear(callback: AsyncCallback&lt;void&gt;): void
Clears this **Preferences** object.
This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
- Example
```
preferences.clear(function (err) {
if (err) {
console.info("Clear to file failed with err: " + err)
return
}
console.info("Cleared to file successfully.")
})
```
### clear
clear(): Promise&lt;void&gt;
Clears this **Preferences** object.
This method uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
- Example
```
let promiseclear = preferences.clear()
promiseclear.then(() => {
console.info("Cleared to file successfully.")
}).catch((err) => {
console.info("Clear to file failed with err: " + err)
})
```
### on('change')
on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
Subscribes to data changes. When the value of the subscribed key changes, a callback will be invoked after the **flush()** method is executed.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Callback used to return data changes.|
- Example
```
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
preferences.on('change', observer)
preferences.put('startup', 'auto')
preferences.flush() // observer will be called.
```
### off('change')
off(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
Unsubscribes from data changes.
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
- Parameters
| Name| Type| Description|
| -------- | -------- | -------- |
| type | string | Event type. The value **change** indicates data change events.|
| callback | Callback&lt;{ key : string }&gt; | Callback used to return data changes.|
- Example
```
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
preferences.off('change', observer)
```
......@@ -4,7 +4,7 @@ Lightweight storage provides applications with data processing capability and al
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. <br/>The APIs of this module are no longer maintained since API Version 9. You are advised to use [@ohos.data.preferences](js-apis-data-preferences.md).
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
......@@ -45,7 +45,7 @@ Reads a file and loads the data to the **Storage** instance in synchronous mode.
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
var path = await context.getFilesDir()
let storage = dataStorage.getStorageSync(path + '/mystore')
......@@ -72,7 +72,7 @@ Reads a file and loads the data to the **Storage** instance. This method uses an
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
var path = await context.getFilesDir()
dataStorage.getStorage(path + '/mystore', function (err, storage) {
......@@ -108,7 +108,7 @@ Reads a file and loads the data to the **Storage** instance. This method uses a
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
var path = await context.getFilesDir()
let promisegetSt = dataStorage.getStorage(path + '/mystore')
......
# Screen Lock Management
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import screenlock from '@ohos.screenLock';
```
## screenlock.isScreenLocked
isScreenLocked(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the screen is locked. This method 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&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result.&nbsp;If&nbsp;**true**&nbsp;is&nbsp;returned,&nbsp;the&nbsp;screen&nbsp;is&nbsp;locked.&nbsp;If&nbsp;**false**&nbsp;is&nbsp;returned,&nbsp;the&nbsp;screen&nbsp;is&nbsp;not&nbsp;locked. |
- Example
```
screenlock.isScreenLocked((err, data)=>{
if (err) {
console.error('isScreenLocked callback error -> ${JSON.stringify(err)}');
return;
}
console.info('isScreenLocked callback success data -> ${JSON.stringify(data)}');
});
```
## screenlock.isScreenLocked
isScreenLocked(): Promise&lt;boolean&gt;
Checks whether the screen is locked. This method uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
- Return Values
| Type | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
- Example
```
screenlock.isScreenLocked().then((data) => {
console.log('isScreenLocked success: data -> ${JSON.stringify(data)}');
}).catch((err) => {
console.error('isScreenLocked fail, promise: err -> ${JSON.stringify(err)}');
});
```
## screenlock.isSecureMode
isSecureMode(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether a device is in secure mode. This method 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&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result.&nbsp;If&nbsp;**true**&nbsp;is&nbsp;returned,&nbsp;the&nbsp;device&nbsp;is&nbsp;in&nbsp;secure&nbsp;mode.&nbsp;If&nbsp;**false**&nbsp;is&nbsp;returned,&nbsp;the&nbsp;device&nbsp;is&nbsp;not&nbsp;in&nbsp;secure&nbsp;mode. |
- Example
```
screenlock.isSecureMode((err, data)=>{
if (err) {
console.error('isSecureMode callback error -> ${JSON.stringify(err)}');
return;
}
console.info('isSecureMode callback success data -> ${JSON.stringify(err)}');
});
```
## screenlock.isSecureMode
isSecureMode(): Promise&lt;boolean&gt;
Checks whether a device is in secure mode. This method uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
- Return Values
| Type | Description |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
- Example
```
screenlock.isSecureMode().then((data) => {
console.log('isSecureMode success: data->${JSON.stringify(data)}');
}).catch((err) => {
console.error('isSecureMode fail, promise: err->${JSON.stringify(err)}');
});
```
## screenlock.unlockScreen
unlockScreen(callback: AsyncCallback&lt;void&gt;): void
Unlocks the screen. This method uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
- Parameters
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback&nbsp;function.&nbsp;If&nbsp;the&nbsp;callback&nbsp;fails,&nbsp;an&nbsp;error&nbsp;message&nbsp;is&nbsp;returned. |
- Example
```
screenlock.unlockScreen((err)=>{
if (err) {
console.error('unlockScreen callback error -> ${JSON.stringify(err)}');
return;
}
console.info('unlockScreen callback success');
});
```
## screenlock.unlockScreen
unlockScreen(): Promise&lt;void&gt;
Unlocks the screen. This method uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.ScreenLock
- Return Values
| Type | Description |
| -------- | -------- |
| Promise&lt;void&gt; | Promise&nbsp;used&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
- Example
```
screenlock.unlockScreen().then(() => {
console.log('unlockScreen success');
}).catch((err) => {
console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}');
});
```
......@@ -23,18 +23,18 @@ OpenHarmony提供了一套UI开发框架,即方舟开发框架(ArkUI框架
| 类Web开发范式 | JS语言 | 数据驱动更新 | 界面较为简单的程序应用和卡片 | Web前端开发人员 |
| 声明式开发范式 | 扩展的TS语言(eTS) | 数据驱动更新 | 复杂度较大、团队合作度较高的程序 | 移动系统应用开发人员、系统应用开发人员 |
对于DevEco Studio V2.2 Beta1及更高版本,在使用JS语言开发时,除传统代码方式外,还支持使用低代码方式。OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS开发规范](../references/apis),通过可视化界面开发方式快速构建布局,可有效降低用户的上手成本并提升用户构建UI界面的效率。
对于DevEco Studio V2.2 Beta1及更高版本,在使用JS语言开发时,除传统代码方式外,还支持使用低代码方式。OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS开发规范](../reference/apis),通过可视化界面开发方式快速构建布局,可有效降低用户的上手成本并提升用户构建UI界面的效率。
### Ability
[Ability](../ability/ability-brief.md)是应用所具备能力的抽象,也是应用程序的重要组成部分。一个应用可以具备多种能力(即可以包含多个Ability)。OpenHarmony支持应用以Ability为单位进行部署。
Ability是应用所具备能力的抽象,也是应用程序的重要组成部分。一个应用可以具备多种能力(即可以包含多个Ability)。OpenHarmony支持应用以Ability为单位进行部署。
Ability可以分为[FA(Feature Ability)](../../glossary.md#f)[PA(Particle Ability)](../../glossary.md#p)两种类型,每种类型为开发者提供了不同的模板,以便实现不同的业务功能。其中,FA支持[Page Ability](../ability/fa-pageability.md)模板,以提供与用户交互的能力。一个Page Ability可以含有一个或多个页面(即Page),Page Ability与Page的关系如下图所示:
![zh-cn_image_0000001215206886](figures/zh-cn_image_0000001215206886.png)
快速入门提供了一个含有两个页面的Page Ability实例。更多Ability的开发内容及指导,请参见[Ability开发](../ability/Readme-CN.md)
快速入门提供了一个含有两个页面的Page Ability实例。更多Ability的开发内容及指导,请参见[Ability开发](../ability/ability-brief.md)
## 工具准备
......
......@@ -20,24 +20,24 @@
## eTS工程项目文件
- **entry**:OpenHarmony工程模块,编译构建生成一个Hap包。
- **src &gt; main &gt; ets**:用于存放ets源码。
- **src &gt; main &gt; ets &gt; MainAbility**:应用/服务的入口。
- **src &gt; main &gt; ets &gt; MainAbility &gt; pages**:MainAbility包含的页面。
- **src &gt; main &gt; ets &gt; MainAbility &gt; app.ets**:承载Ability生命周期。
- **src &gt; main &gt; resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。
- **src &gt; main &gt; config.json**:模块配置文件。主要包含HAP包的配置信息、应用在具体设备上的配置信息以及应用的全局配置信息。
- **build-profile.json5**:模块的模块信息 、编译信息配置项,包括 buildOption target配置等。
- **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。
- **entry** :OpenHarmony工程模块,编译构建生成一个Hap包。
- **src &gt; main &gt; ets** :用于存放ets源码。
- **src &gt; main &gt; ets &gt; MainAbility** :应用/服务的入口。
- **src &gt; main &gt; ets &gt; MainAbility &gt; pages** :MainAbility包含的页面。
- **src &gt; main &gt; ets &gt; MainAbility &gt; app.ets** :承载Ability生命周期。
- **src &gt; main &gt; resources** :用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。
- **src &gt; main &gt; config.json** :模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。
- **build-profile.json5** :模块的模块信息 、编译信息配置项,包括 buildOption target配置等。
- **hvigorfile.js** :模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。
- **build-profile.json5**:应用级配置信息,包括签名、产品配置等。
- **build-profile.json5** :应用级配置信息,包括签名、产品配置等。
- **hvigorfile.js**:应用级编译构建任务脚本。
- **hvigorfile.js** :应用级编译构建任务脚本。
## 构建第一个页面
1. **文本组件。**
1. **使用文本组件。**
工程同步完成后,在“**Project**”窗口,点击“**entry &gt; src &gt; main &gt; ets &gt; MainAbility &gt; pages**”,打开“**index.ets**”文件,可以看到页面由Text组件组成。“**index.ets**”文件的示例如下:
......@@ -98,7 +98,8 @@
}
```
3. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示:
3. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。** 第一个页面效果如下图所示:
![zh-cn_image_0000001216239356](figures/zh-cn_image_0000001216239356.png)
......@@ -235,7 +236,8 @@
}
```
3. **打开index.ets文件,点击预览器中的**![zh-cn_image_0000001262219043](figures/zh-cn_image_0000001262219043.png)**按钮进行刷新。**效果如下图所示:
3. **打开index.ets文件,点击预览器中的** ![zh-cn_image_0000001262219043](figures/zh-cn_image_0000001262219043.png) **按钮进行刷新。** 效果如下图所示:
![zh-cn_image_0000001260684127](figures/zh-cn_image_0000001260684127.png)
......@@ -247,6 +249,7 @@
![zh-cn_image_0000001268077317](figures/zh-cn_image_0000001268077317.png)
3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001262206247](figures/zh-cn_image_0000001262206247.png)按钮运行。效果如下图所示:
![zh-cn_image_0000001217526428](figures/zh-cn_image_0000001217526428.png)
恭喜您已经使用eTS语言开发完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
......@@ -26,7 +26,7 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
1. 打开**DevEco Studio**,点击**File** &gt; **New &gt; Create Project**,选择模板“**Empty Ability**”,点击**Next**进行下一步配置。
![zh-cn_image_0000001268198893](figures/zh-cn_image_0000001268198893.png)
2. 进入配置工程界面,打开“**Enable Visual Enable**”开关**,UI Syntax**选择“**JS**”,其他参数保持默认设置即可。
2. 进入配置工程界面,打开“**Enable Super Visual**”开关,**UI Syntax**选择“**JS**”,其他参数保持默认设置即可。
![zh-cn_image_0000001223717294](figures/zh-cn_image_0000001223717294.png)
3. 点击**Finish**,工具会自动生成示例代码和相关资源,等待工程创建完成。
......@@ -38,11 +38,12 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
![zh-cn_image_0000001223558810](figures/zh-cn_image_0000001223558810.png)
- **entry &gt; src &gt; main &gt; js &gt; MainAbility &gt; pages &gt; index &gt; index.js**:低代码页面的逻辑描述文件,定义了页面里所用到的所有的逻辑关系,比如数据、事件等,详情请参考[JS语法参考](../ui/js-framework-syntax-js.md)。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的js文件。
- **entry &gt; src &gt; main &gt; js &gt; MainAbility &gt; pages &gt; index &gt; index.js** :低代码页面的逻辑描述文件,定义了页面里所用到的所有的逻辑关系,比如数据、事件等,详情请参考[JS语法参考](../ui/js-framework-syntax-js.md)。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的js文件。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 使用低代码页面开发时,其关联js文件的同级目录中不能包含hml和css页面,例如上图中的**js &gt; MainAbility &gt; pages &gt; index**目录下不能包含hml与css文件,否则会出现编译报错。
- **entry &gt; src &gt; main &gt; supervisual &gt; MainAbility &gt; pages &gt; index &gt; index.visual**:visual文件存储低代码页面的数据模型,双击该文件即可打开低代码页面,进行可视化开发设计。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的visual文件。
> 使用低代码页面开发时,其关联js文件的同级目录中不能包含hml和css页面,例如上图中的 **js &gt; MainAbility &gt; pages &gt; index** 目录下不能包含hml与css文件,否则会出现编译报错。
- **entry &gt; src &gt; main &gt; supervisual &gt; MainAbility &gt; pages &gt; index &gt; index.visual** :visual文件存储低代码页面的数据模型,双击该文件即可打开低代码页面,进行可视化开发设计。如果创建了多个低代码页面,则pages目录下会生成多个页面文件夹及对应的visual文件。
## 构建第一个页面
......@@ -71,7 +72,7 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
![zh-cn_image_0000001260928361](figures/zh-cn_image_0000001260928361.gif)
5. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示:
5. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。** 第一个页面效果如下图所示:
![zh-cn_image_0000001216288558](figures/zh-cn_image_0000001216288558.png)
......@@ -110,14 +111,15 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
export default {
onclick() {
router.push ({
router.push({
uri:'pages/second/second', // 指定要跳转的页面
})
}
}
```
-**index.viusal**”: 打开index.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388136](figures/zh-cn_image_0000001215388136.png)(Events),鼠标点击Click事件的输入框,选择onclick,如下所示:
-**index.visual**”: 打开index.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388136](figures/zh-cn_image_0000001215388136.png)(Events),鼠标点击Click事件的输入框,选择onclick,如下所示:
![zh-cn_image_0000001223722586](figures/zh-cn_image_0000001223722586.png)
2. **第二个页面返回到第一个页面。**
......@@ -132,15 +134,16 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
export default {
back() {
router.back ()
router.back()
}
}
```
-**second.viusal**”: 打开second.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388262](figures/zh-cn_image_0000001215388262.png)(Events),鼠标点击Click事件的输入框,选择back,如下所示:
-**second.visual**”: 打开second.visual,选中画布上的Button组件。点击右侧属性样式栏中的事件图标![zh-cn_image_0000001215388262](figures/zh-cn_image_0000001215388262.png)(Events),鼠标点击Click事件的输入框,选择back,如下所示:
![zh-cn_image_0000001268082945](figures/zh-cn_image_0000001268082945.png)
3. **打开index.visual或index.js文件,点击预览器中的**![zh-cn_image_0000001261979271](figures/zh-cn_image_0000001261979271.png)**按钮进行刷新。**效果如下图所示:
3. **打开index.visual或index.js文件,点击预览器中的** ![zh-cn_image_0000001261979271](figures/zh-cn_image_0000001261979271.png) **按钮进行刷新。** 效果如下图所示:
![zh-cn_image_0000001261142799](figures/zh-cn_image_0000001261142799.png)
......@@ -148,10 +151,11 @@ OpenHarmony低代码开发方式具有丰富的UI界面编辑功能,遵循[JS
1. 将搭载OpenHarmony标准系统的开发板与电脑连接。
2. 点击**File &gt;Project Structure** &gt; **Project &gt; Signing Configs**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示:
2. 点击**File &gt; Project Structure** &gt; **Project &gt; Signing Configs**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示:
![zh-cn_image_0000001268283201](figures/zh-cn_image_0000001268283201.png)
3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001262207811](figures/zh-cn_image_0000001262207811.png)按钮运行。效果如下图所示:
![zh-cn_image_0000001262127855](figures/zh-cn_image_0000001262127855.png)
恭喜您已经使用JS语言开发(低代码方式)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
......@@ -19,25 +19,25 @@
## JS工程项目文件
- **entry**:OpenHarmony工程模块,编译构建生成一个Hap包。
- **src &gt; main &gt; js**:用于存放js源码。
- **src &gt; main &gt; js &gt; MainAbility**:应用/服务的入口。
- **src &gt; main &gt; js &gt; MainAbility &gt; i18n**:用于配置不同语言场景资源内容,比如应用文本词条、图片路径等资源。
- **src &gt; main &gt; js &gt; MainAbility &gt; pages**:MainAbility包含的页面。
- **src &gt; main &gt; js &gt; MainAbility &gt; app.js**:承载Ability生命周期。
- **src &gt; main &gt; js** :用于存放js源码。
- **src &gt; main &gt; js &gt; MainAbility** :应用/服务的入口。
- **src &gt; main &gt; js &gt; MainAbility &gt; i18n** :用于配置不同语言场景资源内容,比如应用文本词条、图片路径等资源。
- **src &gt; main &gt; js &gt; MainAbility &gt; pages** :MainAbility包含的页面。
- **src &gt; main &gt; js &gt; MainAbility &gt; app.js** :承载Ability生命周期。
- **src &gt; main &gt; resources**:用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。
- **src &gt; main &gt; config.json**:模块配置文件。主要包含HAP包的配置信息、应用在具体设备上的配置信息以及应用的全局配置信息。
- **build-profile.json5**:模块的模块信息 、编译信息配置项,包括 buildOption target配置等。
- **hvigorfile.js**:模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。
- **src &gt; main &gt; resources** :用于存放应用/服务所用到的资源文件,如图形、多媒体、字符串、布局文件等。
- **src &gt; main &gt; config.json** :模块配置文件。主要包含HAP包的配置信息、应用/服务在具体设备上的配置信息以及应用/服务的全局配置信息。
- **build-profile.json5** :模块的模块信息 、编译信息配置项,包括 buildOption target配置等。
- **hvigorfile.js** :模块级编译构建任务脚本,开发者可以自定义相关任务和代码实现。
- **build-profile.json5**:应用级配置信息,包括签名、产品配置等。
- **build-profile.json5** :应用级配置信息,包括签名、产品配置等。
- **hvigorfile.js**:应用级编译构建任务脚本。
- **hvigorfile.js** :应用级编译构建任务脚本。
## 构建第一个页面
1. **文本组件。**
1. **使用文本组件。**
工程同步完成后,在“**Project**”窗口,点击“**entry &gt; src &gt;main &gt; js &gt; MainAbility &gt; pages&gt; index**”,打开“**index.hml**”文件,设置Text组件内容。“**index.hml**”文件的示例如下:
......@@ -65,7 +65,7 @@
```
3. **设置页面样式。**
在“**Project**”窗口,点击“**entry &gt; src &gt;main &gt; js &gt; MainAbility &gt; pages&gt; index**”,打开“**index.css**”文件,可以对页面中文本、按钮设置宽高、字体大小、间距等样式。“**index.css**”文件的示例如下:
在“**Project**”窗口,点击“**entry &gt; src &gt; main &gt; js &gt; MainAbility &gt; pages&gt; index**”,打开“**index.css**”文件,可以对页面中文本、按钮设置宽高、字体大小、间距等样式。“**index.css**”文件的示例如下:
```
......@@ -98,7 +98,8 @@
}
```
4. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。**第一个页面效果如下图所示:
4. **在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。** 第一个页面效果如下图所示:
![zh-cn_image_0000001216084724](figures/zh-cn_image_0000001216084724.png)
......@@ -167,7 +168,7 @@
```
import router from '@system.router'
import router from '@system.router';
export default {
onclick: function () {
......@@ -183,7 +184,7 @@
```
import router from '@system.router'
import router from '@system.router';
export default {
back: function () {
......@@ -192,7 +193,8 @@
}
```
3. **打开index文件夹下的任意一个文件,点击预览器中的**![zh-cn_image_0000001262339067](figures/zh-cn_image_0000001262339067.png)**按钮进行刷新。**效果如下图所示:
3. **打开index文件夹下的任意一个文件,点击预览器中的** ![zh-cn_image_0000001262339067](figures/zh-cn_image_0000001262339067.png) **按钮进行刷新。** 效果如下图所示:
![zh-cn_image_0000001216269940](figures/zh-cn_image_0000001216269940.png)
......@@ -200,10 +202,11 @@
1. 将搭载OpenHarmony标准系统的开发板与电脑连接。
2. 点击**File &gt;Project Structure** &gt; **Project &gt; Signing Configs**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示:
2. 点击**File &gt; Project Structure** &gt; **Project &gt; Signing Configs**界面勾选“**Automatically generate signing**”,等待自动签名完成即可,点击“**OK**”。如下图所示:
![zh-cn_image_0000001223557290](figures/zh-cn_image_0000001223557290.png)
3. 在编辑窗口右上角的工具栏,点击![zh-cn_image_0000001217047316](figures/zh-cn_image_0000001217047316.png)按钮运行。效果如下图所示:
![zh-cn_image_0000001217527892](figures/zh-cn_image_0000001217527892.png)
恭喜您已经使用JS语言开发(传统代码方式)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
......@@ -100,9 +100,9 @@
- [@ohos.data.dataAbility (DataAbility谓词)](js-apis-data-ability.md)
- [@ohos.data.distributedData (分布式数据管理)](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject (分布式数据对象)](js-apis-data-distributedobject.md)
- [@ohos.data.preferences (轻量级存储)](js-apis-data-preferences.md)
- [@ohos.data.rdb (关系型数据库)](js-apis-data-rdb.md)
- [@ohos.settings (设置数据项名称)](js-apis-settings.md)
- [@ohos.data.storage (轻量级存储)](js-apis-data-storage.md)
- data/rdb/[resultSet (结果集)](js-apis-data-resultset.md)
- 文件管理
......
# 轻量级存储
轻量级存储为应用提供key-value键值型的文件数据处理能力,支持应用对数据进行轻量级存储及查询。数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型。
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
import data_Preferences from '@ohos.data.preferences'
```
## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.DistributedDataManager.Preferences.Core
| 名称 | 参数类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| MAX_KEY_LENGTH | string | 是 | 否 | key的最大长度限制,大小为80字节。 |
| MAX_VALUE_LENGTH | string | 是 | 否 | string类型value的最大长度限制,大小为8192字节。 |
## data_Preferences.getPreferences
getPreferences(context: Context, name: string, callback: AsyncCallback&lt;Preferences&gt;): void
读取指定文件,将数据加载到Preferences实例,用于数据操作,使用callback形式返回结果。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | 是 | 回调函数。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
var path = this.context.getDataBaseDir()
data_Preferences.getPreferences(this.context, 'mystore', function (err, preferences) {
if (err) {
console.info("Get the preferences failed, path: " + path + '/mystore')
return;
}
preferences.putSync('startup', 'auto')
preferences.flushSync()
})
```
## data_Preferences.getPreferences
getPreferences(context: Context, name: string): Promise&lt;Preferences&gt;
读取指定文件,将数据加载到Preferences实例,用于数据操作,使用Promise方式作为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;[Preferences](#preferences)&gt; | Promise实例,用于异步获取结果。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
var path = this.context.getDataBaseDir()
let promisePre = data_Preferences.getPreferences(this.context, 'mystore')
promisePre.then((preferences) => {
preferences.putSync('startup', 'auto')
preferences.flushSync()
}).catch((err) => {
console.info("Get the preferences failed, path: " + path + '/mystore')
})
```
## data_Preferences.deletePreferences
deletePreferences(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
从内存中移除指定文件对应的Preferences单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,使用callback方式作为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
data_Preferences.deletePreferences(this.context, 'mystore', function (err) {
if (err) {
console.info("Deleted failed with err: " + err)
return
}
console.info("Deleted successfully.")
})
```
## data_Preferences.deletePreferences
deletePreferences(context: Context, name: string): Promise&lt;void&gt;
从内存中移除指定文件对应的Preferences单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题,使用promise方式作为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
let promisedelPre = data_Preferences.deletePreferences(this.context, 'mystore')
promisedelPre.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)
})
```
## data_Preferences.removePreferencesFromCache
removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
从内存中移除指定文件对应的Preferences单实例。移除Preferences单实例时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
data_Preferences.removePreferencesFromCache(this.context, 'mystore', function (err) {
if (err) {
console.info("Removed preferences from cache failed with err: " + err)
return
}
console.info("Removed preferences from cache successfully.")
})
```
## data_Preferences.removePreferencesFromCache
removePreferencesFromCache(context: Context, name: string): Promise&lt;void&gt;
从内存中移除指定文件对应的Preferences单实例。移除Preferences单实例时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| context | Context | 是 | 应用程序或功能的上下文 |
| name | string | 是 | 应用程序内部数据存储名称。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步获取结果。 |
- 示例:
```
import Ability from '@ohos.application.Ability'
import data_Preferences from '@ohos.data.preferences'
let promiserevPre = data_Preferences.removePreferencesFromCache(this.context, 'mystore')
promiserevPre.then(() => {
console.info("Removed preferences from cache successfully.")
}).catch((err) => {
console.info("Removed preferences from cache failed with err: " + err)
})
```
## Preferences
提供获取和修改存储数据的接口。
### get
get(key: string, defValue: ValueType, callback: AsyncCallback&lt;ValueType&gt;): void
获取键对应的值,如果值为null或者非默认值类型,返回默认数据。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。它不能为空。 |
| defValue | ValueType | 是 | 默认返回值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;ValueType&gt; | 是 | 回调函数。 |
- 示例:
```
preferences.get('startup', 'default', function(err, value) {
if (err) {
console.info("Get the value of startup failed with err: " + err)
return
}
console.info("The value of startup is " + value)
})
```
### get
get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;
获取键对应的值,如果值为null或者非默认值类型,返默认数据。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- **参数:**
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。它不能为空。 |
| defValue | ValueType | 是 | 默认返回值。支持number、string、boolean。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;ValueType&gt; | Promise实例,用于异步获取结果。 |
- 示例:
```
let promiseget = preferences.get('startup', 'default')
promiseget.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
})
```
### put
put(key: string, value: ValueType, callback: AsyncCallback&lt;void&gt;): void
首先获取指定文件对应的Preferences实例,然后借助Preferences API将数据写入Preferences实例,通过flush或者flushSync将Preferences实例持久化。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要修改的存储的key。它不能为空。 |
| value | ValueType | 是 | 存储的新值。支持number、string、boolean。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
preferences.put('startup', 'auto', function (err) {
if (err) {
console.info("Put the value of startup failed with err: " + err)
return
}
console.info("Put the value of startup successfully.")
})
```
### put
put(key: string, value: ValueType): Promise&lt;void&gt;
首先获取指定文件对应的Preferences实例,然后借助Preferences API将数据写入Preferences实例,通过flush或者flushSync将Preferences实例持久化。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要修改的存储的key。它不能为空。 |
| value | ValueType | 是 | 存储的新值。支持number、string、boolean。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
- 示例:
```
let promiseput = preferences.put('startup', 'auto')
promiseput.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
})
```
### has
has(key: string, callback: AsyncCallback&lt;boolean&gt;): boolean
检查存储对象是否包含名为给定key的存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;boolean&gt; | 是 | 回调函数。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| boolean | true表示存在,false表示不存在。 |
- 示例:
```
preferences.has('startup', function (err, isExist) {
if (err) {
console.info("Check the key of startup failed with err: " + err)
return
}
if (isExist) {
console.info("The key of startup is contained.")
}
})
```
### has
has(key: string): Promise&lt;boolean&gt;
检查存储对象是否包含名为给定key的存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。它不能为空。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise实例,用于异步处理。 |
- 示例:
```
let promisehas = preferences.has('startup')
promisehas.then((isExist) => {
if (isExist) {
console.info("The key of startup is contained.")
}
}).catch((err) => {
console.info("Check the key of startup failed with err: " + err)
})
```
### delete
delete(key: string, callback: AsyncCallback&lt;void&gt;): void
从存储对象中删除名为给定key的存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称,不能为空。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
preferences.delete('startup', function (err) {
if (err) {
console.info("Delete startup key failed with err: " + err)
return
}
console.info("Deleted startup key successfully.")
})
```
### delete
delete(key: string): Promise&lt;void&gt;
从存储对象删除名为给定key的存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 要获取的存储key名称。 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
- 示例:
```
let promisedel = preferences.delete('startup')
promisedel.then(() => {
console.info("Deleted startup key successfully.")
}).catch((err) => {
console.info("Delete startup key failed with err: " + err)
})
```
### flush
flush(callback: AsyncCallback&lt;void&gt;): void
将当前preferences对象中的修改保存到当前的preferences,并异步存储到文件中。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
preferences.flush(function (err) {
if (err) {
console.info("Flush to file failed with err: " + err)
return
}
console.info("Flushed to file successfully.")
})
```
### flush
flush(): Promise&lt;void&gt;
将当前preferences对象中的修改保存到当前的preferences,并异步存储到文件中。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
- 示例:
```
let promiseflush = preferences.flush()
promiseflush.then(() => {
console.info("Flushed to file successfully.")
}).catch((err) => {
console.info("Flush to file failed with err: " + err)
})
```
### clear
clear(callback: AsyncCallback&lt;void&gt;): void
清除此存储对象中的所有存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数。 |
- 示例:
```
preferences.clear(function (err) {
if (err) {
console.info("Clear to file failed with err: " + err)
return
}
console.info("Cleared to file successfully.")
})
```
### clear
clear(): Promise&lt;void&gt;
清除此存储对象中的所有存储。
此方法为异步方法。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Promise&lt;void&gt; | Promise实例,用于异步处理。 |
- 示例:
```
let promiseclear = preferences.clear()
promiseclear.then(() => {
console.info("Cleared to file successfully.")
}).catch((err) => {
console.info("Clear to file failed with err: " + err)
})
```
### on('change')
on(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
订阅数据变更者类,订阅的key的值发生变更后,在执行flush方法后,callback方法会被回调。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 说明 |
| -------- | -------- | -------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;{ key : string }&gt; | 回调对象实例。 |
- 示例:
```
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
preferences.on('change', observer)
preferences.put('startup', 'auto')
preferences.flush() // observer will be called.
```
### off('change')
off(type: 'change', callback: Callback&lt;{ key : string }&gt;): void
当不再进行订阅数据变更时,使用此接口取消订阅。
**系统能力**:SystemCapability.DistributedDataManager.Preferences.Core
- 参数:
| 参数名 | 类型 | 说明 |
| -------- | -------- | -------- |
| type | string | 事件类型,固定值'change',表示数据变更。 |
| callback | Callback&lt;{ key : string }&gt; | 需要取消的回调对象实例。 |
- 示例:
```
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
preferences.off('change', observer)
```
......@@ -40,21 +40,6 @@ data_rdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) {
})
```
API9的示例请参考如下代码:
```
import Ability from '@ohos.application.Ability'
import data_rdb from '@ohos.data.rdb'
export default class MainAbility extends Ability {
const STORE_CONFIG = { name: "RdbTest.db"}
const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)"
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(SQL_CREATE_TABLE)
console.info('create table done.')
})
}
```
## data_rdb.getRdbStore
getRdbStore(context: Context, config: StoreConfig, version: number): Promise&lt;RdbStore&gt;
......@@ -96,28 +81,6 @@ promisegetRdb.then(async (rdbStore) => {
})
```
API9的示例请参考如下代码:
```
import Ability from '@ohos.application.Ability'
import data_rdb from '@ohos.data.rdb'
export default class MainAbility extends Ability {
const STORE_CONFIG = { name: "RdbTest.db" }
const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)"
let promisegetRdb = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1);
promisegetRdb.then(async (rdbStore) => {
let promiseExecSql = rdbStore.executeSql(SQL_CREATE_TABLE, null)
promiseExecSql.then(() => {
console.info('executeSql creat done.')
}).catch((err) => {
console.log("executeSql creat err.")
})
}).catch((err) => {
console.log("getRdbStore err.")
})
}
```
## data_rdb.deleteRdbStore
deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&gt;): void
......@@ -141,18 +104,6 @@ deleteRdbStore(context: Context, name: string, callback: AsyncCallback&lt;void&g
})
```
API9的示例请参考如下代码:
```
import Ability from '@ohos.application.Ability'
import data_rdb from '@ohos.data.rdb'
export default class MainAbility extends Ability {
data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) {
console.info('delete store done.')
})
}
```
## data_rdb.deleteRdbStore
deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
......@@ -183,21 +134,6 @@ deleteRdbStore(context: Context, name: string): Promise&lt;void&gt;
})
```
API9的示例请参考如下代码:
```
import Ability from '@ohos.application.Ability'
import data_rdb from '@ohos.data.rdb'
export default class MainAbility extends Ability {
let promisedeleteRdb = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promisedeleteRdb.then(()=>{
console.info('delete store done.')
}).catch((err) => {
console.log("deleteRdbStore err.")
})
}
```
## RdbPredicates
表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。
......
......@@ -4,7 +4,7 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。<br/>从API Version 9开始,该接口不再维护,推荐使用新接口 [@ohos.data.preferences](js-apis-data-preferences.md)
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
......@@ -45,7 +45,7 @@ getStorageSync(path: string): Storage
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
context.getFilesDir((err, path) => {
if (err) {
......@@ -78,7 +78,7 @@ getStorage(path: string, callback: AsyncCallback&lt;Storage&gt;): void
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
context.getFilesDir((err, path) => {
if (err) {
......@@ -120,7 +120,7 @@ getStorage(path: string): Promise&lt;Storage&gt;
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
context.getFilesDir((err, path) => {
if (err) {
......
......@@ -2,7 +2,7 @@
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
>
> - 从API Version 6开始,该接口不再维护,可以使用接口['@ohos.data.storage'](js-apis-data-storage.md)。在API Version 9后,推荐使用新接口 ['@ohos.data.preferences'](js-apis-data-preferences.md)。
> - 从API Version 6开始,该接口不再维护,可以使用接口['@ohos.data.storage'](js-apis-data-storage.md)。
>
> - 本模块首批接口从API version 3开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册