# JS App Development Guide
# 1. Framework Introduction
# 1.1 Framework Overview
This framework is designed for application development focusing on the frontend development technology stack. It adopts popular frontend development patterns, aligns with the thinking habits of mainstream frontend developers, significantly improves application performance, and provides a wealth of system capabilities to meet basic application functional requirements.
# 2. File Structure
An application consists of one manifest.json file and multiple page/component .ux files:
- The
manifest.jsonfile defines the application description, function permission declarations, system configurations, and page routing information. - Page/component
.uxfiles implement specific functions of a single page or component, including UI templates, style sheets, data definitions, and callback event handling. For detailed usage, refer to File Organization.
# 3. Application Framework
# 3.1 Route Management
The framework manages the page routing of the entire application, enabling seamless switching between pages and governing the complete lifecycle of each page.
- Developers must register pages in
manifest.json. - Page switching is implemented in code using the interface methods provided by the framework.
For detailed usage, refer to manifest File, Page Routing, and Page Launch Modes.
# 3.2 Data Binding
Data binding enables easy synchronization between data and views. When modifying data, you only need to update the data in the logic layer, and the view layer will automatically refresh accordingly. For detailed usage of data binding, refer to Template.
# 3.3 UI Components
The framework provides a set of basic UI components. In addition to supporting common HTML5 tags (e.g., <div>, <input>), component tags also include native UI-related tags such as <switch>, <slider>, and <list>.
For detailed usage, refer to Components.
# 3.4 Native Interfaces
The framework also offers abundant native interfaces, such as network requests and local storage. These APIs greatly reduce developer workload and accelerate application development. For detailed usage, refer to Interfaces.
# 4. Supported Devices
| Model | Supported Quick App System Version | Screen Resolution | Screen Size |
|---|---|---|---|
| imoo Z1 | 1.5.0 | 240x240 | 1.3 inches |
| imoo Z7 | 1.0.0 | 240x240 | 1.3 inches |
| imoo Z3 | 1.0.0 | 320x360 | 1.5 inches |
# 5. File Organization
# 5.1 Application Resources
An application includes:
- A
manifestfile describing project configuration information. - An
app.uxfile storing public resource scripts for the project. - Multiple
.uxfiles describing pages.
Typical Example of Directory Structure:
Application Root Directory
├── manifest.json
├── app.ux
├── page1
│ ├── index.ux
├── page2
│ ├── index.ux
└── common
├── xxx.png
└── xxx.css
- The common directory stores shared resource files (e.g., images, CSS, JS).
# 5.2 Application Resource Access Rules
# 5.2.1 Path Types
- Absolute Path: Paths starting with / (e.g., /common/a.png).
- Relative Path: Paths not starting with / (e.g., a.png, ../common/a.png).
# 5.2.2 File Types
- Code Files: Files containing code, such as .js, .css, and .ux.
- Resource Files: Files used only as data (e.g., images, audio).
# 5.2.3 Access Specifications
- When importing other code files into a code file, use relative paths (e.g., ../common/style.css).
- When referencing resource files (e.g., images, audio) in a code file, absolute paths are recommended (e.g., /common/a.png).
- In CSS, access resource files using url(PATH) (consistent with frontend development), e.g., url(/common/a.png).
# 5.3 Storage Directory Definition
- When an application accesses files using file storage interfaces, it can access predefined file read/write directories using a specific scheme (only internal is supported).
- Access to files outside the following directories is denied (using ../ to access parent directories is prohibited).
| Directory Type | Path Prefix | Access Visibility | Description |
|---|---|---|---|
| Application Private | internal://app/ | App-only | Deleted when the application is uninstalled. |
# 6. manifest File
The manifest.json file contains the application description, interface declarations, and page routing information.
# 6.1 manifest Attributes
| Attribute | Type | Default Value | Required | Description |
|---|---|---|---|---|
| package | String | - | Yes | Application package name. If there is an existing cooperative Android app, ensure consistency with the Android app’s package name. Recommended format: com.company.module (e.g., com.example.demo). |
| name | String | - | Yes | Application name (max. 6 Chinese characters). Consistent with the name in the app store. Used for display on desktop icons, pop-ups, etc. |
| icon | String | - | Yes | Application icon: 86x86 pixels, 10px rounded corners, PNG format (bit depth ≥24). |
| smallIcon | String | - | Yes | Small application icon: 76x76 pixels, 10px rounded corners, PNG format (bit depth ≥24). |
| forbiddenIcon | String | - | Yes | Disabled application icon (displayed when the watch app is disabled by the parent): 86x86 pixels, 10px rounded corners. |
| versionName | String | - | No | Application version name (e.g., "1.0.0"). |
| versionCode | Number | - | Yes | Application version number (must be a number). Start from 1 and increment by 1 for each new package upload. |
| features | Array | - | No | List of interfaces. Refer to the documentation of each interface for details. |
| config | Object | - | Yes | System configuration information. See 6.2 config for details. |
| permissions | Array | - | Yes | Permission configuration. See 6.3 permissions for details. |
| router | Object | - | Yes | Routing information. See 6.4 router for details. |
# 6.2 config Attributes
| Attribute | Type | Default Value | Description |
|---|---|---|---|
| logLevel | String | log | Log printing level: off, error, warn, info, log, debug. |
| designWidth | Number | 750 | Page design base width (scales element sizes based on actual device width). For watches, set to 240 (watch screen physical size: 240x240). |
# 6.3 permissions
After declaration, a prompt for required permissions will appear when the app starts. Users can choose Deny or Allow:
- Deny: Exit the app. The prompt will reappear on next launch.
- Allow: Enter the app.
| Permission Value | Permission Description |
|---|---|
| 0 | Access network |
| 1 | Access Bluetooth |
| 2 | Toggle WIFI |
| 3 | Access camera |
| 4 | Read/write files on the device |
| 5 | Record audio |
| 6 | Access contacts |
| 7 | Access location information |
| 11 | Media audio/video |
Sample Code:
{
"permissions": [
{
"0": "Access network",
"4": "Read/write files on the device"
}
]
}
# 6.4 router
Defines the composition and configuration of pages. Routing must be configured.
| Attribute | Type | Default Value | Required | Description |
|---|---|---|---|---|
| entry | String | - | Yes | Name of the home page. |
| pages | Object | - | Yes | List of page configurations. The key is the page name (corresponding to the page directory, e.g., "hello" for the hello directory). The value is the detailed page configuration (page). See 6.4.1 router.pages for details. |
Sample Code:
"router": {
"entry": "home",
"pages": {
"home": {
"component": "index" // Corresponding to src/home/index.ux
},
"detail": {
"component": "detail" // Corresponding to src/detail/detail.ux
},
"views/about": {
"component": "index" // Corresponding to src/views/about/index.ux
}
}
}
Example of Page Navigation in Components:
router.push({ uri: 'home' });
router.push({ uri: 'detail' });
router.push({ uri: 'views/about' });
# 6.4.1 router.pages
Defines routing information for a single page.
| Attribute | Type | Default Value | Required | Description |
|---|---|---|---|---|
| component | String | - | Yes | Component name corresponding to the page (consistent with the .ux filename, e.g., "index" for index.ux). |
# 7. UX Files
Apps, pages, and custom components are written in .ux files. A .ux file consists of three parts: template (UI structure), style (styling), and script (logic).
# 7.1 Typical Page UX File Example
<template>
<div class="demo-page">
<text class="title">Welcome to {{title}}</text>
</div>
</template>
<style>
.demo-page {
flex-direction: column;
justify-content: center;
align-items: center;
}
.title {
font-size: 40px;
text-align: center;
}
</style>
<script>
import router from '@system.router'
export default {
data: {
title: 'Sample Page'
},
routeDetail () {
router.push ({
uri: '/detail'
})
}
}
</script>
# 7.2 app.ux
Manages global JavaScript logic and the app lifecycle.
<script>
export default {
onCreate() {
console.info('Application onCreate');
},
onDestroy() {
console.info('Application onDestroy');
},
}
</script>
# 8. Template
A tag language similar to HTML. It combines basic components, custom components, and events to build the page structure.
Note: A template can only have one root node (e.g., div). Do not include multiple root nodes under
<template>.
# 8.1 Data Binding
<template>
<text>{{message}}</text>
</template>
<script>
export default {
data: {
message: 'Hello'
}
}
</script>
# 8.2 Event Binding
<template>
<div>
<!-- Standard format -->
<text onclick="press"></text>
<!-- Shorthand -->
<text @click="press"></text>
</div>
</template>
<script>
export default {
press(e) {
console.log('handleClick');
}
}
</script>
Supported Event Callback Formats (`{{}}` can be omitted):
- "fn": fn is the event callback function name (implemented in
<script>). - "fn(a,b)": Function parameters (e.g., a, b) can be constants or page data variables (no need for this prefix).
- "a+b": Expressions (data types of a and b are the same as above).
When the callback function is called, an evt parameter is automatically added to the end of the parameter list. Use evt to access context data related to the callback event (e.g., click position x/y for click events).
# 8.3 List Rendering
<template>
<div>
<div for="{{list}}" tid="id">
<text>{{$idx}}</text>
<text>{{$item.name}}</text>
</div>
<!-- Custom element variable name -->
<div for="{{value in list}}" tid="id">
<text>{{$idx}}.{{value.name}}</text>
</div>
<!-- Custom element variable and index name -->
<div for="{{(index, value) in list}}" tid="id">
<text>{{index}}.{{value.name}}</text>
</div>
</div>
</template>
<script>
export default {
data: {
list: [
{id: 1, name: 'jack', age: 18},
{id: 2, name: 'tony', age: 19},
]
}
}
</script>
for Directive Syntax:
- for="{{list}}": list is the source data array. The default array element name is $item.
- for="{{value in list}}": value is the custom array element name. The default index name is $idx.
- for="{{(index, value) in list}}": index is the custom index name, and value is the custom element name.
tid Attribute:
Specifies the unique ID of array elements. If not specified, the array index ($idx) is used by default. It optimizes list redrawing efficiency by reusing element nodes.
Notes:
- The data attribute specified by tid must exist (otherwise, runtime errors may occur).
- The data attribute specified by tid must be unique (otherwise, performance issues may occur).
- Expressions are not supported for tid.
# 8.4 Conditional Rendering
There are two types of conditional rendering: if/elif/else and show.
# 8.4.1 if/elif/else
When if is false, the component is not built in the vdom and not rendered. Nodes using if/elif/else must be siblings (otherwise, compilation fails).
<template>
<div>
<text if="{{display}}">Hello-1</text>
<text elif="{{display}}">Hello-2</text>
<text else>Hello-3</text>
</div>
</template>
<script>
export default {
data: {
display: false
}
}
</script>
# 8.4.2 show (Rendering Optimization)
When show is false, the component is not rendered but remains built in the vdom (only the display style is set to none).
<template>
<text show="{{visible}}">Hello</text>
</template>
<script>
export default {
data: {
visible: false
}
}
</script>
Note: Do not set for and if on the same element.
# 9. Style
Describes the styling of the template components and determines how components are displayed.
- Layout: Uses CSS Flexbox (flexible box) styling. For some native components, CSS is slightly extended and modified.
- Watch Screen: Physical size is 240x240 pixels.
# 9.1 Style Import
Two ways to import external files:
<!-- Import external file (replaces internal styles) -->
<style src="./style.css"></style>
<!-- Merge external files -->
<style>
@import './style.css';
.a {
}
</style>
# 9.2 Inline Styles
Control component styles using the style or class attribute:
<!-- Inline style -->
<div style="color:red; margin: 10px;"/>
<!-- Class declaration -->
<div class="normal append"/>
# 9.3 Selectors
CSS selectors are used to select elements for styling. Supported selectors:
| Selector | Example | Description |
|---|---|---|
| .class | .container | Selects components with class="container". |
| , | .title, .content | Selects components with class="title" or class="content". |
ID selectors and parent-child cascading selectors are not supported.
# 9.4 Pseudo-Classes
Pseudo-classes are keywords in selectors that specify special states of elements. Only background-color and background-image are supported for styling.
| Name | Supported Components | Description |
|---|---|---|
| :active | input[type="button"] | Selects elements activated by the user (for example, a pressed button). |
| :checked | input[type="checkbox"], [type="radio"] | Selects elements with the checked attribute set to true. |
# 9.5 Style Precompilation
Supports precompilation of Less and Sass (provides variables, calculations, etc.). Nested properties of Less/Sass are not supported.
Supports precompilation of Less and Sass (provides variables, calculations, etc.). Nested properties of Less/Sass are not supported.
<!-- Import external file (replaces internal styles) -->
<style lang="less" src="./lessFile.less"></style>
<!-- Merge external files -->
<style lang="less">
@import './lessFile.less';
.page-less #testTag .less-font-text,
.page-less #testTag .less-font-comma{
font-size: 60px;
}
/* Unsupported syntax */
.page-less {
#testTag {
.less-font-text, .less-font-comma {
font-size: 60px;
}
}
}
</style>
# 9.6 Dynamically Changing Styles
Methods to dynamically modify styles (consistent with traditional frontend development):
- Modify class: Update the value of variables used in the component’s class attribute.
- Modify inline style: Update a specific CSS value in the component’s style attribute.
- Modify bound objects: Control element styles via bound objects.
- Modify bound style strings: Control element styles via style strings.
<template>
<div class="container">
<text class="title {{ className }}" onclick="changeClassName">Click to change text color</text>
<text class="title" style="color: {{ textColor }}" onclick="changeInlineStyle">Click to change text color</text>
<text class="title" style="{{ styleObj }}" onclick="changeStyleObj">Click to change text color</text>
<text class="title" style="{{ styleText }}" onclick="changeStyleText">Click to change text color</text>
</div>
</template>
<script>
export default {
data: {
className: 'text-blue',
textColor: '#0faeff',
styleObj: {
color: 'red'
},
styleText: 'color: blue'
},
changeClassName() {
this.className = 'text-red'
},
changeInlineStyle() {
this.textColor = '#f76160'
},
changeStyleObj() {
this.styleObj = {
color: 'yellow'
}
},
changeStyleText() {
this.styleText = 'color: green'
}
}
</script>
# 10. Script
Defines page data and implements lifecycle interfaces.
# 10.1 Supported Syntax
Only the following ES6 syntax is supported:
- let/const
- Arrow functions
- class
- Default values
- Destructuring assignment
- Destructuring binding pattern
- Enhanced object initializer
- for-of
- Rest parameter
- Template strings
To use Promise, download the third-party library es6-promise and import it globally in app.ux.
# 10.2 Module Declaration
Import functional modules via import and call module methods in code:
import fetch from '@system.fetch';
# 10.3 Code Reference
It is recommended to use import to import JS code:
import utils from '../common/utils.js';
# 10.4 Public Methods
| Attribute | Type | Description |
|---|---|---|
| $element | Function | Retrieves the DOM object of a component with a specified id. If no id is specified, returns the root component’s DOM object. Usage:- <template><div id='xxx'></div></template>- this.$element('xxx') (retrieves the div with id="xxx")- this.$element() (retrieves the root component). |
# 10.5 Retrieving DOM Elements
Retrieve DOM elements via $element:
<template>
<div class="container">
<list id="list">
<list-item for="{{todolist}}">
<text>{{$item.title}}</text>
<text>{{$item.date}}</text>
</list-item>
</list>
</div>
</template>
<script>
export default {
data: {
todolist: [{
title: 'Go to school',
date: '2020-01-01 10:00:00',
}, {
title: 'Do homework',
date: '2020-01-02 20:00:00',
}],
},
onReady(){
const elem = this.$element('list');
// Scroll the list to the item at the specified index
elem.scrollTo({
index: 1
});
}
}
</script>
# 10.6 Global Objects
A global object exists in global JS (similar to the window object in browsers):
// app.ux
global.name = 'imoo';
// index.ux
console.log(global.name); // Output: 'imoo'
# 10.7 App Object
Access via $app:
| Attribute | Type | Description |
|---|---|---|
| $def | Object | Retrieves the object exposed in app.ux using this.$app.$def. |
# 10.8 Lifecycle Interfaces
# 10.8.1 Page Lifecycle
| Attribute | Type | Parameters | Return Value | Description | Trigger Timing |
|---|---|---|---|---|---|
| onInit | Function | None | None | Page initialization | Triggered once when page data initialization is complete. |
| onReady | Function | None | None | Page creation complete | Triggered once when page creation is complete. |
| onShow | Function | None | None | Page display | Triggered when the page is displayed. |
| onHide | Function | None | None | Page hidden | Triggered when the page is hidden. |
| onDestroy | Function | None | None | Page destruction | Triggered when the page is destroyed. |
Lifecycle Sequence for Page A:
- Open Page A: onInit() → onReady() → onShow()
- Open Page B from Page A: onHide()
- Return to Page A from Page B: onShow()
- Exit Page A: onHide() → onDestroy()
- Page hidden to background: onHide()
- Page restored from background to foreground: onShow()
# 10.8.2 App Lifecycle
| Attribute | Type | Parameters | Return Value | Description | Trigger Timing |
|---|---|---|---|---|---|
| onCreate | Function | None | None | App creation | Triggered when the app is created. |
| onDestroy | Function | None | None | App exit | Triggered when the app exits. |
# 11. Multi-Language Support
Apps based on this framework may target multiple countries and regions. With multi-language support, a single app (one RPK file) can support multiple language versions. Developers do not need to develop separate source code projects for different languages, reducing maintenance effort.
To use the system’s default language, developers only need two steps: define resource files and reference resources.
# 11.1 Define Resource Files
Resource files store business information for multiple languages (using JSON files).
- Create an i18n folder in the project’s src directory.
- Place resource definition files for each language/region in i18n (e.g., zh.json for Chinese, en.json for English).
- If only one language is supported, declare a single file named defaults.json.
Sample JSON File Content:
{
"app-name": "Application Name",
"message": {
"pageA": {
"text": "pure-text-content",
"format": {
"object": "type-{name}",
"array": "type-{0}"
},
"array": [
"item-type-string",
{
"key": "item-type-object-attribute"
},
["item-type-array"]
],
"plurals": {
"double": "car | cars",
"three": "no apples | one apple | {count} apples",
"format": {
"object": "type-{name}",
"array": "type-{0}"
}
}
}
}
}
- Reference content via paths like message.pageA.text (e.g., "pure-text-content").
# 11.2 Reference Resources in Pages
Multi-language usage in pages relies on ViewModel functions such as $t (usable in <template> or <script>).
Sample Code:
<template>
<div>
<text>{{ $t('message.pageA.text') }}</text>
<text>{{ $t('message.pageA.format.object', { name: 'arg-object' }) }}</text>
<text>{{ $t('message.pageA.format.array', ['arg-array']) }}</text>
</div>
</template>
<script>
export default {
onInit() {
// Simple formatting:
this.$t('message.pageA.text');
this.$t('message.pageA.format.object', { name: 'arg-object' });
this.$t('message.pageA.format.array', ['arg-array']);
}
};
</script>
# 11.3 Simple Formatting Methods
| Attribute | Type | Parameters | Description |
|---|---|---|---|
| $t | Function | - path: String (resource path) - arg0: Object/Array (formatting parameters, optional) | Performs simple replacement based on the system language. Example: this.$t('message.pageA.text'). |
Examples:
// No additional parameters: Outputs "pure-text-content"
this.$t('message.pageA.text');
// Additional object parameter: Outputs "type-arg-object"
this.$t('message.pageA.format.object', { name: 'arg-object' });
// Additional array parameter: Outputs "type-arg-array"
this.$t('message.pageA.format.array', ['arg-array']);
# 11.4 Retrieve Language
# 11.4.1 Desktop App Name
The desktop app name changes with the system language. Define app-name in each language file under the i18n directory to set the app name for different languages (see 11.1 Define Resource Files for examples).
# 11.4.2 Language File Naming
Language files in the i18n directory must follow this format:
| File Name | Language |
|---|---|
| zh-CN.json | Chinese (Simplified) |
| zh-TW.json | Chinese (Traditional) |
| en.json | English |
| de-DE.json | German |
| es-ES.json | Spanish |
| in-ID.json | Indonesian |
| pl-PL.json | Polish |
| th.json | Thai |
| vi-VN.json | Vietnamese |
# 12. Components
WARNING: Custom components have known issues and are not supported currently.
# 12.1 Custom Components
When developing pages, developers must use Native components (e.g., text, div) rendered by the Native layer. For complex pages, writing all UI code in a single <template> reduces maintainability and causes unnecessary coupling.
Custom components solve this problem:
- Split pages into functional modules (each module manages its own logic and UI).
- Used like Native components (rendered based on their
<template>). - Similar to pages (have a ViewModel to manage data, events, and methods).
A page is a special custom component (no import required, serves the entire page).
# 12.1.1 Custom Component Example
<template>
<div>
<text>Custom Component:</text>
<text>{{ say }}</text>
<text>{{ obj.name }}</text>
</div>
</template>
<script>
// Child Component
export default {
data: {
say: 'hello',
obj: {
name: 'quickApp'
}
},
onInit() {
console.log('I am a child component')
}
}
</script>
# 12.1.2 Component Import
<import name="child" src="./child.ux"></import>
<template>
<div>
<text>Imported Component:</text>
<child></child>
</div>
</template>
# 12.1.3 Parent-Child Component Communication
1. Parent to Child
The child component declares exposed properties in the props attribute, and the parent component passes data via the child component’s tag.
Note: Currently, converting hyphens to camelCase for props is not supported.
<!-- Child Component -->
<template>
<div class="child-demo">
<text>Child Component:</text>
<text>{{ say }}</text>
<text>{{ obj.name }}</text>
</div>
</template>
<script>
export default {
props: ['say', 'obj'],
onInit() {
console.info(`Data from parent:`, this.say, this.obj)
}
}
</script>
<!-- Parent Component -->
<import name="child" src="./child.ux"></import>
<template>
<div class="parent-demo">
<child say="{{say}}" obj="{{obj}}"></child>
</div>
</template>
<script>
export default {
data: {
say: 'hello',
obj: {
name: 'child-demo'
}
}
}
</script>
2. Child to Parent
The child component triggers a custom event bound to the node via $emit() to execute the parent component’s method.
<!-- Parent Component -->
<import name="child" src="./child.ux"></import>
<template>
<div class="parent-demo">
<child say="{{say}}" obj="{{obj}}" @change-name="handleChange"></child>
</div>
</template>
<script>
export default {
data: {
say: 'hello',
obj: {
name: 'child-demo'
}
},
handleChange(data) {
this.obj = {
name: data.name // Updates to "World"
}
}
}
</script>
<!-- Child Component -->
<template>
<div class="child-demo">
<text>Child Component:</text>
<text>{{ say }}</text>
<text @click="setName">{{ obj.name }}</text>
</div>
</template>
<script>
export default {
props: ['say', 'obj'],
onInit() {
console.info(`Data from parent:`, this.say, this.obj)
},
setName() {
this.$emit('changeName', {
name: 'World'
})
}
}
</script>
# 12.1.4 Sibling/Cross-Level Component Communication
For communication between siblings, cross-parent-child components, or different pages:
- Expose an eventbus (with publish-subscribe capabilities) in app.ux.
- Use the eventbus in other pages or components.
Step 1: Define eventbus in app.ux
class EventBus {
constructor() {
this.callbacks = {};
}
$on(name, callback) {
this.callbacks[name] = this.callbacks[name] || [];
this.callbacks[name].push(callback);
}
$emit(name, data) {
this.callbacks[name].forEach(fn => fn(data));
}
}
export default {
eventbus: new EventBus()
}
Step 2: Communicate Between Page A and Page B
// Page A (Publish)
this.$app.$def.eventbus.$emit('message', {
name: 'Jay',
age: 18
})
// Page B (Subscribe)
this.$app.$def.eventbus.$on('message', data => {
console.log(data) // Output: { name: 'Jay', age: 18 }
})
# 12.2 Common Properties
Common properties are supported by all components. Developers can use them on any component tag.
# 12.2.1 Regular Properties
| Name | Type | Default Value | Description |
|---|---|---|---|
| id | String | - | Unique identifier for the component. |
| style | String | - | Inline style declaration. |
| class | String | - | Reference to style sheets. |
# 12.2.2 Rendering Properties
| Name | Type | Default Value | Description |
|---|---|---|---|
| for | Array | - | Loops to expand (repeat) the current tag. |
| if | Boolean | - | Conditionally adds or removes the current tag from the DOM. |
| show | Boolean | - | Shows or hides the current tag (similar to toggling display: flex/none). |
# 12.3 Common Events
Common events are callback events supported by all components. Developers can register callbacks using on{eventName} (e.g., onclick) or @{eventName} (e.g., @click) on component tags.
| Name | Parameters | Description |
|---|---|---|
| touchstart | TouchEvent | Triggered when a finger first touches the component. |
| touchmove | TouchEvent | Triggered when a finger moves after touching the component. |
| touchend | TouchEvent | Triggered when a finger finishes touching the component. |
| touchcancel | TouchEvent | Triggered when a touch action is interrupted (e.g., incoming call, page exit). |
| click | - | Triggered by a click action. |
| longpress | - | Triggered by a long-press action. |
| swipe | SwipeEvent | Triggered after a quick swipe on the component. |
# 12.3.1 TouchEvent
| Attribute | Type | Description |
|---|---|---|
| type | String | Type of the current event (e.g., click, longpress). |
| timestamp | Number | Timestamp when the event is triggered. |
| point | Point | Coordinates of the touch point. See 12.3.2 Point for more details. |
# 12.3.2 Point
| Attribute | Type | Description |
|---|---|---|
| x | Number | Horizontal distance from the top-left corner of the screen (origin). |
| y | Number | Vertical distance from the top-left corner of the screen (origin). |
# 12.3.3 SwipeEvent
| Attribute | Type | Description |
|---|---|---|
| direction | String | Swipe direction: left, right, up, down. |
# 12.4 Common Styles
Common styles are supported by all components. They are used the same way as CSS properties and can be written in inline styles or <style> tags.
| Name | Type | Default Value | Description |
|---|---|---|---|
| width | <length> | <percentage> | 0 | Component width (defaults to 0 if not set). |
| height | <length> | <percentage> | - | Component height (defaults to 0 for some components if not set). |
| padding | <length> | 0 | Shorthand for all padding properties. |
| margin | <length> | 0 | Shorthand for all margin properties. |
| margin-[left/top/right/bottom] | <length> | 0 | Sets left/top/right/bottom margin individually. |
| border-width | <length> | 0 | Shorthand for all border width properties. |
| border-color | <color> | black | Shorthand for all border color properties. |
| border-radius | <length> | - | Sets the border radius of the element. |
| border-[top/bottom]-[left/right]-radius | <length> | - | Sets the radius of individual corners. |
| background-color | <color> | - | Sets the background color. |
| background-image | <uri> | - | Sets the background image. |
| background-size | contain | cover | auto | <length> | <percentage> | - | Sets the background image size. |
| background-repeat | repeat | no-repeat | repeat | Sets whether and how the background image repeats. |
| background-position | <length> | <percentage> | left | right | top | bottom | center | 0px 0px | Sets the background image position. |
| display | String | flex | Defines the element’s box type: flex (flex layout), none (not rendered). |
| position | fixed | absolute | relative | - | Defines the element’s positioning type. |
| [left/top/right/bottom] | <length> | - | Used with fixed or absolute positioning. |
Note: Common styles are not mandatory, but if width and height are not set, they default to 0 and the component will not be rendered.
Supported Color Formats
- rgb(255, 255, 255)
- rgba(255, 255, 255, 1.0)
- HEX: #rrggbb
- Enumeration: black, white, etc. (not supported in script).
# 12.5 Animation Styles
WARNING: Animations have known issues (may cause element misalignment). Use the frame animation component instead for now.
Components generally support dynamic translation effects set in style or CSS.
| Name | Type | Default Value | Description |
|---|---|---|---|
| transform | String | - | See Table 1: transform Description for details. |
| animation-name | String | - | Specifies @keyframes. See Table 2: @keyframes Description for details. |
| animation-delay | <time> | 0 | Delay before animation starts. Supported units: s (seconds), ms (milliseconds). Default unit: ms (e.g., 1000ms, 1s). |
| animation-duration | <time> | 0 | Animation cycle duration. Supported units: s, ms. Default unit: ms. Maximum: 60s. Must be set; otherwise, duration is 0 and the animation will not play. |
| animation-iteration-count | Number | infinite | 1 | Number of animation plays. Use infinite for infinite loops. |
| animation-timing-function | String | linear | Animation speed curve: • linear: Constant speed.• ease-in: Starts slowly (cubic-bezier(0.42, 0.0, 1.0, 1.0)).• ease-out: Ends slowly (cubic-bezier(0.0, 0.0, 0.58, 1.0)).• ease-in-out: Starts and ends slowly (cubic-bezier(0.42, 0.0, 0.58, 1.0)). |
| animation-fill-mode | String | none | State after animation ends: • none: Reverts to initial state.• forwards: Retains the state of the last keyframe. |
Table 1: transform Description
| Name | Type | Description |
|---|---|---|
| translateX | <length> | Horizontal translation (X-axis). |
| translateY | <length> | Vertical translation (Y-axis). |
Table 2: @keyframes Description
| Name | Type | Default Value | Description |
|---|---|---|---|
| background-color | <color> | - | Background color applied to the component after animation. |
| width | <length> | - | Width applied to the component after animation. |
| height | <length> | - | Height applied to the component after animation. |
| transform | String | - | Transformation type applied to the component. |
For cases where start/end values are not supported, explicitly specify them using from and to:
@keyframes Go {
from {
background-color: #f76160;
}
to {
background-color: #09ba07;
}
}
# 12.6 Component Details
# 12.6.1 div
Basic container used as the root node of the page structure or for grouping content.
- Child Components: Supported.
- Properties: Supports Common Properties.
- Events: Supports Common Events.
- Styles: Supports Common Styles + additional styles below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| flex-direction | String | row | No | Flex container main axis direction: • column: Vertical (top to bottom).• row: Horizontal (left to right). |
| flex-wrap | String | nowrap | No | Whether the flex container wraps lines (cannot be modified dynamically): • nowrap: No wrap (single line).• wrap: Wrap (multiple lines). |
| justify-content | String | flex-start | No | Main axis alignment for the current line of the flex container: • flex-start: Items at the start of the container.• flex-end: Items at the end of the container.• center: Items centered in the container.• space-between: Items with space between them.• space-around: Items with space around them. |
| align-items | String | flex-start | No | Cross-axis alignment for the current line of the flex container: • flex-start: Items aligned to the start of the cross-axis.• flex-end: Items aligned to the end of the cross-axis.• center: Items centered on the cross-axis. |
# 12.6.2 list
Basic container used for page structure or content grouping (optimized for long lists).
- Child Components: Only
<list-item>is supported. - Properties: Supports Common Properties.
- Events: Supports Common Events + additional events below:
| Name | Parameters | Description |
|---|---|---|
| scroll | { scrollX: scrollXValue, scrollY: scrollYValue, scrollState: stateValue } | Triggered when the list scrolls. scrollState values:• 0: List stopped.• 1: List scrolling via user gesture.• 2: List scrolling (user has released). |
| scrollbottom | - | Triggered when the list scrolls to the bottom. |
| scrolltop | - | Triggered when the list scrolls to the top. |
| scrollend | - | Triggered when the list finishes scrolling. |
| scrolltouchup | - | Triggered when the user lifts their finger during list scrolling. |
Methods:
| Name | Parameters | Description |
|---|---|---|
| scrollTo | { index: number } | Scrolls the list to the item at the specified index. |
Styles: Supports Common Styles.
# 12.6.3 list-item
Child component of <list> used to display individual list items.
- Child Components: Supported.
- Properties: Supports Common Properties.
- Events: Supports Common Events.
- Styles: Supports Common Styles.
Note: margin-related styles are not supported for list-item.
# 12.6.4 stack
Stack container where child components are stacked in order (later components cover earlier ones).
- Child Components: Supported.
- Properties: Supports Common Properties.
- Events: Supports Common Events.
- Styles: Supports Common Styles.
Note: Since absolute positioning does not support percentages, margin is not supported for child components of stack.
# 12.6.5 swiper
Swipe container that enables switching between child components.
- Child Components: Supports all components except
<list>. - Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| index | Number | 0 | No | Index of the currently displayed child component. |
| loop | Boolean | false | No | Whether to enable looped swiping (cannot be modified dynamically). To enable looping: 1. The total length of remaining components (excluding the first) must be ≥ swiper length. 2. The total length of remaining components (excluding the last) must be ≥ swiper length. |
| duration | Number | - | No | Animation duration for component switching (in milliseconds). |
| vertical | Boolean | false | No | Whether to enable vertical swiping (uses vertical indicators; cannot be modified dynamically). |
- Events: Supports Common Events + additional events below:
| Name | Parameters | Description |
|---|---|---|
| change | { index: currentIndex } | Triggered when the index of the displayed component changes. |
- Styles: Supports Common Styles.
# 12.6.6 image
Image component used to render and display images.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| src | String | - | No | Image path. Supported formats: PNG, JPG (PNG bit depth ≥ 24). Cannot be used together with qrcode. |
| qrcode | String | - | No | Text used to generate a QR code. Cannot be used together with src. |
Notes: Maximum size of a single network image: 50KB. Maximum cached images per app: 100 images or 500KB. No limit on local image size/count, but single app installation package limit: 512KB.
Events: Supports Common Events.
Styles: Supports Common Styles + additional styles below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| object-fit | contain | cover | fill | none | scale-down | cover | No | Image scaling type: • contain: Maintains aspect ratio, fits within bounds (centered). • cover: Maintains aspect ratio, covers bounds (centered). • fill: Stretches to fill bounds (aspect ratio not preserved). • none: No scaling (centered). • scale-down: Maintains aspect ratio, scales down or stays the same size (effectively the smaller of contain and none, centered). |
# 12.6.7 image-animator
Image frame animation player.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| images | Array | - | Yes | Collection of frame information (each frame includes image path, size, and position). Supported formats: PNG, JPG. |
| iteration | Number | String | infinite | No | Number of animation plays: use a number for a fixed number of plays, or infinite for an infinite loop. |
| reverse | Boolean | false | No | Play order: • false: Play from first to last image. • true: Play from last to first image. |
| fixedsize | Boolean | true | No | Whether image size is fixed to component size: • true: Image size matches component size (ignores width, height, top, left). • false: Each image can set width, height, top, left individually. |
| duration | String | - | Yes | Single play duration. Supported units: s, ms (default is ms if unit omitted). duration = 0 disables animation. Changes take effect on the next animation loop. |
ImageFrame Description
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| src | <uri> | - | Yes | Image path (only local images are supported). |
| width | <length> | 0 | No | Image width. |
| height | <length> | 0 | No | Image height. |
| top | <length> | 0 | No | Vertical coordinate relative to the component’s top-left corner. |
| left | <length> | 0 | No | Horizontal coordinate relative to the component’s top-left corner. |
Events: Supports Common Events + additional events below:
| Name | Parameters | Description |
|---|---|---|
| stop | - | Triggered when the frame animation ends. |
Methods:
| Name | Parameters | Description |
|---|---|---|
| start | - | Starts the animation (restarts from frame 1 if called again). |
| pause | - | Pauses the animation. |
| stop | - | Stops the animation. |
| resume | - | Resumes the animation. |
| getState | - | Retrieves the play state: playing, paused, stopped. |
Styles: Supports Common Styles.
# 12.6.8 progress
Progress bar used to display content loading or operation progress.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| type | String | horizontal | No | Progress bar type (cannot be modified dynamically): - horizontal: Horizontal bar (arc bar via radius style). - circular: Circular loading animation. |
| percent | Number | 0 | No | Current progress (0-100). Invalid when type="circular". |
- Events: Supports Common Events.
- Styles: Supports Common Styles + additional styles below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| color | <color> | - | No | Progress bar color. |
| layer-color | <color> | - | No | Progress bar background color. |
| stroke-width | <length> | - | No | Progress bar width. |
| radius | <length> | - | No | Radius of the arc progress bar (must be used with center-x and center-y). Enables arc rendering. |
| center-x | <length> | - | No | Center X-coordinate of the arc progress bar (origin: component’s top-left corner). Must be used with center-y and radius. |
| center-y | <length> | - | No | Center Y-coordinate of the arc progress bar (origin: component’s top-left corner). Must be used with center-x and radius. |
| start-angle | <deg> | 240 | No | Start angle of the arc progress bar (baseline: 12 o’clock). Range: 0–360 (clockwise). |
| total-angle | <deg> | 240 | No | Total length of the arc progress bar. Range: -360 to 360 (negative values render counterclockwise). |
# 12.6.9 text
Text component used to display a segment of text.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| text-shaping | Boolean | false | No | Whether to enable emoji support. |
- Events: Supports Common Events.
- Styles: Supports Common Styles + additional styles below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| color | <color> | #ffffff | No | Text color. |
| font-size | <length> | 30px | No | Text size. |
| letter-spacing | <length> | 2px | No | Character spacing. |
| text-align | String | left | No | Text alignment: left, center, right. |
| text-overflow | String | clip | No | Text overflow handling: clip (clip to container) or ellipsis (show ... for overflowing text). |
# 12.6.10 marquee
Marquee component used to display a single line of scrolling text.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| scrollamount | Number | 6 | No | Maximum distance the marquee moves per scroll (pixels). |
- Events: Supports Common Events.
- Styles: Supports Common Styles + additional styles below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| color | <color> | #ffffff | No | Text color of the marquee. |
| font-size | <length> | 30px | No | Text size of the marquee. |
| font-family | String | HYQiHei-65S | No | Font. Only HYQiHei-65S is supported currently. |
# 12.6.11 chart
Chart component used to display line charts and bar charts.
- Child Components: Not supported.
- Properties: Supports Common Properties + additional properties below:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| type | String | line | Yes | Chart type (cannot be modified dynamically): - bar: Bar chart. - line: Line chart. |
| options | Object | - | Yes | Chart parameter settings (required for bar/line charts). Configures min/max values, tick count, visibility of X/Y axes, line width, smoothness, etc. See Table 1: options Definition for details. (Cannot be modified dynamically) |
| datasets | Array | - | Yes | Data collection (required for bar/line charts). Configures multiple datasets and their background colors. See Table 2: datasets Definition for details. |
Table 1: options Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| xAxis | Object | - | Yes | X-axis settings. Configures min/max values, tick count, and visibility. See Table 3: xAxis Definition for details. |
| yAxis | Object | - | Yes | Y-axis settings. Configures min/max values, tick count, and visibility. See Table 4: yAxis Definition for details. |
| series | Object | - | No | Data series settings (only for line charts). Configures line style (width, smoothness) and the style/size of the white dot at the front of the line. See Table 5: series Definition and Table 6: lineStyle Definition for details. |
Table 2: datasets Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| strokeColor | <color> | #ff6384 | No | Line color (only for line charts). |
| fillColor | <color> | #ff6384 | No | Fill color. |
| data | Array | - | Yes | Set of points for drawing lines or bars. |
| gradient | Boolean | false | No | Whether to display fill color. |
Table 3: xAxis Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| min | Number | 0 | No | Minimum X-axis value (no negative values; only for line charts). |
| max | Number | 100 | No | Maximum X-axis value (no negative values; only for line charts). |
| axisTick | Number | 10 | No | Number of X-axis ticks (1–20). Actual tick display depends on: chartWidthInPixels / (max - min). For bar charts, the number of bars per group matches the tick count (bars are drawn at tick positions). |
| display | Boolean | false | No | Whether to display the X-axis. |
| color | <color> | #c0c0c0 | No | X-axis color. |
Table 4: yAxis Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| min | Number | 0 | No | Minimum Y-axis value (no negative values). |
| max | Number | 100 | No | Maximum Y-axis value. |
| axisTick | Number | 10 | No | Number of Y-axis ticks (1–20). Actual display depends on: chartWidthInPixels / (max - min). |
| display | Boolean | false | No | Whether to display the Y-axis. |
| color | <color> | #c0c0c0 | No | Y-axis color. |
Table 5: series Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| lineStyle | Object | - | No | Line style settings (e.g., width, smoothness). See Table 6: lineStyle Definition for details. |
| headPoint | Point | - | No | Style and size of the white dot at the front of the line. See Table 7: HeadPoint/TopPoint/BottomPoint Definition for details. |
| topPoint | Point | - | No | Style and size of the dot at the highest point of the line. See Table 7. |
Table 6: lineStyle Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| width | <length> | 1px | No | Sets the line width. |
| smooth | Boolean | false | No | Whether to enable line smoothing. |
Table 7: HeadPoint/TopPoint/BottomPoint Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| shape | string | circle | No | Shape of the highlight point at the start/top/bottom of the line. |
| size | <length> | 5px | No | Size of the highlight point at the start/top/bottom of the line. |
| strokeWidth | <length> | 1px | No | Border width of the highlight point. |
| strokeColor | <color> | #ff0000 | No | Border color of the highlight point. |
| fillColor | <color> | #ff0000 | No | Fill color of the highlight point. |
| display | boolean | true | No | Whether to display the highlight point. |
Table 8: loop Definition
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| margin | <length> | 1 | No | Number of erasure points (horizontal distance between the most recently drawn point and the oldest). Note: When used together with topPoint/bottomPoint/headPoint, the point may fall in the erased area and become invisible, so using them simultaneously is not recommended. |
Events
Supports common events.
Methods
| Method | Parameters | Description |
|---|---|---|
| append | { serial: number, data: Array<number> } | Dynamically adds data to an existing data series. The target series is specified by serial, which is the index of the datasets array (starting from 0). Note: Does not update datasets[index].data. Only supported by line charts; the x‑coordinate increases by 1 (affected by xAxis min/max). |
Styles
Supports common styles.
input
Interactive components, including radio buttons, checkboxes, and buttons.
Subcomponents
Not supported.
Properties
Supports common properties.
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| type | string | button | No | Type of the input component. Optional values: button, checkbox, radio. Dynamic modification is not supported.• button: Defines a clickable button.• checkbox: Defines a checkbox.• radio: Defines a radio button, allowing selection of one option among multiple options with the same name value. |
| checked | boolean | false | No | Specifies whether the component is currently selected. |
| name | string | - | No | Name of the input component. |
| value | string | - | No | Value of the input component. Required when type is radio, and must be unique among options that share the same name value. |
Events
Supports common events.
When the input type is checkbox or radio, the following events are supported:
| Name | Parameters | Description |
|---|---|---|
| change | { checked: true | false } | Triggered when the checked state of the checkbox or radio button changes. |
Styles
Supports common styles +:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| color | <color> | #ffffff | No | Text color of the single-line input box or button. |
| font-size | <length> | 30px | No | Text size of the single-line input box or button. |
| width | <length> | - | No | Width of the component. Defaults to 100px when type is button. |
| height | <length> | - | No | Height of the component. Defaults to 50px when type is button. |
switch
Switch selector for enabling or disabling a function.
Subcomponents
Not supported.
Properties
Supports common properties.
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| checked | boolean | false | No | Specifies whether the switch is on. |
Events
Supports common events +:
| Name | Parameters | Description |
|---|---|---|
| change | { checked: checkedValue } | Triggered when the selected state of the switch changes. |
Styles
Supports common styles.
picker Embedded sliding selector for the page.
Subcomponents
Not supported.
Properties
Supports common properties.
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| type | string | text | No | Sets the type of the sliding selector. Optional values: text, time. • text: Text selector. • time: Time selector. |
Text Selector (type=text)
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| range | Array | - | No | Sets the value range of the text selector. Must use data binding, e.g. range="", and declare the corresponding variable in JS: data: ["15", "20", "25"]. |
| selected | string | 0 | No | Sets the default selected value of the text selector. The value must be the index (as a string) of range. |
Time Selector (type=time)
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| selected | string | 00:00 | No | Sets the default value of the time selector (format: HH:mm). |
Events
| Name | Parameters | Description |
|---|---|---|
| change | - When type=text: { newValue, newSelected }<br>- When type=time: { hour, minute } | Triggered after a value is selected. |
Styles
Supports common styles +:
| Name | Type | Default Value | Required | Description |
|---|---|---|---|---|
| color | <color> | #808080 | No | Font color of candidate items. |
| font-size | <length> | 30px | No | Font size of candidate items. |
| selected-color | <color> | #ffffff | No | Font color of the selected item. |
| selected-font-size | <length> | 38px | No | Font size of the selected item. |
Note: width and height must be set; otherwise, the component will not render.
Interfaces
Interface Overview
General Rules
Synchronous
After a synchronous method is called, subsequent operations can only continue after the method returns a result. The return value can be of any type.
Example:
var info = app.getInfo();
console.log(JSON.stringify(info));
Asynchronous
An asynchronous method call does not block the caller's work. After the business logic is executed, the callback function provided by the developer will be invoked.
Callback Functions Supported by Asynchronous Interfaces
| Callback Function | Parameter Name | Type | Return Value | Description |
|---|---|---|---|---|
| success | data | any | Optional | Triggered when execution is successful. The return value can be of any type (see the interface documentation for details). |
| fail | data / code | any / number | - | Triggered when execution fails. data is the error message (usually a string, but may be other types; see the interface documentation for details). code is the error code. |
| cancel | data | any | - | Triggered when the user cancels. Supported in some user interaction scenarios. |
| complete | - | - | - | Triggered when execution is completed, regardless of success or failure. |
Notes:
- Refer to the specific interface description to check whether the four callback functions (success, fail, cancel, complete) are supported.
- The success, fail, and cancel callbacks are mutually exclusive (only one will be triggered). Triggering any of them will invoke the complete callback again.
Example:
battery.getStatus({
success: function(data) {
console.log('success get battery level:' + data.level);
},
fail: function(data, code) {
console.log('fail to get battery level code:' + code);
},
});
Common Error Codes
| Code | Meaning |
|---|---|
| 200 | General error |
| 201 | User rejection |
| 202 | Invalid parameters |
| 203 | Service unavailable |
| 204 | Request timed out |
Application Context: app
Import Module
import app from '@system.app';
app.getInfo()
Gets the information declared in the current application configuration file.
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| appName | string | Name of the application. |
| versionName | string | Version name of the application. |
| versionCode | number | Version code of the application. |
Example
var info = app.getInfo();
console.log(JSON.stringify(info));
app.terminate()
Exits the current application. Example
app.terminate();
app.getOpenId(OBJECT)
Gets the app's openId (unique identifier).
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| appId | Number | Yes | The ID assigned to the app (must be applied for by developers). If you have previously applied for access to Qualcomm Spreadtrum and migrated the app, you can reuse the previously applied appId. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| openId | string | Unique ID for app payment. |
Example
app.getOpenId({
appId: 100,
success: data => {
console.log('success ' + data.openId);
}
});
app.getRealNameInfo()
Gets the real-name authentication age range.
Supported Device Versions: D3S/V1.5.0, Z6Pro/V2.7.0 Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| age | string | Age range: 0-3 years, 3-8 years, 8-12 years, 12-16 years, 16-18 years. |
Example
app.getRealNameInfo({
success: data => {
// data.age is the age range information
console.log('age info:' + data.age);
},
fail: (data, code) => {
// Failure may be due to uncompleted real-name authentication or internal interface access errors
}
});
Log Printing: console
Import Module
No import required.
Log Categories
Prints text information: console.debug|log|info|warn|error(message)
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| message | string | Yes | The text information to be printed. |
Example
console.log('log: I am log');
console.debug('debug: I am debug');
console.info('info: I am info');
console.warn('warn: I am warn');
console.error('error: I am error');
Note: console.log() prints debug-level log information, which is visible in the Logel tool.
Page Routing: router
Import Module
import router from '@system.router';
router.push(OBJECT)
Navigates to another page in the application.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the target page (the route name defined in manifest.json). |
| params | Object | No | Data to pass to the target page. After navigation, the parameters can be used directly in the target page (for example, this.name, where name is the key in params). |
params Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
PARAM_LAUNCH_FLAG (___PARAM_LAUNCH_FLAG___ in example) | string | No | Only supports "clearTask". When launching the target page, all other pages except this one will be cleared from the navigation stack. |
Example
Configuration in manifest.json:
"router": {
"entry": "home",
"pages": {
"home": {
"component": "index"
},
"about": {
"component": "index"
}
}
}
Navigate to the about component:
router.push({
uri: 'about',
params: {
name: 'hello world',
},
});
Navigate and clear other pages (returning will exit the app):
router.push({
uri: 'about',
params: {
___PARAM_LAUNCH_FLAG___: 'clearTask',
},
});
router.replace(OBJECT)
Navigates to another page in the application; the current page cannot be returned to.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the target page (the route name defined in manifest.json). |
| params | Object | No | Data to pass to the target page. After navigation, the parameters can be used directly in the target page (for example, this.name, where name is the key in params). The params fields are the same as above. |
Example
router.replace({
uri: 'about',
params: {
name: 'hello world',
},
});
router.back()
Returns to the specified page.
Example
router.back();
Application Configuration: configuration
Import Module
import configuration from '@system.configuration';
configuration.getLocale()
Gets the current language and region of the application (synchronized with the system by default).
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| language | string | Language (e.g., zh for Chinese). |
| countryOrRegion | string | Country or region (e.g., CN for China). |
Example
const localeInfo = configuration.getLocale();
console.info(localeInfo.language);
Timers
Import Module
No import required.
setTimeout(handler[, delay[, ...args]])
Sets a timer that executes a function after the timer expires.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| handler | Function | Yes | The function to execute when the timer expires. |
| delay | number | No | The number of milliseconds to delay before calling handler. If omitted, defaults to 0 (i.e., as soon as possible). |
| ...args | Array | No | Additional parameters passed to handler when the timer expires. |
Return Value
timeoutID: The ID of the timer.
Example
var timeoutID = setTimeout(function() {
console.log('delay 1s');
}, 1000);
clearTimeout(timeoutID)
Cancels a timer previously established with setTimeout().
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| timeoutID | number | Yes | The ID of the timer to cancel (returned by setTimeout()). |
Example
clearTimeout(timeoutID);
setInterval(handler[, delay[, ...args]])
Repeatedly calls a function with a fixed time delay between calls. The interval must be 3 seconds or longer.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| handler | Function | Yes | The function to execute when the timer expires. |
| delay | number | No | The number of milliseconds to delay before calling handler. If omitted, defaults to 0 (i.e., as soon as possible). |
| ...args | Array | No | Additional parameters passed to handler when the timer expires. |
Return Value
intervalID: The ID of the repeating timer. Example
var intervalID = setInterval(function() {
console.log('execute every 1s.');
}, 5000); // The interval must be 3000ms or longer; otherwise, system errors may occur.
clearInterval(intervalID)
Cancels a repeating timer previously established with setInterval().
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| intervalID | number | Yes | The ID of the repeating timer to cancel (returned by setInterval()). |
Example
clearInterval(intervalID);
Pop-up Window: prompt
Import Module
import prompt from '@system.prompt';
prompt.showToast(OBJECT)
Displays a Toast.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| message | string | Yes | The text information to display. |
| duration | number | No | 0 for short duration, 1 for long duration (defaults to 0). |
Example
prompt.showToast({
message: 'Hello World'
});
Upload/Download: request
Import Module
import request from '@system.request';
request.upload(OBJECT)
Uploads files.
Parameters
| Parameter Name | Type | Required | Description |
|----------------|------------------|----------|----------------------------------------------------------------------------------------------|
| url | string | Yes | Resource address. |
| header | Object | No | Request headers. |
| method | string | No | Request method: `POST`, `PUT` (defaults to `POST`). |
| files | Array\<File> | Yes | List of files to upload. Must be submitted using `multipart/form-data`. |
| data | Array<RequestData> | No | Form data for the request. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
**Table 2: File**
| Parameter Name | Type | Required | Description |
|----------------|--------|----------|----------------------------------------------------------------------------------------------------------------------------------|
| filename | string | No | The filename in the request header when submitting via multipart. |
| name | string | No | The name of the form item when submitting via multipart (defaults to `file`). |
| uri | string | Yes | The local storage path of the file (see the storage directory definition for details on how to construct/use this path). |
| type | string | No | The content type (MIME type) of the file. Defaults to the type inferred from the file name or path extension if not specified. |
Table 3: RequestData
| Parameter Name | Type | Required | Description |
|----------------|--------|----------|--------------------------------|
| name | string | Yes | The name of the form element. |
| value | string | Yes | The value of the form element.|
**Success Return Value:**
| Parameter Name | Type | Description |
|----------------|--------|----------------------------------------------------------------------------------------------|
| code | number | The status code returned by the server. |
| data | string | The content returned by the server (its actual type depends on the `Content-Type` header). |
| headers | Object | The response headers returned by the server. |
Example
```javascript
request.upload({
url: 'http://www.example.com',
files: [
{
uri: 'internal://xxx/xxx/test',
name: 'file1',
filename: 'test.png'
}
],
data: [
{
name: 'param1',
value: 'value1'
}
],
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
request.download(OBJECT)
Downloads files.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| url | string | Yes | Resource address. |
| requestId | string | No | Custom request ID (used to abort the download). |
| header | Object | No | Request headers. |
| description | string | No | Description of the download (defaults to the file name). |
| filename | string | No | The name and path of the downloaded file (defaults to the value derived from the request or resource address). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| token | string | The token for the download (used to check download status). |
Example
request.download({
url: 'http://www.example.com',
filename: "internal://cache/imgs/1.png",
success: function(data) {
console.log(`handling success${data.token}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
request.onDownloadComplete(OBJECT)
Listens for download tasks.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| token | string | Yes | The token returned by the download interface. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| uri | string | The URI of the downloaded file. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 1000 | Download failed |
| 1001 | Download task does not exist |
Example
request.onDownloadComplete({
token: '123',
success: function(data) {
console.log(`handling success${data.uri}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
Complete Download Example
request.download({
url: 'http://www.example.com', // Path of the resource to download
filename: "internal://cache/imgs/1.png", // Path to save the downloaded file (stored in the `cache/imgs` directory with the name `1.png`)
success: data => {
console.log(`download success`);
request.onDownloadComplete({
token: data.token,
success: () => {
console.log(`onDownloadComplete success`);
},
fail: (data, code) => {
console.log(`onDownloadComplete fail code = ${code}`);
}
});
},
fail: (data, code) => {
console.log(`download fail, code = ${code}`);
}
});
request.cancel(OBJECT)
Cancels a download task.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| requestId | String | Yes | The request ID passed to the download interface. |
Data Request: fetch
Import Module
import fetch from '@system.fetch';
fetch.fetch(OBJECT)
Gets network data.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| url | String | Yes | Resource URL. If the URL contains Chinese characters, encode it with encodeURI. |
| data | String | No | Request parameters (in JSON string format). |
| header | Object | No | Request headers (all properties are set to the request headers). |
| method | String | No | HTTP method, defaults to GET. Optional values: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT (must be uppercase). |
| responseType | String | No | The return type is determined by the Content-Type in the server response header. Supports text and json formats (see the success return value for details). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution (may fail due to permission issues). |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| code | number | The status code returned by the server. |
| data | String/Object | The return data; its type is determined by responseType. |
| headers | Object | All response headers returned by the server. |
Relationship Between responseType and data in Success Return Value
| responseType | data Type | Description |
|---|---|---|
| None | String | If the type in the server response header is text/*, application/json, application/javascript, or application/xml, the value is the text content. |
| text | String | Returns plain text. |
| json | Object | Returns a JSON-formatted object. |
Example
fetch.fetch({
url: 'https://www.demo.com',
method: 'POST',
responseType: 'text',
data: '{"id":1}',
success: function(response) {
console.log('response code:' + response.code);
console.log('response data:' + response.data);
},
fail: function(data, code) {
console.log('fail callback');
},
});
Data Storage: storage
Import Module
import storage from '@system.storage';
storage.get(OBJECT) Reads stored content.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| key | string | Yes | Content index. The string can be up to 32 characters long and cannot contain special characters such as /, *, +, ,, :, ;, <, =, >, ?, [, ], \, or \x7F. |
| default | string | No | Default value returned if the key does not exist. If not specified, an empty string (length 0) is returned. |
| success | Function | No | Callback for successful execution (returns the stored content). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Example
storage.get({
key: 'A1',
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
storage.set(OBJECT)
Modifies stored content.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| key | string | Yes | Content index. The string can be up to 32 characters long and cannot contain special characters such as /, *, +, ,, :, ;, <, =, >, ?, [, ], \, or \x7F. |
| value | String | No | New value. If the new value is an empty string (length 0), the data item indexed by key will be deleted. The string can be up to 128 characters long. For storing large amounts of data, use the file interface (file). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Example
storage.set({
key: 'A1',
value: 'V1',
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
storage.clear(OBJECT)
Clears all stored content.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Example
storage.clear({
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
storage.delete(OBJECT)
Deletes specific stored content.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| key | string | Yes | Content index. The string can be up to 32 characters long and cannot contain special characters such as /, *, +, ,, :, ;, <, =, >, ?, [, ], , or \x7F. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Example
storage.delete({
key: 'A1',
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
File Storage: file
Import Module
import file from '@system.file';
The URI string of a file or directory can be up to 128 characters long and cannot contain special characters such as ", *, +, ,, :, ;, <, =, >, ?, [, ], , or \x7F.
file.move(OBJECT)
Moves a specified file to another location.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| srcUri | string | Yes | URI of the file to move. |
| dstUri | string | Yes | URI of the target location for the file. |
| success | Function | No | Callback for successful execution (returns the URI of the target location). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (called regardless of success or failure). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.move({
srcUri: 'internal://cache/path/to/file',
dstUri: 'internal://files/path/to/file',
success: function(uri) {
console.log(`move success: ${uri}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.copy(OBJECT)
Copies a specified file to a target location.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| srcUri | string | Yes | URI of the file to copy. |
| dstUri | string | Yes | URI of the target location for the copied file. |
| success | Function | No | Callback for successful execution (returns the URI of the target location). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (called regardless of success or failure). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.copy({
srcUri: 'internal://cache/path/to/file',
dstUri: 'internal://files/path/to/file',
success: function(uri) {
console.log(`copy success: ${uri}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.list(OBJECT)
Gets a list of all files in a specified path.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the directory. |
| success | Function | No | Callback for successful execution (returns the list of files). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| fileList | Array | The list of files obtained. |
Table 1: FileInfo
| Parameter Name | Type | Description |
|---|---|---|
| uri | string | URI of the file. |
| lastModifiedTime | number | Timestamp of the last file save (seconds since 1970/01/01 00:00:00 GMT). |
| length | number | File size in bytes. |
| type | string | File type. Possible values: dir (Directory), file (File). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
file.get(OBJECT)
Gets information about a specified local file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the file to copy. |
| recursive | boolean | No | Specifies whether to recursively get the list of files in subdirectories (defaults to false). |
| success | Function | No | Callback for successful execution (returns the URI of the target location). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| uri | string | URI of the file. |
| lastModifiedTime | number | Timestamp of the last file save (seconds since 1970/01/01 00:00:00 GMT). |
| length | number | File size (in bytes). Fixed to 0 if type is dir. |
| type | string | File type. Optional values:- dir: Directory;- file: File. |
| subFiles | Array | List of files (in subdirectories if recursive is true). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.get({
uri: 'internal://files/path/to/file',
success: function(data) {
console.log(data.uri);
console.log(data.length);
console.log(data.lastModifiedTime);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.delete(OBJECT)
Deletes a local file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the file to delete. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.delete({
uri: 'internal://files/path/to/file',
success: function(data) {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.writeText(OBJECT)
Writes text content to a specified file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the local file (the file will be created if it does not exist). |
| text | string | Yes | The string to write. |
| encoding | string | No | Encoding format (defaults to UTF-8). |
| append | boolean | No | Specifies whether to use append mode (defaults to false). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.writeText({
uri: 'internal://files/work/demo.txt',
text: 'test',
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.writeArrayBuffer(OBJECT)
Writes Buffer content to a specified file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the local file (the file will be created if it does not exist). |
| buffer | Uint8Array | Yes | The Buffer to write. |
| position | number | No | Offset of the position to start writing (defaults to 0). |
| append | boolean | No | Specifies whether to use append mode (defaults to false). The position parameter is ignored if append is true. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.writeArrayBuffer({
uri: 'internal://files/work/demo',
buffer: buffer,
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.readText(OBJECT)
Reads text content from a specified file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the local file. |
| encoding | string | No | Encoding format (defaults to UTF-8). |
| position | number | No | Start position for reading (defaults to the start of the file). |
| length | number | No | Length of content to read (defaults to 4096). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| text | string | The read text content. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.readText({
uri: 'internal://files/work/demo.txt',
success: function(data) {
console.log('text: ' + data.text);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.readArrayBuffer(OBJECT)
Reads Buffer content from a specified file.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the local file. |
| position | number | No | Start position for reading (defaults to the start of the file). |
| length | number | No | Length of content to read (defaults to the end of the file). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| buffer | Uint8Array | The read file content (as Buffer). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.readArrayBuffer({
uri: 'internal://files/work/demo',
position: 100,
length: 100,
success: function(data) {
console.log('buffer.length: ' + data.buffer.length);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.access(OBJECT)
Checks whether a specified file or directory exists.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI of the directory or file. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.access({
uri: 'internal://files/test',
success: function(data) {
console.log(`handling success`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.mkdir(OBJECT)
Creates a specified directory (cannot be used to create files).
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI path of the directory. |
| recursive | boolean | No | Specifies whether to recursively create parent directories (defaults to false). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.mkdir({
uri: 'internal://files/dir',
success: function(data) {
console.log(`handling success`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
file.rmdir(OBJECT)
Deletes a specified directory.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | URI path of the directory. |
| recursive | boolean | No | Specifies whether to recursively delete subdirectories and files in the directory (defaults to false). false means only empty directories can be deleted. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 202 | Invalid parameters |
| 300 | I/O error |
| 301 | File or directory does not exist |
Example
file.rmdir({
uri: 'internal://cache',
success: function(data) {
console.log(`handling success`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
Geolocation: geolocation
Import Module
import geolocation from '@system.geolocation';
geolocation.getLocation(OBJECT)
Gets the device's geolocation.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| timeout | number | No | Timeout in milliseconds (defaults to 180000). Timeout is set to prevent request blocking due to system permission rejection, weak positioning signals, or incorrect positioning settings. The fail callback is triggered after timeout. The value must be a 32-bit positive integer. If the value is ≤ 0, the system uses the default value. |
| coordType | string | No | Coordinate system type (optional values can be obtained via getSupportedCoordTypes; defaults to wgs84). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution (regardless of success or failure). |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| longitude | number | Device location: longitude. |
| latitude | number | Device location: latitude. |
| accuracy | number | Device location: accuracy. |
| time | number | Device location: timestamp. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 201 | User rejected; failed to obtain location permission |
| 204 | Timeout returned |
Example
geolocation.getLocation({
success: function(data) {
console.log(
`handling success: longitude = ${data.longitude}, latitude = ${
data.latitude
}`
);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
geolocation.getSupportedCoordTypes() Gets the coordinate system types supported by the device.
Return Value
An array of strings representing coordinate system types (e.g., [wgs84, gcj02]).
Example
var types = geolocation.getSupportedCoordTypes();
Network Status: network
Import Module
import network from '@system.network';
network.getType(OBJECT)
Gets the network type.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution (returns the network type). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| type | string | Network type. Possible values: 2g, 3g, 4g, wifi, none. |
| metered | boolean | Specifies whether the network is metered (pay-as-you-go). |
Example
network.getType({
success: function(data) {
console.log(`handling success: ${data.type}`);
}
});
Device Information: device
Import Module
import device from '@system.device';
device.getInfo(OBJECT) Gets information about the current device.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| brand | string | Device brand. |
| manufacturer | string | Device manufacturer. |
| model | string | Certified device model. |
| externalModel | string | Marketed device model. |
| product | string | Device code name. |
| language | string | System language. |
| region | string | System region. |
| windowWidth | number | Usable window width. |
| windowHeight | number | Usable window height. |
Fail Error Codes
| Error Code | Description |
|---|---|
| 200 | Some information in the return result cannot be obtained. |
Example
device.getInfo({
success: function(ret) {
console.log(`handling success, brand = ${ret.brand}`);
}
});
Screen Brightness: brightness
Import Module
import brightness from '@system.brightness';
brightness.getValue(OBJECT)
Gets the current screen brightness of the device.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution (returns the screen brightness). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| value | number | Screen brightness (integer between 1 and 255). |
Example
brightness.getValue({
success: function(data) {
console.log(`handling success, value = ${data.value}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
brightness.setValue(OBJECT)
Sets the current screen brightness of the device.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| value | number | Yes | Screen brightness (integer between 1 and 255). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Example
brightness.setValue({
value: 100,
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
brightness.setKeepScreenOn(OBJECT)
Sets whether to keep the screen on.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| keepScreenOn | boolean | Yes | Specifies whether to keep the screen on. |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Example
brightness.setKeepScreenOn({
keepScreenOn: true,
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
System Volume: volume
Import Module
import volume from '@system.volume';
volume.getMediaValue(OBJECT)
Gets the current media volume.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution (returns the media volume). |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| value | number | Current system media volume. There are 5 volume levels: 0, 0.4, 0.6, 0.8, 1. |
Example
volume.getMediaValue({
success: function(data) {
console.log(`handling success: ${data.value}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
volume.setMediaValue(OBJECT)
Sets the current media volume.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| value | Number | Yes | Volume to set. There are 5 volume levels: 0, 0.4, 0.6, 0.8, 1. |
| success | Function | No | Callback for successful execution. |
| fail | Function | Yes | Callback for failed execution. A pop-up prompt may appear when increasing the volume while a Bluetooth headset is connected; clicking “Cancel” triggers this callback, and the volume remains unchanged. |
| complete | Function | No | Callback for completed execution. |
Example
volume.setMediaValue({
value: 0.8,
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
Battery Information: battery
Import Module
import battery from '@system.battery';
battery.getStatus(OBJECT)
Gets the current charging status and remaining battery level of the device.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| charging | boolean | Specifies whether the battery is charging. |
| level | number | Remaining battery level (range: 0.00 - 1.00). |
Example
battery.getStatus({
success: function(data) {
console.log('success get battery level:' + data.level);
},
fail: function(data, code) {
console.log('fail to get battery level code:' + code + ', data: ' + data);
},
});
record.start(OBJECT)
import record from '@system.record';
record.start(OBJECT)
Starts audio recording.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| duration | Number | No | Recording duration in milliseconds. If duration is a valid value, recording stops when the duration is reached. |
| sampleRate | Number | No | Sample rate. The supported sample rate range varies by audio format. |
| numberOfChannels | Number | No | Number of recording channels (valid values: 1/2). |
| encodeBitRate | Number | No | Encoding bit rate. The value depends on the sample rate and audio format. |
| format | String | No | Audio format (only amr is supported). |
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| uri | String | Storage path of the recording file (in the app's cache directory). |
Fail Error Codes
| Error Code | Description |
|---|---|
| 201 | User rejected; failed to obtain recording permission |
Example
record.start({
duration: 10000,
sampleRate: 8000,
numberOfChannels: 1,
encodeBitRate: 16000,
format: 'amr',
success: function(data) {
console.log(`handling success: ${data.uri}`);
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
record.stop(OBJECT) Stops audio recording.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Example
record.stop({
success: function() {
console.log('handling success');
},
fail: function(data, code) {
console.log(`handling fail, code = ${code}`);
}
});
Audio Playback: audio
Import Module
import audio from '@system.audio';
Properties
| Name | Parameter Type | Readable | Writable | Required | Description |
|---|---|---|---|---|---|
| src | String | Yes | Yes | Yes | URI of the audio media to play. |
| currentTime | Number | Yes | Yes | No | Current playback progress of the audio (in seconds). Setting this value adjusts the playback progress. |
| duration | Number | Yes | No | No | Total playback duration of the audio (in seconds). Returns NaN if unknown. |
| autoplay | Boolean | Yes | Yes | No | Specifies whether to play the audio automatically (defaults to false). |
| loop | Boolean | Yes | Yes | No | Specifies whether to play the audio in a loop (defaults to false). |
| volume | Number | Yes | Yes | No | Audio volume (defaults to the current system media volume). Range: [0.0, 1.0]. |
| muted | Boolean | Yes | Yes | No | Specifies whether to mute the audio (defaults to false). |
Example
audio.src = './hello.mp3';
Note: Currently, other properties cannot be accessed or set via audio.propertyName. Support will be added in future versions.
Methods
audio.play()
Starts audio playback.
Example
audio.src = './hello.mp3';
audio.play();
audio.pause()
Pauses audio playback.
Example
audio.pause();
audio.stop()
Stops audio playback. Playback can be resumed via play().
Example
audio.stop();
audio.getPlayState(OBJECT)
Gets the current playback state data.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Callback for successful execution. |
| fail | Function | No | Callback for failed execution. |
| complete | Function | No | Callback for completed execution. |
Success Return Value
| Parameter Name | Type | Description |
|---|---|---|
| state | String | Playback state: 'play', 'pause', 'stop'. |
| src | String | URI of the currently playing audio media (empty string when stopped). |
| currentTime | Number | Current playback progress of the audio (in seconds; -1 when stopped). |
| autoplay | Boolean | Specifies whether the audio is playing automatically. |
| loop | Boolean | Specifies whether the audio is playing in a loop. |
| volume | Number | Audio volume (defaults to the current system media volume). Range: [0.0, 1.0]. |
| muted | Boolean | Specifies whether the audio is muted. |
Example
audio.getPlayState({
success: function(data) {
console.log(`handling success: state: ${data.state},src:${ data.src },currentTime:${data.currentTime},
autoplay:${data.autoplay},loop:${ data.loop },volume: ${data.volume},muted:${data.muted}`)
},
fail: function(data, code) {
console.log('handling fail, code=' + code)
}
})
Events
| Name | Description |
|---|---|
| play | Callback event when the play method is called or autoplay is true. |
| pause | Callback event after the pause method is called. |
| stop | Callback event after the stop method is called. |
| loadeddata | Callback event when audio data is obtained for the first time. |
| ended | Callback event when playback ends. |
| durationchange | Callback event when the playback duration changes. |
| error | Callback event when a playback error occurs. |
| timeupdate | Triggered when the playback progress changes; can be used to implement a progress bar. |
Example
audio.onplay = ()=>{
console.log('playing');
}
audio.ontimeupdate = data => {
console.log(data.currentTime)
}
Multimedia: media
Import Module
import media from '@system.media';
media.pickImage(OBJECT) Select an image.
Parameters
| Parameter Name | Type | Required | Description |
|---|---|---|---|
| success | Function | No | Success callback. |
| fail | Function | No | Failure callback. |
Return Value
| Parameter Name | Type | Description |
|---|---|---|
| uri | string | Path of the selected file. |
| name | string | Name of the selected file. |
| size | number | Size of the selected file, in bytes (B). |
Example
media.pickImage({
success: (data) => {
console.log(`handling success: ${data.uri}`)
},
fail: (data, code) => {
console.log(`handling fail, code = ${code}`)
}
})
Vibration: vibrator
Import Module
import vibrator from '@system.vibrator';
vibrator.vibrate(OBJECT)
Trigger device vibration.
Parameters: None
Example
vibrator.vibrate();
Input Method: input
Import Module
import input from '@system.input';
input.openInputMethod(OBJECT)
Text Customization
Example Code
input.openInputMethod({
inputText: 'test input', // Text in the input area
confirmText: 'Search', // Button text
maxLength: 33,
success: (res) => {
console.log('input success:' + res.outputText);
},
fail: (err, code) => {
console.log('input failed' + err + " code:" + code);
}
});