APIs
General Rules
Synchronous
When a synchronous method is called, the caller can continue follow-up actions only after the execution result is returned. The return value can be of any type.
- Example
var info = app.getInfo();
console.log(JSON.stringify(info));
Asynchronous
The whole calling process of a asynchronous method does not impede the actions of the caller. After the business is implemented, the caller calls a callback function provided by the developer.
- Callback functions supported by asynchronous APIs
:::Tip
To check whether a specific API supports the following four callback functions, success, fail, cancel, and complete, see the corresponding API specification.
Three callback functions, success, fail, and cancel, are mutual exclusive. Only one of them will be triggered at a time. And the complete callback will be called again when any of the previous three callback functions is triggered. :::
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);
},
});
Subscription
A subscription API does not return an immediate result. Developers need to set a corresponding callback function in parameters. This callback function is called upon task completion or event change. The callback function can be executed for multiple times.
Subscription APIs support the following callback functions.
Take the geolocation API as example.
geolocation.subscribe({
success: function (data) {
console.log("get location. latitude:" + data.latitude);
},
fail: function (data, code) {
console.log("fail to get location. code:" + code);
},
});
Common Error Codes
This section provides common error codes.
Among these error codes, code 200 is a common system error code, which is reported upon occurrence of an unknown exception. For example, the framework fails to request for memory space.
code | Meaning |
---|---|
200 | Common error |
202 | Parameter error |
300 | I/O error |
Basic Functions
Application Context
Imported Module
import app from "@system.app";
app.getInfo()
Gets the declaration information in the configuration file of the current application.
Parameter
None
Return value
Parameter Name Type Description appName string Indicates the application name. versionName string Indicates the version name of the application. versionCode number Indicates the version number of the application. Example
var info = app.getInfo();
console.log(JSON.stringify(info));
app.terminate()
Exits the current Ability.
Parameter
None
Example
app.terminate();
Log Print
Imported Module
No import required.
Log Classify
Prints a text message, console.debug|log|info|warn|error(message).
Parameter
Parameter Name Type Required Description message string Yes Indicates the test message to be printed. Example
var versionCode = 1;
console.info("Hello World. The current version code is " + versionCode);
The message printed by console.log() contains debug-level log information.
Page Route
Imported Module
import router from "@system.router";
router.replace(OBJECT)
Replaces the current page with another page in the application and then destroys the replaced page.
Parameter
Parameter Name Type Required Description uri string Yes Uniform Resource Identifier (URI) of the target page, which can be specified in either of the following two formats: An absolute page path provided by the pages list in the configuration file, for example, pages/index/indexpages/detail/detail, or a special value. If the URI value is "/", the application jumps to the homepage. params Object No The data to be transfered to the target page during the jumping process. After the application jumps to the target page, the parameters can be used directly on the page. For example, this.data1, where data1 is the value of key in params during the jumping process. If this field already exists on the target page, the existing field value will be overwritten with the passed in value. Example
// On the current page
export default {
replacePage() {
router.replace({
uri: "pages/detail/detail",
params: {
data1: "message",
},
});
},
};
// On the detail page
export default {
data: {
data1: "default",
},
onInit() {
console.info("showData1:" + this.data1);
},
};
Application Configuration
Imported Module
import configuration from "@system.configuration";
configuration.getLocale()
Gets the current language and region of an application. The configuration is synchronized with the system language and region by default.
Return value
Parameter Name Type Description language string Language. For example, zh. countryOrRegion string Country or region. For example, CN. dir string Test direction. Value range: ltr: left to right; rtl: right to left. Example
const localeInfo = configuration.getLocale();
console.info(localeInfo.language);
Timer
Support Devices
Table 1 Devices Supporting APIs
API | Lightweight smart wearables |
---|---|
setTimeout | Support |
clearTimeout | Support |
setInterval | Support |
clearInterval | Support |
Imported Module
No import required.
Permission List
None
setTimeout(handler[, delay[, ...args]])
Sets a timer. This timer executes a function upon expiration.
Parameter
Parameter Name Type Required Description handler Function Yes The function to be executed upon expiration of the timer. delay number No A delay in milliseconds. The function is called after the delay. If this parameter is not set, the default delay value 0 is used, which means immediate execution or execution as soon as possible. ...args Array <any>
No Additional arguments, which will be transferred to handler as parameters once the time expires. Return value
ID of the timer timeoutID
Example
var timeoutID = setTimeout(function () {
console.log("delay 1s");
}, 1000);
clearTimeout(timeoutID)
Cancels the timer previously created by calling setTimeout().
Parameter
Parameter Name Type Required Description timeoutID number Yes ID of the timer to be removed, which is returned by setTimeout(). Example
var timeoutID = setTimeout(function () {
console.log("do after 1s delay.");
}, 1000);
clearTimeout(timeoutID);
setInterval(handler[, delay[, ...args]])
Sets a fixed interval between calls when a function is called repeatedly.
Parameter
Parameter Name Type Required Description handler Function Yes The function to be called repeatedly. delay number No A delay in milliseconds. One second equals to 1000 milliseconds. The function is called repeatedly at an interval of the delay time. ...args Array <any>
No Additional arguments, which will be transferred to handler as parameters once the time expires. Return value
ID of the repeat timer intervalID
Example
var intervalID = setInterval(function () {
console.log("do very 1s.");
}, 1000);
clearInterval(intervalID)
Removes the scheduled repeating task previously set by setInterval().
Parameter
Parameter Name Type Required Description intervalID number Yes ID of the repeat timer to be removed, which is returned by setInterval().
- Example
var intervalID = setInterval(function () {
console.log("do very 1s.");
}, 1000);
clearInterval(intervalID);
Page Route
API Declaration
Declaration not required
Imported Module
import router from '@system.router' or const router = require('@system.router')
API Definition
router.push(OBJECT)
Jumps to a page in the application.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
uri | String | Yes | URI of the target page. The URI can be specified in one of the following formats: A complete URI containing a schema. The supported schemas include tel, sms, and mailto, for example, tel:10086. Path of a page in the application, which starts with ‘/’, for example, /about. The path of a page in the application, which does not start with ‘/’, for example, About. A special value. If the URI value is "/", the application jumps to the page whose path is "/". If no value is set, the application jumps to the homepage that supports a complete URI containing a schema. The following describes how to process a URI with a schema: query the filter settings of all pages in the app and then select an appropriate page to process the request (for details, see the manifest file). If no page is appropriate for request processing, the default strategy will be used to process the request. The default strategy supports the processing of HTTP, HTTPS, and internal schemas. If the default strategy fails to process a request too, a system application will attempt to process the request. If no system application can process the request, the request will be discarded. The default strategy uses the following logic for request processing: For an HTTP or HTTPS schema, an internal web browser is used to open the page. For an internal schema (see File Organization), a corresponding application in the system is called to open the file, whose type is determined by the file extension in the URI. For a HAP schema (see the HAP link), a page supported by the HAP link will be opened. |
Example:
- Page switch in application
- Switch by path
router.push({ uri: "/about", params: { testId: "1", }, });
- Switch by name
// open page by name router.push({ uri: "About", params: { testId: "1", }, });
- Switch by path
- Open another quick application
router.push({
uri: "hap://app/com.example.quickapp/page?key=value",
});
router.replace(OBJECT)
Jumps to a page within the application with the current page inaccessible.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
uri | String | Yes | URI of the target page. The URI can be specified in one of the following formats: The path of a page in the application, which starts with "/", for example, /about. Name of a page in the application, which does not start with "/", for example, About. A special value. If the value is "/", the application jumps to the page with the path "/”. If no value is set, the application jumps to the homepage. |
params | Object | No | The parameters to be transferred during the jumping process. These parameters can be used on the target page through this.param1, where param1 is the parameter name in JSON. The value of param1 will be converted into String type. When using the this.param1 variable, you are required to define the property with the same key name in public (transfer parameter outside the application) or protected (transfer parameter inside the application) for the target page. |
Example:
router.replace({
uri: "/test",
params: {
testId: "1",
},
});
router.back(OBJECT)
Returns to a specific page.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
path | String | No | Path of the target page. The following values are optional: If this parameter is not set, the application returns to the previous page, which is an open page in the application and has a path starting with "/”, for example, /about. A special value. If the path value is “/”, the application jumps to the page with a name of “/”. If no page has the name, the application jumps to the homepage. Note: The path must be set to the path of an open page in the current application, whose name starts with "/”. Or else, the path parameter is invalid and the application returns to the previous page. If no open page matches the path parameter, the application returns to the previous page. If multiple pages match the path parameter, the application returns to the last page opened. |
Example:
// Page A, open page by name
router.push({
uri: "B",
});
// Page B, open page by name
router.push({
uri: "C",
});
// Page C, open page by name
router.push({
uri: "D",
});
// Page D, open page by name
router.push({
uri: "E",
});
// Page E is not set to the path and it returns to page D
router.back();
// Page D is not set to the path name and it returns to page C
router.back();
// Page C is set to the path and it returns to page A
router.back({
path: "/A",
});
router.clear()
Clears the historical record of pages expect the current page.
Parameters:
None
Example:
router.clear();
router.getLength()
Gets the number of pages in the current page stack.
Return value:
Type | Description |
---|---|
Number | Number of pages |
Example:
var length = router.getLength();
console.log(`page's length = ${length}`);
router.getState()
Gets the state of the current page.
Return parameters:
Parameter Name | Type | Description |
---|---|---|
index | Number | Location of the current page in the page stack. |
name | String | Name of the current page |
path | String | Path of the current page |
Example:
var page = router.getState();
console.log(`page index = ${page.index}`);
console.log(`page name = ${page.name}`);
console.log(`page path = ${page.path}`);
router.getPages()
Gets the list of the current page stack.
Return value:
Type | Description |
---|---|
Array | List of the page stack. Each element in the array is of the Object type. |
Each element in the array consists of:
Field | Type | Description |
---|---|---|
name | String | Page name |
path | String | Page path |
Example:
var stacks = router.getPages();
console.log("name of page at the bottom of stacks: ", stacks[0].name); // e.g. list, detail and so on
console.log("path of page at the bottom of stacks: ", stacks[0].path); // e.g. /list, /detail, /home/preview
File Data
Data Storage
Imported Module
import storage from "@system.storage";
storage.get(OBJECT)
Reads stored contents.
Parameter
Parameter Name Type Required Description key string Yes Content index. The maximum length of the string is 32. Special characters such as “/"*+,:;<=>?[] | \x7F” are not allowed in the string. default string No If key does not exist, the default value is returned. If no default value is specified, an empty string with the length of 0 is returned. success Function No Callback function after a successful API call, which is used to return the stored contents. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Example
storage.get({
key: "storage_key",
success: function (data) {
console.log("call storage.get success: " + data);
},
fail: function (data, code) {
console.log("call storage.get fail, code: " + code + ", data: " + data);
},
complete: function () {
console.log("call complete");
},
});
storage.set(OBJECT)
Modifies stored contents.
Parameter
Parameter Name Type Required Description key string Yes Index of the stored content to be modified. The maximum length of the string is 32. Special characters such as “/"*+,:;<=>?[] | \x7F” are not allowed in the string. value string No New value. The maximum length is 128. If the value is an empty string with the length of 0, the data entry with the index specified by key is deleted. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Example
storage.set({
key: "storage_key",
value: "storage value",
success: function () {
console.log("call storage.set success.");
},
fail: function (data, code) {
console.log("call storage.set fail, code: " + code + ", data: " + data);
},
});
storage.clear(OBJECT)
Clears stored contents.
Parameter
Parameter Name Type Required Description success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Example
storage.clear({
success: function () {
console.log("call storage.clear success.");
},
fail: function (data, code) {
console.log("call storage.clear fail, code: " + code + ", data: " + data);
},
});
storage.delete(OBJECT)
Deletes stored contents.
Parameter
Parameter Name Type Required Description key string Yes Content index. The maximum length of the string is 32. Special characters such as “/"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Example
storage.delete({
key: "Storage1",
success: function () {
console.log("call storage.delete success.");
},
fail: function (data, code) {
console.log("call storage.delete fail, code: " + code + ", data: " + data);
},
});
File Storage
Imported Module
import file from "@system.file";
file.move(OBJECT)
Moves a specific file to another location.
Parameter
Parameter Name Type Required Description srcUri string Yes URI of the file to be moved. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. dstUri string Yes The URI of the location where the file will be moved to. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. This function returns the URI of the location where the file will be moved to. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.move({
srcUri: "internal://app/myfiles1",
dstUri: "internal://app/myfiles2",
success: function (uri) {
console.log("call success callback success");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.copy(OBJECT)
Copies a specific file to a specified location for storage.For the specification of URIs used by the API, see File Organization.
Parameter
Parameter Name Type Required Description srcUri string Yes URI of the file to be copied. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. dstUri string Yes URI of the location where the file will be copied to. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. This function returns the URI of the location where the file will be copied to. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.copy({
srcUri: "internal://app/file.txt",
dstUri: "internal://app/file_copy.txt",
success: function (uri) {
console.log("call success callback success");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.list(OBJECT)
Gets a list of all files in a specific path. For the specification of URIs used by the API, see File Organization.
Parameter
Parameter Name Type Required Description uri string Yes Directory URI. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Return values of success:
Parameter Name Type Description fileList Array <FileInfo>
The obtained file list, in which the information of each file is displayed in the following format: { uri:'file1', lastModifiedTime:1589965924479, length:10240, type: 'file' } Table 1 FileInfo
Parameter Name Type Description uri string File URI. lastModifiedTime number The last file storage timestamp, displayed as the number of millisecond from 1970/01/01 00:00:00 GMT to the current time. A fixed value 0 is returned due to the restriction of the underlying file system. length number File size in the unit of bytes. The length has a fixed value 0 when the file type is dir. type string File type. The optional values are: dir: directory; file: file.
Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.list({
uri: "internal://app/pic",
success: function (data) {
console.log(data.fileList);
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.get(OBJECT)
Gets the information of a specific local file. For the specification of URIs used by the API, see File Organization.
Parameter
Parameter Name Type Required Description uri string Yes File URI. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. recursive boolean No Indicates whether to get a recursive list of files in subdirectories. The default is false. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete.
Return values of success:
Parameter Name Type Description uri string File URI. length number File size in bytes. The length has a fixed value 0 when the file type is dir. lastModifiedTime number File storage timestamp, which is displayed as the number of milliseconds from 1970/01/01 00:00:00 to the current time. A fixed value 0 is returned due to the restriction of the underlying file system. type string File type. The optional values are: dir: directory; file: file. subFiles Array A list of files.
Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.get({
uri: "internal://app/file",
success: function (data) {
console.log(data.uri);
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.delete(OBJECT)
Deletes a local file. For the information of URIs used by the API, see File Organization.
Parameter
Parameter Name Type Required Description uri string Yes URI of the file to be deleted. A resource path of the application is not allowed. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.delete({
uri: "internal://app/my_file",
success: function () {
console.log("call delete success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.writeText(OBJECT)
Writes texts to a specific file.
Parameter
Parameter Name Type Required Description uri string Yes URI of a local file. If the local file does not exist, a file will be created. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. text string Yes A written string. encoding string No Encoding format. The default is UTF-8. Only UTF-8 is supported now. append boolean No Indicates whether the append mode is used. The default is false. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.writeText({
uri: "internal://app/workspace/test.txt",
text: "Text that just for test.",
success: function () {
console.log("call writeText success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.writeArrayBuffer(OBJECT)
Writes the contents of a buffer to a specific file.
Parameter
Parameter Name Type Required Description uri string Yes URI of a local file. If the local file does not exist, a file will be created. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. buffer Uint8Array Yes The buffer whose contents will be written to a file. position number No An offset of the position where the data writing starts in the file. The default is 0. append boolean No Indicates whether the append mode is used. The default is false. When this parameter is set to true, the position parameter is invalid. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.writeArrayBuffer({
uri: "internal://cache/workspace/test",
buffer: buffer, //buffer belongs to Uint8Array type
success: function () {
console.log("call writeArrayBuffer success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.readText(OBJECT)
Reads texts from a specific file.
Parameter
Parameter Name Type Required Description uri string Yes URI of a local file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. encoding string No Encoding format. The default is UTF-8. Only UTF-8 is supported now. position number No The position where text reading is started. The default is the starting position of the file. length number No The length of texts to be read. The default is 4096. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Return values of success:
Parameter Name Type Description text string Text contents that have been read.
Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. 302 Size of file contents to be read exceeds 4KB. Example
file.readText({
uri: "internal://cache/workspace/text.txt",
success: function (data) {
console.log("call readText success: " + data.text);
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.readArrayBuffer(OBJECT)
Reads buffer contents form a specific file.
Parameter
Parameter Name Type Required Description uri string Yes URI of a local file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. position number No The position where buffer reading is started. The default is the starting position of the file. length number No Length of contents to be read. The contents to the end of the file is read. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Return values of success:
Parameter Name Type Description buffer Uint8Array File contents that have been read.
Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.readArrayBuffer({
uri: "internal://app/workspace/test",
position: 10,
length: 200,
success: function (data) {
console.log("call readArrayBuffer success: " + data.buffer);
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.access(OBJECT)
Checks whether a specific file or directory exists.
Parameter
Parameter Name Type Required Description uri string Yes URI of a directory or file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.access({
uri: "internal://app/test",
success: function () {
console.log("call access success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.mkdir(OBJECT)
Creates a specific directory.
Parameter
Parameter Name Type Required Description uri string Yes URI path of the directory. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed. In addition, the maximum recursive depth of the directory is 5. recursive boolean No Indicates whether to recursively create a parent directory for this directory. The default is false. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. Example
file.mkdir({
uri: "internal://share/test_directory",
success: function () {
console.log("call mkdir success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
file.rmdir(OBJECT)
Deletes a specific directory.
Parameter
Parameter Name Type Required Description uri string Yes URI path of the directory. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string. recursive boolean No Indicates whether to recursively delete subfiles and subdirectories. The default is false. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Returned error codes of fail:
Error Code Description 202 A parameter error occurs. 300 An I/O error occurs. 301 File or directory does not exist. Example
file.rmdir({
uri: "internal://app/test_directory",
success: function () {
console.log("call rmdir success.");
},
fail: function (data, code) {
console.error("call fail callback fail, code: " + code + ", data: " + data);
},
});
Audio Player
Play: boolean play();
Pause: boolean pause();
Stop: boolean stop();
Get Player Status
getPlayState({ success: (data) => {}, complete: () => {} });
data Attributes | Type | Value |
---|---|---|
status | string | "play","pause","stop" |
src | string | Audio file path |
currentTime | number | Current play time |
autoplay | boolean | Autoplay or not |
loop | boolean | Loop play or not |
volume | number | Volume |
muted | boolean | Muted or not |
Set/Get Play Path
audio.src = "internal://mass/A.mp3";
Set/Get Play Position
currentTime;
Get Audio Play Time
duration;
Set/Get Loop Play
loop;
Set/Get Player Volume
volume;
Set/Get Player Mute State
muted;
Set onplay Callback
onplay;
Set onpause Callback
onpause;
Set onstop Callback
onstop;
Set onloadeddata Callback
onloadeddata;
Set onended Callback
onended;
Set onerror Callback
onerror;
Set ontimeupdate Callback
ontimeupdate (notification interval 1S)
Player Demo
import audio from "@system.audio";
audio.onplay = () => {};
audio.onpause = () => {};
audio.onstop = () => {};
audio.onloadeddata = () => {};
audio.onended = () => {};
audio.onerror = () => {};
audio.ontimeupdate = () => {};
audio.src = "internal://mass/A.mp3";
audio.play();
audio.pause();
audio.stop();
System Capabilities
Device Interconnect
The interconnect API is used for communicating with the application on a mobile phone, sending and receiving data to and from the application on the mobile phone. Because a connection to the mobile phone is automatically set up, you need not to care about connection creation or destroy. However, a callback function can be registered to receive the information of connection status changes, which allows you to take actions when necessary, such as notifying the user of a status change.
Get APK Installation Information on Mobile Phone:
var conn_status = conn.getApkStatus();
if (conn_status == "CONNECTED") {
} else if (conn_status == "DISCONNECTED") {
} else if (conn_status == "UNINSTALLED") {
} else {
//error
}
API Declaration
{ "name": "system.interconnect" }
Imported Module
import interconnect from '@system.interconnect' or const interconnect = require('@system.interconnect')
API Definition
interconnect.instance
Gets a connection object, which exists as a singleton in the application. All follow-up data transfer actions are based on this connection object.
Parameter
None.
Example
let conn = interconnect.instance();
Data Transfer API Specifications
Send Data conn.send
conn.send({
data: {},
success: ()=>{
console.log(`handling success`)
},
fail: (data: {data, code})=> {
console.log(`handling fail, errMsg = ${data.data}, errCode = ${data.code}`)
}
})
Receive Data conn.onmessage
conn.onmessage = (data: {data}) => {
console.log(`received message: ${data.data}`)
}
Connection Open Callback conn.onopen
conn.onopen = () => {
console.log(`connection opened`);
};
Connection Close Callback conn.onclose
conn.onclose = (data: {data, code}) => {
console.log(`connection closed, reason = ${data.data}, code = ${data.code}`)
}
Connection Error Callback conn.onerror
conn.onerror = (data: {data, code})=> {
console.log(`connection error, errMsg = ${data.data}, errCode = ${data.code}`)
}
Network Status
API Declaration
{ "name": "system.network" }
Imported Module
import network from '@system.network' or const network = require('@system.network')
API Definition
network.subscribe(OBJECT)
Cancels the listening of network connection status.
Parameters:
None
Example:
network.unsubscribe();
Subscription
Subscribe Bluetooth Status
subscribe({
type: "BT",
callback: (conn_status) => {
if (conn_status) {
//connection status
} else {
//disconnection status
}
},
});
Subscribe Wi-Fi Status
subscribe({
type: "WIFI",
callback: (conn_status) => {
if (conn_status) {
//connection status
} else {
//disconnection status
}
},
});
Unsubscribe
Unsubscribe Bluetooth Status: unsubscribe({type:'BT'})
Unsubscribe Wi-Fi Status: unsubscribe({type:'WIFI'});
Vibrator
API Declaration
{ "name": "system.vibrator" }
Imported Module
import vibrator from '@system.vibrator' or const vibrator = require('@system.vibrator')
API Definition
vibrator.vibrate(OBJECT)
Triggers the vibrator.
Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
mode | String | No | Vibration mode: “long” indicates long vibration; “short” indicates short vibration. The default is long. |
Example:
vibrator.vibrate({
mode: "long",
});
Screen Brightness
API Declaration
{ "name": "system.brightness" }
Imported Module
import brightness from '@system.brightness' or const brightness = require('@system.brightness')
API Definition
brightness.getValue(OBJECT)
Gets the current screen brightness.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Return values of success:
Parameter Value | Type | Description |
---|---|---|
value | Integer | Screen brightness. The value range is 0-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.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
value | Integer | Yes | Screen brightness. The value range is 0-255. |
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Example:
brightness.setValue({
value: 100,
success: function () {
console.log("handling success");
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`);
},
});
brightness.getMode(OBJECT)
Gets the current screen brightness mode.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Return values of success:
Parameter Value | Type | Description |
---|---|---|
mode | Integer | 0 indicates the manual brightness adjustment. 1 indicates automatic brightness adjustment. |
Example:
brightness.getMode({
success: function (data) {
console.log(`handling success, mode = ${data.mode}`);
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`);
},
});
brightness.setMode(OBJECT)
Sets the current screen brightness mode.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
mode | Integer | Yes | 0 indicates the manual brightness adjustment. 1 indicates automatic brightness adjustment. |
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Example:
brightness.setMode({
mode: 1,
success: function () {
console.log("handling success");
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`);
},
});
brightness.setKeepScreenOn(OBJECT) 1060+
Sets whether to keep the screen on.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
keepScreenOn | Boolean | Yes | Whether to keep the screen on. |
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Example:
brightness.setKeepScreenOn({
keepScreenOn: true,
success: function () {
console.log("handling success");
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`);
},
});
Device Information
Modules to Import
import device from "@system.device";
device.getInfo(OBJECT)
Gets the information of the current device.
Parameter
Parameter Name Type Required Description success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. Return values of success:
Parameter Name Type Description brand string Brand. manufacturer string Manufacturer. model string Model. product string Code. language string System language. region string System region. windowWidth number Available window width. windowHeight number Available window height. screenDensity number Screen density. screenShape string Screen shape. Optional values: rect: rectangle screen; circle: circle screen. IMEI string Device IMEI. releaseType5+ string Release type. The value format is type + version number, for example, Beta1. The optional values are:
Canary: In the same apiVersion, different Canary versions are API compliant. Beta versions are not compliant with Canary versions.
Beta: In the same apiVersion, different Beta versions are API compliant. Release versions are not compliant with Beta versions.
Release: Release versions are compliant with five API versions.deviceType5+ string Device type. The optional values are:
tv: smart screen
wearable: smart wearable
liteWearable: lightweight smart wearables
smartVision: smart vision devicesReturned error codes of fail:
Error Code Description 200 Unavailable information in the returned result. Example
device.getInfo({
success: function (data) {
console.log(
"Device information obtained successfully. Device brand:" + data.brand
);
},
fail: function (data, code) {
console.log(
"Failed to obtain device information. Error code:" +
code +
"; Error information: " +
data
);
},
});
Health(Sensor)
Modules to Import
import request from "@system.health";
var hr = getHr();
Geographic Location
Modules to Import
import geolocation from "@system.geolocation";
or;
const geolocation = require("@system.geolocation");
geolocation.getLocation(OBJECT)
Obtains the geographic location.
- Parameters:
Parameter | Type | Mandatory | Description |
---|---|---|---|
timeout | Long | No | Timeout duration, in milliseconds. The default value is 30000. The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called. |
coordType | String | No | Coordinate system type. Available types can be obtained by getSupportedCoordTypes. The default type is wgs84 |
success | Function | Yes | Called when the operation is successful. |
fail | Function | No | Called when the operation fails. Possibly because the user rejected the request |
complete | Function | No | Called when the execution is complete. |
- The following values will be returned when the operation is successful:
Parameter | Type | Description |
---|---|---|
longitude | Number | Longitude |
latitude | Number | Latitude |
accuracy | Number | Location accuracy |
time | Number | Time (when the location is obtained) |
- One of the following error codes will be returned if the operation fails.
Error Code | Description |
---|---|
201 | Failed to obtain the required permission because the user rejected the request. |
204 | Operation times out due to a poor network condition or unavailable GPS. |
1000 1000+ | System location disabled. |
- 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.subscribe(OBJECT)
Listens to the geographical location. If this API is called multiple times, the last call takes effect.
- Parameters:
Parameter | Type | Mandatory | Description |
---|---|---|---|
reserved | Boolean | No | Persistent subscription. The default value is false. When it is set to be true, then after the page is destroyed, this API would not be unsubscribed automatically. It need to be unsubscribed manually |
coordType | String | No | Coordinate system type. Available types can be obtained by getSupportedCoordTypes,The default type is wgs84. |
callback | Function | Yes | Called when the geographical location changes |
fail | Function | No | Called when the listening fails, Possibly because the user rejected the request |
- The following values will be returned when the network type is obtained.:
Parameter | Type | Description |
---|---|---|
longitude | Number | Longitude |
latitude | Number | Latitude |
accuracy | Number | Location accuracy |
time | Number | Time when the location is obtained |
- One of the following error codes will be returned if the operation fails.
Error Code | Description |
---|---|
201 | Failed to obtain the required permission because the user rejected the request. |
1000 1000+ | System location disabled. |
- Example
geolocation.subscribe({
callback: function (data) {
console.log(
`handling success: longitude = ${data.longitude}, latitude = ${data.latitude}`
);
},
fail: function (data, code) {
console.log(`handling fail, code = ${code}`);
},
});
geolocation.unsubscribe()
Cancels listening to the geographical location.
Parameters N/A
Example
geolocation.unsubscribe();
Network Access
Upload and Download
Support Devices
Table 1 Devices Supporting APIs
API | Mobile Phone | Tablet | Smart Screen | Smart Wearable |
---|---|---|---|---|
request.upload | Support | Support | Support | Support |
request.download | Support | Support | Support | Support |
request.onDownloadComplete | Support | Support | Support | Support |
Imported Module
import request from "@system.request";
request.upload(OBJECT)
Uploads files.
Parameter
Parameter Name Type Required Description url string Yes Resource URL. header Object No Request header. method string No Request method: POST or PUT. The default is POST. files Array <File>
Yes A list of files to be uploaded. Use multipart/form-data to submit the list. data Array <RequestData>
No Requested form data. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete.
Table 2 File
Parameter Name | Type | Required | Description |
---|---|---|---|
filename | string | No | The file name in the request header when multipart submits the form. |
name | string | No | The name of the form item when multipart submits the form. The default is file. |
uri | string | Yes | The local storage URI of the file. For the usage of URI, see the definition of storage directories. |
type | string | No | The type of contents in the file. The content type is obtained according to the file name or the URI suffix by default. |
Table 3 RequestData
Parameter Name | Type | Required | Description |
---|---|---|---|
name | string | Yes | Indicates the name of a form element. |
value | string | Yes | Indicates the value of a form element. |
Return values of success:
Parameter Name | Type | Description |
---|---|---|
code | number | Status code returned by the server. |
data | string | Contents returned by the server. The type of this value is determined by the type of contents in the returned header. |
headers | Object | The contents of the header returned by the server. |
- Example
request.upload({
url: "http://www.path.com",
files: [
{
uri: "internal://cache/path/to/file.txt",
name: "file",
filename: "file.txt",
},
],
data: [
{
name: "name1",
value: "value",
},
],
success: function (data) {
console.log("upload success, code:" + data.code);
},
fail: function () {
console.log("upload fail");
},
});
request.download(OBJECT)
Downloads a file.
Parameter
Parameter Name Type Required Description url string Yes Resource URL. header Object No Request header. description string No A download description of the resource address. The default is the file name. filename string No The name of the file to be downloaded. The file name is obtained from the request or resource address by default. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete. share bool Yes true: The download request will coexist with requests of share type. false: The download request will interrupt requests of share type. onDownLoadNotify Function No Notification of the download progress. Return values of success:
Parameter Name | Type | Description |
---|---|---|
token | string | A token that indicates the download, which is the basis to get the download status. |
Return values of onDownLoadNotify:
Parameter Name | Type | Description |
---|---|---|
result | number | 0 - success (other values - failure) |
percent | number | 0 to 100 (download progress) |
Returned error codes of fail:
Error Code | Description |
---|---|
400 | Indicates that the download task failed. |
- Example
request.download({
url: "http://www.path.com",
success: function (data) {
console.log("call success callback success: " + data.token);
},
fail: function (data, code) {
console.log("handling fail");
},
});
request.onDownloadComplete(OBJECT)
Gets the status of a download task.
Parameter
Parameter Name Type Required Description token string Yes The token returned by the download API. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete.
Return values of success:
Parameter Name | Type | Description |
---|---|---|
uri | string | Indicates the URI of the downloaded file. |
percent | number | 0 to 100 (download progress) |
Returned error codes of fail:
Error Code | Description |
---|---|
400 | Indicates that the download task failed. |
401 | Indicates that the download task does not exist. |
Example
request.onDownloadComplete({
token: "token-index",
success: function (data) {
console.log("download success, uri:" + data.uri);
},
fail: function (data, code) {
console.log("download fail");
},
});
Date Request
Support Devices
Table 1 Devices Supporting APIs
API | Smart Wearable |
---|---|
fetch.fetch | Support |
Imported Module
import fetch from "@system.fetch";
fetch.fetch(OBJECT)
Fetches data through the network.
Parameter
Parameter Name Type Required Description url string Yes Resource URL. data string| Object No Requested parameters. The optional types include string and JSON object. header Object No Sets the request header. method string No The default request method is GET. The optional methods include: OPTIONS, GET, HEAD, POST, PUT, DELETE, and TRACE. responseType string No The response type is determined by Content-Type in the header returned by the server by default. The supported types include text and JSON formats. For details, see the return values of success. success Function No Callback function after a successful API call. fail Function No Callback function after a failed API call. complete Function No Callback function after an API call is complete.
Table 2 Relationship Between data and Content-Type
data | Content-Type | Description |
---|---|---|
string | Not set | The default Content-Type is text/plain. The value of data is used as the request body. |
string | Any type | The value of data is used as the request body. |
Object | Not set | The default Content-Type is application/x-www-form-urlencoded. The data is used as the request body after being encoded and spliced according to the specification of resource addresses. |
Object | application/x-www-form-urlencoded | The data is used as the request body after being encoded and spliced according to the specification of resource addresses. |
Return values of success:
Parameter Name | Type | Description |
---|---|---|
code | number | Indicates the server status code. |
data | string| Object | The type of returned data is determined by responseType. For details, see the relationship between responseType and data in success. |
headers | Object | Indicates all headers in the response of the server. |
Table 3 Relationship Between responseType and data in success
responseType | data | Description |
---|---|---|
None | string | If the type in the header returned by the server is text/*, application/json, application/javascript, or application/xml, the value is the text contents. |
text | string | Returns text contents. |
json | Object | Returns an JSON object. |
- Example
import fetch from "@system.fetch";
export default {
data: {
responseData: "NA",
url: "test_url",
},
fetch: function () {
var that = this;
fetch.fetch({
url: that.url,
success: function (response) {
console.info("fetch success");
that.responseData = JSON.stringify(response);
},
fail: function () {
console.info("fetch fail");
},
});
},
};
HTTPS is supported by default. If HTTP support is required, a network tag with the attribute "usesCleartext": true needs to be added in config.json. For example:
{
"deviceConfig": {
"default": {
"network": {
"usesCleartext": true
}
...
}
}
...
}
Others
Cipher
API Declaration
{ "name": "system.cipher" }
Imported Module
import cipher from '@system.cipher' or const cipher = require('@system.cipher')
API Definition
cipher.rsa(OBJECT)
RSA encryption and decryption. RSA does not support segment-based encryption. Therefore, an error may occur if the content to be encrypted is too long.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
action | String | Yes | Cipher action type. The optional values include: encrypt: encrypt, decrypt: decrypt, and sign: digital signature. |
text | String | Yes | The text content to be encrypted or decrypted. The text content to be encrypted must be a piece of normal text with a length not exceeding the result of keySize/8 - 66. keySize is the length of the private key. For example, the text length cannot exceed 62 bytes when the private key length is 1024. The text content to be decrypted must be a binary data segment encoded with base64. The default style is used during base64 encoding, which is the same as the parameter below. |
key | String | Yes | The RSA key used for encryption or decryption. This key is a string generated after base64 encoding. A public key is used in encryption while a private key is used in decryption. |
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Return values of success:
Parameter Name | Type | Description |
---|---|---|
text | String | The text content generated after encryption or decryption. The content after encryption is a binary data segment encoded with base64. The content after decryption is a piece of normal text. An error may occur if the content after decryption cannot be converted to a UTF-8 string. |
Error codes returned by fail
Error Code | Description |
---|---|
202 | Input parameter error. |
Example:
//encrypt
cipher.rsa({
action: "encrypt",
//the text content to be encrypted
text: "hello",
//public encryption key with base64 encoding
key:
"-----BEGIN RSA PRIVATE KEY-----\n" +
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDc7GR2MrfAoefES+wrs1ns2afT\n" +
"eJXSfIkEHfPXG9fVFjaws1ho4KcZfsxlA0+SXvc83f2SVGCuzULmM2lxxRCtcUN/\n" +
"h7SoaYEeluhqFimL2AEjfSwINHCLqObJkcjCfoZpE1JCehPiDOJsyT50Auc08h/4\n" +
"jHQfanyC1nc62LqUCQIDAQAB\n" +
"-----END RSA PRIVATE KEY-----",
success: function(data) {
console.log(`handling success: ${data.text}`);
},
fail: function(data, code) {
console.log(`### cipher.rsa fail ### ${code}: ${data}`);
},
});
//decrypt:
cipher.rsa({
action: "decrypt",
//the content to be decrypted is a binary data segment encoded with base64. The content after decryption is the text with "hello".
text:
"CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n" +
"gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n" +
"S/ZWNI4Q8Q0suNjNkGU=",
//private decryption key with base64 encoding
key:
"-----BEGIN RSA PUBLIC KEY-----\n" +
"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANzsZHYyt8Ch58RL\n" +
"7CuzWezZp9N4ldJ8iQQd89cb19UWNrCzWGjgpxl+zGUDT5Je9zzd/ZJUYK7NQuYz\n" +
"aXHFEK1xQ3+HtKhpgR6W6GoWKYvYASN9LAg0cIuo5smRyMJ+hmkTUkJ6E+IM4mzJ\n" +
"PnQC5zTyH/iMdB9qfILWdzrYupQJAgMBAAECgYEAkibhH0DWR13U0gvYJeD08Lfd\n" +
"Sw1PMHyquEqIcho9Yv7bF3LOXjOg2EEGPx09mvuwXFgP1Kp1e67XPytr6pQQPzK7\n" +
"XAPcLPx80R/ZjZs8vNFndDOd1HgD3vSVmYQarNzmKi72tOUWMPevsaFXPHo6Xx3X\n" +
"8x0wYb7XuBsQguRctTECQQD7GWX3JUiyo562iVrpTDPOXsrUxmzCrgz2OZildxMd\n" +
"Pp/PkyDrx7mEXTpk4K/XnQJ3GpJNi2iDSxDuPSAeJ/aPAkEA4Tw4+1Z43S/xH3C3\n" +
"nfulYBNyB4si6KEUuC0krcC1pDJ21Gd12efKo5VF8SaJI1ZUQOzguV+dqNsB/JUY\n" +
"OFfX5wJAB1dKv9r7MR3Peg6x9bggm5vx2h6i914XSuuMJupASM6X5X2rrLj+F3yS\n" +
"RHi9K1SPyeOg+1tkBtKfABgRZFBOyQJAbuTivUSe73AqTKuHjB4ZF0ubqgEkJ9sf\n" +
"Q2rekzm9dOFvxjZGPQo1qALX09qATMi1ZN376ukby8ZAnSafLSZ64wJBAM2V37go\n" +
"Sj44HF76ksRow8gecuQm48NCTGAGTicXg8riKog2GC9y8pMNHAezoR9wXJF7kk+k\n" +
"lz5cHyoMZ9mcd30=\n"
"-----END RSA PUBLIC KEY-----",
success: function(data) {
console.log(`handling success: ${data.text}`);
},
fail: function(data, code) {
console.log(`### cipher.rsa fail ### ${code}: ${data}`);
},
});
cipher.aes(OBJECT) 1060+
AES encryption and decryption. AES supports segment-based encryption.
Parameters:
Parameter Name | Type | Required | Description |
---|---|---|---|
action | String | Yes | Cipher action type. Two optional values are available: encrypt: encrypt, and decrypt: decrypt. |
text | String | Yes | The text content to be encrypted or decrypted. The text content to be encrypted must be a piece of normal text. The text content to be decrypted must be a binary data segment encoded with base64. The default style is used during base64 encoding, which is the same as the parameter below. |
key | String | Yes | The key used for encryption or decryption. This key is a string generated after base64 encoding. |
transformation | String | No | The encryption mode and padding scheme used by the AES algorithm. The default is "AES/CBC/PKCS5Padding". |
iv | String | No | The initialization vector used for AES encryption and decryption. This vector is a string encoded with base64. The default is the value of key. |
ivOffset | Integer | No | The offset of the initialization vector used for AES encryption and decryption. The default is 0. |
ivLen | Integer | No | The length in bytes of the initialization vector used for AES encryption and decryption. The default is 16. |
success | Function | No | Callback on success |
fail | Function | No | Callback on failure |
complete | Function | No | Callback on completion |
Return values of success:
Parameter Name | Type | Description |
---|---|---|
text | String | The text content generated after encryption or decryption. The content after encryption is a binary data segment encoded with base64. The content after decryption is a piece of normal text. An error occurs (CODE: 200) when the content obtained after decryption cannot be converted into a UTF-8 string |
Error codes returned by fail
Error Code | Description |
---|---|
200 | General error, which is returned when an error occurs during encryption or decryption |
202 | Parameter error |
Example:
//encrypt
cipher.aes({
action: "encrypt",
//the text content to be encrypted
text: "hello",
//key with base64 encoding
key: "NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=",
transformation: "AES/CBC/PKCS5Padding",
ivOffset: 0,
ivLen: 16,
success: (data) => {
console.log(`handling success: ${data.text}`);
},
fail: (data, code) => {
console.log(`### cipher.aes fail ### ${code}: ${data}`);
},
});
//decrypt:
cipher.aes({
action: "decrypt",
//the content to be decrypted is a binary data segment encoded with base64.
text:
"CUg3tTxTIdpCfreIxIBdws3uhd5qXLwcrVl3XDnQzZFVHyjVVCDHS16rjopaZ4C5xU2Tc8mSDzt7\n" +
"gp9vBfSwi7bMtSUvXG18DlncsKJFDkJpS5t0PkpS9YrJXrY80Gpe+ME6+6dN9bjgqMljbitDdBRf\n" +
"S/ZWNI4Q8Q0suNjNkGU=",
//key with base64 encoding
key: "NDM5Qjk2UjAzMEE0NzVCRjlFMkQwQkVGOFc1NkM1QkQ=",
transformation: "AES/CBC/PKCS5Padding",
ivOffset: 0,
ivLen: 16,
success: (data) => {
this.dealTxt = data.text;
},
fail: (data, code) => {
prompt.showToast({
message: "encryption failed, code=" + code + ":" + data,
});
},
});