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.

codeMeaning
200Common error
202Parameter error
300I/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 NameTypeDescription
    appNamestringIndicates the application name.
    versionNamestringIndicates the version name of the application.
    versionCodenumberIndicates 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 NameTypeRequiredDescription
    messagestringYesIndicates 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 NameTypeRequiredDescription
    uristringYesUniform 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.
    paramsObjectNoThe 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 NameTypeDescription
    languagestringLanguage. For example, zh.
    countryOrRegionstringCountry or region. For example, CN.
    dirstringTest 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

APILightweight smart wearables
setTimeoutSupport
clearTimeoutSupport
setIntervalSupport
clearIntervalSupport

Imported Module

No import required.

Permission List

None

setTimeout(handler[, delay[, ...args]])

Sets a timer. This timer executes a function upon expiration.

  • Parameter

    Parameter NameTypeRequiredDescription
    handlerFunctionYesThe function to be executed upon expiration of the timer.
    delaynumberNoA 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.
    ...argsArray<any>NoAdditional 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 NameTypeRequiredDescription
    timeoutIDnumberYesID 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 NameTypeRequiredDescription
    handlerFunctionYesThe function to be called repeatedly.
    delaynumberNoA delay in milliseconds. One second equals to 1000 milliseconds. The function is called repeatedly at an interval of the delay time.
    ...argsArray<any>NoAdditional 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 NameTypeRequiredDescription
    intervalIDnumberYesID 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:

ParameterTypeRequiredDescription
uriStringYesURI 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",
        },
      });
      
  • 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:

ParameterTypeRequiredDescription
uriStringYesURI 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.
paramsObjectNoThe 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:

ParameterTypeRequiredDescription
pathStringNoPath 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:

TypeDescription
NumberNumber 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 NameTypeDescription
indexNumberLocation of the current page in the page stack.
nameStringName of the current page
pathStringPath 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:

TypeDescription
ArrayList of the page stack. Each element in the array is of the Object type.

Each element in the array consists of:

FieldTypeDescription
nameStringPage name
pathStringPage 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 NameTypeRequiredDescription
    keystringYesContent index. The maximum length of the string is 32. Special characters such as “/"*+,:;<=>?[] | \x7F” are not allowed in the string.
    defaultstringNoIf 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.
    successFunctionNoCallback function after a successful API call, which is used to return the stored contents.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback 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 NameTypeRequiredDescription
    keystringYesIndex 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.
    valuestringNoNew 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.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback 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 NameTypeRequiredDescription
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback 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 NameTypeRequiredDescription
    keystringYesContent index. The maximum length of the string is 32. Special characters such as “/"*+,:;<=>?[] | \x7F” are not allowed in the string.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback 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 NameTypeRequiredDescription
    srcUristringYesURI 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.
    dstUristringYesThe 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.
    successFunctionNoCallback function after a successful API call. This function returns the URI of the location where the file will be moved to.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    srcUristringYesURI 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.
    dstUristringYesURI 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.
    successFunctionNoCallback function after a successful API call. This function returns the URI of the location where the file will be copied to.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesDirectory URI. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Return values of success:

    Parameter NameTypeDescription
    fileListArray<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 NameTypeDescription
    uristringFile URI.
    lastModifiedTimenumberThe 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.
    lengthnumberFile size in the unit of bytes. The length has a fixed value 0 when the file type is dir.
    typestringFile type. The optional values are: dir: directory; file: file.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesFile URI. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    recursivebooleanNoIndicates whether to get a recursive list of files in subdirectories. The default is false.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Return values of success:

    Parameter NameTypeDescription
    uristringFile URI.
    lengthnumberFile size in bytes. The length has a fixed value 0 when the file type is dir.
    lastModifiedTimenumberFile 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.
    typestringFile type. The optional values are: dir: directory; file: file.
    subFilesArrayA list of files.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI 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.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI 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.
    textstringYesA written string.
    encodingstringNoEncoding format. The default is UTF-8. Only UTF-8 is supported now.
    appendbooleanNoIndicates whether the append mode is used. The default is false.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI 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.
    bufferUint8ArrayYesThe buffer whose contents will be written to a file.
    positionnumberNoAn offset of the position where the data writing starts in the file. The default is 0.
    appendbooleanNoIndicates whether the append mode is used. The default is false. When this parameter is set to true, the position parameter is invalid.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI of a local file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    encodingstringNoEncoding format. The default is UTF-8. Only UTF-8 is supported now.
    positionnumberNoThe position where text reading is started. The default is the starting position of the file.
    lengthnumberNoThe length of texts to be read. The default is 4096.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Return values of success:

    Parameter NameTypeDescription
    textstringText contents that have been read.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File or directory does not exist.
    302Size 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 NameTypeRequiredDescription
    uristringYesURI of a local file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    positionnumberNoThe position where buffer reading is started. The default is the starting position of the file.
    lengthnumberNoLength of contents to be read. The contents to the end of the file is read.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Return values of success:

    Parameter NameTypeDescription
    bufferUint8ArrayFile contents that have been read.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI of a directory or file. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 NameTypeRequiredDescription
    uristringYesURI 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.
    recursivebooleanNoIndicates whether to recursively create a parent directory for this directory. The default is false.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An 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 NameTypeRequiredDescription
    uristringYesURI path of the directory. The maximum length of the string is 128. Special characters such as “"*+,:;<=>?[] | \x7F” are not allowed in the string.
    recursivebooleanNoIndicates whether to recursively delete subfiles and subdirectories. The default is false.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Returned error codes of fail:

    Error CodeDescription
    202A parameter error occurs.
    300An I/O error occurs.
    301File 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 AttributesTypeValue
statusstring"play","pause","stop"
srcstringAudio file path
currentTimenumberCurrent play time
autoplaybooleanAutoplay or not
loopbooleanLoop play or not
volumenumberVolume
mutedbooleanMuted 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:

ParameterTypeRequiredDescription
modeStringNoVibration 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 NameTypeRequiredDescription
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback on completion

Return values of success:

Parameter ValueTypeDescription
valueIntegerScreen 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 NameTypeRequiredDescription
valueIntegerYesScreen brightness. The value range is 0-255.
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback 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 NameTypeRequiredDescription
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback on completion

Return values of success:

Parameter ValueTypeDescription
modeInteger0 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 NameTypeRequiredDescription
modeIntegerYes0 indicates the manual brightness adjustment. 1 indicates automatic brightness adjustment.
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback 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 NameTypeRequiredDescription
keepScreenOnBooleanYesWhether to keep the screen on.
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback 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 NameTypeRequiredDescription
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
  • Return values of success:

    Parameter NameTypeDescription
    brandstringBrand.
    manufacturerstringManufacturer.
    modelstringModel.
    productstringCode.
    languagestringSystem language.
    regionstringSystem region.
    windowWidthnumberAvailable window width.
    windowHeightnumberAvailable window height.
    screenDensitynumberScreen density.
    screenShapestringScreen shape. Optional values: rect: rectangle screen; circle: circle screen.
    IMEIstringDevice IMEI.
    releaseType5+stringRelease 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+stringDevice type. The optional values are:
    tv: smart screen
    wearable: smart wearable
    liteWearable: lightweight smart wearables
    smartVision: smart vision devices
  • Returned error codes of fail:

    Error CodeDescription
    200Unavailable 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:
ParameterTypeMandatoryDescription
timeoutLongNoTimeout 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.
coordTypeStringNoCoordinate system type. Available types can be obtained by getSupportedCoordTypes. The default type is wgs84
successFunctionYesCalled when the operation is successful.
failFunctionNoCalled when the operation fails. Possibly because the user rejected the request
completeFunctionNoCalled when the execution is complete.
  • The following values will be returned when the operation is successful:
ParameterTypeDescription
longitudeNumberLongitude
latitudeNumberLatitude
accuracyNumberLocation accuracy
timeNumberTime (when the location is obtained)
  • One of the following error codes will be returned if the operation fails.
Error CodeDescription
201Failed to obtain the required permission because the user rejected the request.
204Operation 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:
ParameterTypeMandatoryDescription
reservedBooleanNoPersistent 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
coordTypeStringNoCoordinate system type. Available types can be obtained by getSupportedCoordTypes,The default type is wgs84.
callbackFunctionYesCalled when the geographical location changes
failFunctionNoCalled when the listening fails, Possibly because the user rejected the request
  • The following values will be returned when the network type is obtained.:
ParameterTypeDescription
longitudeNumberLongitude
latitudeNumberLatitude
accuracyNumberLocation accuracy
timeNumberTime when the location is obtained
  • One of the following error codes will be returned if the operation fails.
Error CodeDescription
201Failed 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

APIMobile PhoneTabletSmart ScreenSmart Wearable
request.uploadSupportSupportSupportSupport
request.downloadSupportSupportSupportSupport
request.onDownloadCompleteSupportSupportSupportSupport

Imported Module

import request from "@system.request";

request.upload(OBJECT)

Uploads files.

  • Parameter

    Parameter NameTypeRequiredDescription
    urlstringYesResource URL.
    headerObjectNoRequest header.
    methodstringNoRequest method: POST or PUT. The default is POST.
    filesArray<File>YesA list of files to be uploaded. Use multipart/form-data to submit the list.
    dataArray<RequestData>NoRequested form data.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.

Table 2 File

Parameter NameTypeRequiredDescription
filenamestringNoThe file name in the request header when multipart submits the form.
namestringNoThe name of the form item when multipart submits the form. The default is file.
uristringYesThe local storage URI of the file. For the usage of URI, see the definition of storage directories.
typestringNoThe 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 NameTypeRequiredDescription
namestringYesIndicates the name of a form element.
valuestringYesIndicates the value of a form element.

Return values of success:

Parameter NameTypeDescription
codenumberStatus code returned by the server.
datastringContents returned by the server. The type of this value is determined by the type of contents in the returned header.
headersObjectThe 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 NameTypeRequiredDescription
    urlstringYesResource URL.
    headerObjectNoRequest header.
    descriptionstringNoA download description of the resource address. The default is the file name.
    filenamestringNoThe name of the file to be downloaded. The file name is obtained from the request or resource address by default.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.
    shareboolYestrue: The download request will coexist with requests of share type. false: The download request will interrupt requests of share type.
    onDownLoadNotifyFunctionNoNotification of the download progress.

    Return values of success:

Parameter NameTypeDescription
tokenstringA token that indicates the download, which is the basis to get the download status.

Return values of onDownLoadNotify:

Parameter NameTypeDescription
resultnumber0 - success (other values - failure)
percentnumber0 to 100 (download progress)

Returned error codes of fail:

Error CodeDescription
400Indicates 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 NameTypeRequiredDescription
    tokenstringYesThe token returned by the download API.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.

Return values of success:

Parameter NameTypeDescription
uristringIndicates the URI of the downloaded file.
percentnumber0 to 100 (download progress)

Returned error codes of fail:

Error CodeDescription
400Indicates that the download task failed.
401Indicates 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

APISmart Wearable
fetch.fetchSupport

Imported Module

import fetch from "@system.fetch";

fetch.fetch(OBJECT)

Fetches data through the network.

  • Parameter

    Parameter NameTypeRequiredDescription
    urlstringYesResource URL.
    datastring| ObjectNoRequested parameters. The optional types include string and JSON object.
    headerObjectNoSets the request header.
    methodstringNoThe default request method is GET. The optional methods include: OPTIONS, GET, HEAD, POST, PUT, DELETE, and TRACE.
    responseTypestringNoThe 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.
    successFunctionNoCallback function after a successful API call.
    failFunctionNoCallback function after a failed API call.
    completeFunctionNoCallback function after an API call is complete.

Table 2 Relationship Between data and Content-Type

dataContent-TypeDescription
stringNot setThe default Content-Type is text/plain. The value of data is used as the request body.
stringAny typeThe value of data is used as the request body.
ObjectNot setThe 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.
Objectapplication/x-www-form-urlencodedThe data is used as the request body after being encoded and spliced according to the specification of resource addresses.

Return values of success:

Parameter NameTypeDescription
codenumberIndicates the server status code.
datastring| ObjectThe type of returned data is determined by responseType. For details, see the relationship between responseType and data in success.
headersObjectIndicates all headers in the response of the server.

Table 3 Relationship Between responseType and data in success

responseTypedataDescription
NonestringIf the type in the header returned by the server is text/*, application/json, application/javascript, or application/xml, the value is the text contents.
textstringReturns text contents.
jsonObjectReturns 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 NameTypeRequiredDescription
actionStringYesCipher action type. The optional values include: encrypt: encrypt, decrypt: decrypt, and sign: digital signature.
textStringYesThe 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.
keyStringYesThe 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.
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback on completion

Return values of success:

Parameter NameTypeDescription
textStringThe 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 CodeDescription
202Input 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 NameTypeRequiredDescription
actionStringYesCipher action type. Two optional values are available: encrypt: encrypt, and decrypt: decrypt.
textStringYesThe 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.
keyStringYesThe key used for encryption or decryption. This key is a string generated after base64 encoding.
transformationStringNoThe encryption mode and padding scheme used by the AES algorithm. The default is "AES/CBC/PKCS5Padding".
ivStringNoThe initialization vector used for AES encryption and decryption. This vector is a string encoded with base64. The default is the value of key.
ivOffsetIntegerNoThe offset of the initialization vector used for AES encryption and decryption. The default is 0.
ivLenIntegerNoThe length in bytes of the initialization vector used for AES encryption and decryption. The default is 16.
successFunctionNoCallback on success
failFunctionNoCallback on failure
completeFunctionNoCallback on completion

Return values of success:

Parameter NameTypeDescription
textStringThe 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 CodeDescription
200General error, which is returned when an error occurs during encryption or decryption
202Parameter 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,
    });
  },
});
Last Updated:
Contributors: 550, wangze