提交 0a16345c 编写于 作者: L luoying_ace_admin

Merge branch 'master' of gitee.com:openharmony/docs into master128

...@@ -42,7 +42,7 @@ arkXtest is divided into two parts: unit test framework and UI test framework. ...@@ -42,7 +42,7 @@ arkXtest is divided into two parts: unit test framework and UI test framework.
- The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). - The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md).
## Environment preparations ## Preparing the Environment
### Environment Requirements ### Environment Requirements
...@@ -72,7 +72,7 @@ export default function abilityTest() { ...@@ -72,7 +72,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) { it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin"); console.info("uitest: TestUiExample begin");
//start tested ability //start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result) console.info('Uitest, start ability finished:' + result)
}).catch(err => { }).catch(err => {
console.info('Uitest, start ability failed: ' + err) console.info('Uitest, start ability failed: ' + err)
...@@ -81,7 +81,7 @@ export default function abilityTest() { ...@@ -81,7 +81,7 @@ export default function abilityTest() {
//check top display ability //check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{ await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability"); console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
done(); done();
}) })
...@@ -119,7 +119,7 @@ export default function abilityTest() { ...@@ -119,7 +119,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) { it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin"); console.info("uitest: TestUiExample begin");
//start tested ability //start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result) console.info('Uitest, start ability finished:' + result)
}).catch(err => { }).catch(err => {
console.info('Uitest, start ability failed: ' + err) console.info('Uitest, start ability failed: ' + err)
...@@ -128,7 +128,7 @@ export default function abilityTest() { ...@@ -128,7 +128,7 @@ export default function abilityTest() {
//check top display ability //check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{ await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability"); console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
//ui test code //ui test code
//init uidriver //init uidriver
...@@ -154,20 +154,173 @@ export default function abilityTest() { ...@@ -154,20 +154,173 @@ export default function abilityTest() {
## Running the Test Script ## Running the Test Script
### In DevEco Studio
You can run a test script in DevEco Studio in any of the following modes: You can run a test script in DevEco Studio in any of the following modes:
- Test package level: All test cases in the test package are executed. 1. Test package level: All test cases in the test package are executed.
- Test suite level: All test cases defined in the **describe** method are executed.
- Test method level: The specified **it** method, that is, a single test case, is executed. 2. Test suite level: All test cases defined in the **describe** method are executed.
3. Test method level: The specified **it** method, that is, a single test case, is executed.
![](figures/Execute.PNG) ![](figures/Execute.PNG)
## Viewing the Test Result **Viewing the Test Result**
After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure.
![](figures/TestResult.PNG) ![](figures/TestResult.PNG)
### In the CLI
To run a test script in the CLI, execute **aa** commands with different execution control keywords.
Parameters in aa test commands
| Keyword | Abbreviation| Description | Example |
| ------------- | ------------ | -------------------------------------- | ---------------------------------- |
| --bundleName | -b | Application bundle name. | - b com.test.example |
| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry |
| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry |
| NA | -s | \<key, value> pair.| - s unittest OpenHarmonyTestRunner |
The framework supports multiple test case execution modes, which are triggered by the key-value pair following the **-s** keyword. The table below lists the available keys and values.
| Key | Description | Value | Parameter |
| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- |
| unittest | OpenHarmonyTestRunner object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner |
| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt |
| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt |
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
**Running Commands**
Configure hdc-related environment variables, and then perform the following:
- Open the CLI.
- Run the **aa test** commands.
Example 1: Execute all test cases.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner
```
Example 2: Execute cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class s1,s2
```
Example 3: Execute specified cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0
```
Example 4: Execute all test cases except the specified ones, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s notClass testStop
```
Example 5: Execute specified test cases, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s itName stop_0
```
Example 6: Set the timeout interval for executing a test case.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s timeout 15000
```
Example 7: Enable break-on-error mode.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s breakOnError true
```
Example 8: Execute test cases of the specified type.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s testType function
```
Example 9: Execute test cases at the specified level.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s level 0
```
Example 10: Execute test cases with the specified level.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small
```
**Viewing the Test Result**
- During test execution in the CLI, the log information similar to the following is displayed:
```
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 1
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 0
OHOS_REPORT_STATUS: consuming=4
```
| Log Field | Description |
| ------- | -------------------------|
| OHOS_REPORT_SUM | Total number of test cases in the current test suite.|
| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.|
| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. |
| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.|
| OHOS_REPORT_STATUS: stream | Error information of the current test case.|
| OHOS_REPORT_STATUS: test| Name of the current test case.|
| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. The options are as follows:<br>**0**: pass<br>**1**: error<br>**2**: fail|
| OHOS_REPORT_STATUS: consuming | Execution duration of the current test case.|
- After the commands are executed, the log information similar to the following is displayed:
```
OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245
OHOS_REPORT_CODE: 0
OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error
OHOS_REPORT_STATUS: taskconsuming=16029
```
| Log Field | Description |
| ------------------| -------------------------|
| run | Total number of test cases in the current test package.|
| Failure | Number of failed test cases.|
| Error | Number of test cases whose execution encounters errors. |
| Pass | Number of passed test cases.|
| Ignore | Number of test cases not executed.|
| taskconsuming| Total time spent in executing the current test case.|
> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information.
## FAQs ## FAQs
### FAQs About Unit Test Cases ### FAQs About Unit Test Cases
...@@ -182,7 +335,7 @@ The logs added to the test case are displayed after the test case execution, rat ...@@ -182,7 +335,7 @@ The logs added to the test case are displayed after the test case execution, rat
More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete. More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete.
**Solution** **Solution**
If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode
...@@ -209,14 +362,18 @@ After the test case execution is complete, the console displays the error messag ...@@ -209,14 +362,18 @@ After the test case execution is complete, the console displays the error messag
**Possible Causes** **Possible Causes**
1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
3. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until the timeout expires.
**Solution** **Solution**
1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. 1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. 2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
3. Check the code logic and assertion result of the test case and make sure that the assertion is passed.
### FAQs About UI Test Cases ### FAQs About UI Test Cases
#### The failure log contains "Get windows failed/GetRootByWindow failed" #### The failure log contains "Get windows failed/GetRootByWindow failed"
......
# RDB Overview # RDB Overview
The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. A relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing data as in a local database. To satisfy different needs in complicated scenarios, the RDB store offers APIs for performing operations, such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. After an application is uninstalled, the related RDB store will be automatically deleted.
You do not need to care about the implementation of the database locking mechanism. You do not need to care about the implementation of the database locking mechanism.
## Basic concepts ## Basic Concepts
- **RDB** - **RDB store**
A type of database created on the basis of relational models. The RDB stores data in rows and columns. A RDB is also called RDB store. A type of database created on the basis of relational models. A RDB store holds data in rows and columns.
- **Predicate** - **Predicate**
A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. A representation of the property or feature of a data entity, or the relationship between data entities. Predicates are used to define operation conditions.
- **Result set** - **Result set**
...@@ -24,9 +24,9 @@ You do not need to care about the implementation of the database locking mechani ...@@ -24,9 +24,9 @@ You do not need to care about the implementation of the database locking mechani
## Working Principles ## Working Principles
The RDB provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features. The RDB store provides common operation APIs for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features.
**Figure 1** How RDB works **Figure 1** Working mechanism
![how-rdb-works](figures/how-rdb-works.png) ![how-rdb-works](figures/how-rdb-works.png)
...@@ -38,6 +38,6 @@ The RDB provides common operation APIs for external systems. It uses the SQLite ...@@ -38,6 +38,6 @@ The RDB provides common operation APIs for external systems. It uses the SQLite
## Constraints ## Constraints
- A maximum of four connection pools can be connected to an RDB to manage read and write operations. - An RDB store can be connected to a maximum of four connection pools to manage read and write operations.
- To ensure data accuracy, the RDB supports only one write operation at a time. - To ensure data accuracy, the RDB store supports only one write operation at a time.
...@@ -59,7 +59,7 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 ...@@ -59,7 +59,7 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md). The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md).
1. Configure the required permission in the **module.json5** file. 1. Configure the required permission in the **module.json5** file.
``` ```
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -69,13 +69,16 @@ The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In add ...@@ -69,13 +69,16 @@ The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In add
``` ```
2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. 2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded.
``` ```
import abilityAccessCtrl from '@ohos.abilityAccessCtrl.d.ts';
private requestPermissions() { private requestPermissions() {
let permissionList: Array<string> = [ let permissionList: Array<string> = [
"ohos.permission.READ_MEDIA" "ohos.permission.READ_MEDIA"
]; ];
this.context.requestPermissionsFromUser(permissionList) let atManager = abilityAccessCtrl.createAtManager();
atManager.requestPermissionsFromUser(this.context, permissionList)
.then(data => { .then(data => {
console.info(`request permission data result = ${data.authResults}`) console.info(`request permission data result = ${data.authResults}`)
}) })
......
...@@ -42,8 +42,8 @@ async function example() { ...@@ -42,8 +42,8 @@ async function example() {
let mediaType = mediaLibrary.MediaType.IMAGE; let mediaType = mediaLibrary.MediaType.IMAGE;
let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE;
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_IMAGE) const path = await media.getPublicDirectory(DIR_IMAGE);
// myAlbum is the path for storing the new file and the name of the new album. // myAlbum is the path for storing the new file and the name of the new album.
media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => {
if (fileAsset != undefined) { if (fileAsset != undefined) {
...@@ -80,7 +80,7 @@ async function example() { ...@@ -80,7 +80,7 @@ async function example() {
selectionArgs: [], selectionArgs: [],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let albumList = await media.getAlbums(AlbumNoArgsfetchOp); let albumList = await media.getAlbums(AlbumNoArgsfetchOp);
let album = albumList[0]; let album = albumList[0];
album.albumName = 'newAlbum'; album.albumName = 'newAlbum';
...@@ -88,7 +88,7 @@ async function example() { ...@@ -88,7 +88,7 @@ async function example() {
album.commitModify().then(function() { album.commitModify().then(function() {
console.info("albumRename successfully"); console.info("albumRename successfully");
}).catch(function(err){ }).catch(function(err){
console.info("albumRename failed with error:"+ err); console.info("albumRename failed with error: " + err);
}); });
} }
``` ```
...@@ -17,7 +17,7 @@ Before using file paths for development, learn the file formats supported by eac ...@@ -17,7 +17,7 @@ Before using file paths for development, learn the file formats supported by eac
| Directory | Directory Type | Media Type | Description | Supported File Format | | Directory | Directory Type | Media Type | Description | Supported File Format |
| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ | | ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ |
| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | | Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv | | Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv |
| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif | | Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif |
| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg | | Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg |
...@@ -38,7 +38,7 @@ The following describes how to obtain the public directory that stores camera fi ...@@ -38,7 +38,7 @@ The following describes how to obtain the public directory that stores camera fi
```ts ```ts
async function example(){ async function example(){
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA;
const dicResult = await media.getPublicDirectory(DIR_CAMERA); const dicResult = await media.getPublicDirectory(DIR_CAMERA);
if (dicResult == 'Camera/') { if (dicResult == 'Camera/') {
...@@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o ...@@ -69,7 +69,7 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o
**How to Develop** **How to Develop**
1. Call [Context.getFilesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox. 1. Call [context.filesDir](../reference/apis/js-apis-inner-app-context.md#contextgetfilesdir) to obtain the directory of the application sandbox.
2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. 2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory.
3. Call **fileio.open** to open the file in the sandbox. 3. Call **fileio.open** to open the file in the sandbox.
4. Call **fileAsset.open** to open the file in the public directory. 4. Call **fileAsset.open** to open the file in the public directory.
...@@ -81,11 +81,11 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o ...@@ -81,11 +81,11 @@ You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to o
```ts ```ts
async function copyPublic2Sandbox() { async function copyPublic2Sandbox() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = globalThis.context.filesDir;
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
...@@ -108,7 +108,7 @@ async function copyPublic2Sandbox() { ...@@ -108,7 +108,7 @@ async function copyPublic2Sandbox() {
```ts ```ts
async function copySandbox2Public() { async function copySandbox2Public() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let sandboxDirPath = globalThis.context.filesDir; let sandboxDirPath = globalThis.context.filesDir;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
...@@ -120,26 +120,26 @@ async function copySandbox2Public() { ...@@ -120,26 +120,26 @@ async function copySandbox2Public() {
console.info('createFile failed, message = ' + err); console.info('createFile failed, message = ' + err);
} }
try { try {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile02.txt'], selectionArgs: ['testFile02.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
var fileAsset = await fetchResult.getFirstObject(); var fileAsset = await fetchResult.getFirstObject();
} catch (err) { } catch (err) {
console.info('file asset get failed, message = ', err) console.info('file asset get failed, message = ' + err);
} }
var fdPub = await fileAsset.open('rw'); let fdPub = await fileAsset.open('rw');
var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); let fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2);
await fileio.copyFile(fdSand, fdPub); await fileio.copyFile(fdSand, fdPub);
await fileio.close(fdPub); await fileio.close(fdPub);
await fileio.close(fdSand); await fileio.close(fdSand);
let fdPubRead = await fileAsset.open('rw'); let fdPubRead = await fileAsset.open('rw');
try { try {
var arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fdPubRead, arrayBuffer); await fileio.read(fdPubRead, arrayBuffer);
var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer)); var content_pub = String.fromCharCode(...new Uint8Array(arrayBuffer));
fileAsset.close(fdPubRead); fileAsset.close(fdPubRead);
} catch (err) { } catch (err) {
console.log('read text failed, message = ', err); console.log('read text failed, message = ', err);
...@@ -167,12 +167,12 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -167,12 +167,12 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then (function (asset) { media.createAsset(mediaType, "testFile.text", path).then (function (asset) {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:" + JSON.stringify(asset));
}).catch(function(err){ }).catch(function(err){
console.info("createAsset failed with error:"+ err); console.info("createAsset failed with error: " + err);
}); });
} }
``` ```
...@@ -192,10 +192,10 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe ...@@ -192,10 +192,10 @@ You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../refe
```ts ```ts
async function writeOnlyPromise() { async function writeOnlyPromise() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?',
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
}; };
let fetchResult = await media.getFileAssets(fileAssetFetchOp); let fetchResult = await media.getFileAssets(fileAssetFetchOp);
...@@ -218,8 +218,8 @@ async function writeOnlyPromise() { ...@@ -218,8 +218,8 @@ async function writeOnlyPromise() {
```ts ```ts
async function readOnlyPromise() { async function readOnlyPromise() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileAssetFetchOp = { let fileAssetFetchOp = {
selections: fileKeyObj.DISPLAY_NAME + '= ?' , selections: fileKeyObj.DISPLAY_NAME + '= ?' ,
selectionArgs: ['testFile.txt'], selectionArgs: ['testFile.txt'],
...@@ -233,7 +233,7 @@ async function readOnlyPromise() { ...@@ -233,7 +233,7 @@ async function readOnlyPromise() {
let arrayBuffer = new ArrayBuffer(4096); let arrayBuffer = new ArrayBuffer(4096);
await fileio.read(fd, arrayBuffer); await fileio.read(fd, arrayBuffer);
let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer));
globalThis.fileContent = fileContent globalThis.fileContent = fileContent;
globalThis.fileName = fileAsset.displayName; globalThis.fileName = fileAsset.displayName;
console.info('file content: ', fileContent); console.info('file content: ', fileContent);
await fileAsset.close(fd); await fileAsset.close(fd);
......
...@@ -22,7 +22,7 @@ The **mediaLibrary** module provides APIs for you to access and modify media fil ...@@ -22,7 +22,7 @@ The **mediaLibrary** module provides APIs for you to access and modify media fil
> >
> This development guide applies only to the stage model (available from API version 9). > This development guide applies only to the stage model (available from API version 9).
To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. Unless otherwise specified, the **MediaLibrary** APIs are used in **pages/index.ets** or custom .ets files of the project code.
Before using the **MediaLibrary** APIs to develop features, you must learn how to: Before using the **MediaLibrary** APIs to develop features, you must learn how to:
...@@ -43,7 +43,7 @@ An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrar ...@@ -43,7 +43,7 @@ An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrar
import mediaLibrary from '@ohos.multimedia.mediaLibrary'; import mediaLibrary from '@ohos.multimedia.mediaLibrary';
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
``` ```
## Requesting Permissions ## Requesting Permissions
...@@ -56,7 +56,7 @@ To read and write a **MediaLibrary** instance, you must have the required permis ...@@ -56,7 +56,7 @@ To read and write a **MediaLibrary** instance, you must have the required permis
| ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant | | ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant |
| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant | | ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant |
After configuring the permissions in the **module.json5** file, the application must call [Context.requestPermissionsFromUser](../reference/apis/js-apis-ability-context.md#abilitycontextrequestpermissionsfromuser) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. After configuring the permissions in the **module.json5** file, the application must call [abilityAccessCtrl.requestPermissionsFromUser](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
> **NOTE**<br>Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**. > **NOTE**<br>Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**.
...@@ -73,7 +73,7 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -73,7 +73,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"MainAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
...@@ -83,7 +83,7 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -83,7 +83,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"MainAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
...@@ -93,7 +93,7 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -93,7 +93,7 @@ After configuring the permissions in the **module.json5** file, the application
"reason": "$string:reason", "reason": "$string:reason",
"usedScene": { "usedScene": {
"abilities": [ "abilities": [
"MainAbility" "EntryAbility"
], ],
"when": "always" "when": "always"
} }
...@@ -103,19 +103,21 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -103,19 +103,21 @@ After configuring the permissions in the **module.json5** file, the application
} }
``` ```
2. Call **requestPermissionsFromUser** to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. 2. In the **Ability.ts** file, call **requestPermissionsFromUser** in the **onWindowStageCreate** callback to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box.
```ts ```ts
import Ability from '@ohos.application.Ability' import UIAbility from '@ohos.app.ability.UIAbility';
import abilityAccessCtrl, {Permissions} from '@ohos.abilityAccessCtrl';
export default class MainAbility extends Ability { export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] let list : Array<Permissions> = ['ohos.permission.READ_MEDIA', 'ohos.permission.WRITE_MEDIA'];
var permissionRequestResult; let permissionRequestResult;
this.context.requestPermissionsFromUser(permissions,(err,result) => { let atManager = abilityAccessCtrl.createAtManager();
if(err){ atManager.requestPermissionsFromUser(this.context, list, (err, result) => {
if (err) {
console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); console.log('requestPermissionsFromUserError: ' + JSON.stringify(err));
}else{ } else {
permissionRequestResult=result; permissionRequestResult=result;
console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult));
} }
...@@ -123,5 +125,3 @@ After configuring the permissions in the **module.json5** file, the application ...@@ -123,5 +125,3 @@ After configuring the permissions in the **module.json5** file, the application
} }
} }
``` ```
...@@ -33,14 +33,14 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA ...@@ -33,14 +33,14 @@ To specify the image as the media type, set **selectionArgs** to **MediaType.IMA
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getNextObject((err, fileAsset) => {
...@@ -64,13 +64,13 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. ...@@ -64,13 +64,13 @@ To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let option = { let option = {
selections: fileKeyObj.DATE_ADDED + '= ?', selections: fileKeyObj.DATE_ADDED + '= ?',
selectionArgs: ['2022-8-5'], selectionArgs: ['2022-8-5'],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getNextObject((err, fileAsset) => {
...@@ -92,15 +92,15 @@ To sort files in descending order by the date when they are added, set **order** ...@@ -92,15 +92,15 @@ To sort files in descending order by the date when they are added, set **order**
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
order: fileKeyObj.DATE_ADDED + " DESC", order: fileKeyObj.DATE_ADDED + " DESC",
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getNextObject((err, fileAsset) => {
...@@ -124,14 +124,14 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. ...@@ -124,14 +124,14 @@ To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.IMAGE let fileType = mediaLibrary.MediaType.IMAGE;
let option = { let option = {
selections: fileKeyObj.ALBUM_NAME + '= ?', selections: fileKeyObj.ALBUM_NAME + '= ?',
selectionArgs: ['myAlbum'], selectionArgs: ['myAlbum'],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
for (let i = 0; i < fetchFileResult.getCount(); i++) { for (let i = 0; i < fetchFileResult.getCount(); i++) {
fetchFileResult.getNextObject((err, fileAsset) => { fetchFileResult.getNextObject((err, fileAsset) => {
...@@ -189,7 +189,7 @@ Complete sample code: ...@@ -189,7 +189,7 @@ Complete sample code:
```ts ```ts
async function getCameraImagePromise() { async function getCameraImagePromise() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
...@@ -236,7 +236,7 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir ...@@ -236,7 +236,7 @@ The following describes how to obtain the thumbnail (size: 720 x 720) of the fir
```ts ```ts
async function getFirstThumbnailPromise() { async function getFirstThumbnailPromise() {
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
let fileKeyObj = mediaLibrary.FileKey; let fileKeyObj = mediaLibrary.FileKey;
let imageType = mediaLibrary.MediaType.IMAGE; let imageType = mediaLibrary.MediaType.IMAGE;
let imagesFetchOp = { let imagesFetchOp = {
...@@ -280,7 +280,7 @@ async function example() { ...@@ -280,7 +280,7 @@ async function example() {
let mediaType = mediaLibrary.MediaType.FILE; let mediaType = mediaLibrary.MediaType.FILE;
let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const path = await media.getPublicDirectory(DIR_DOCUMENTS); const path = await media.getPublicDirectory(DIR_DOCUMENTS);
media.createAsset(mediaType, "testFile.text", path).then ((asset) => { media.createAsset(mediaType, "testFile.text", path).then ((asset) => {
console.info("createAsset successfully:"+ JSON.stringify(asset)); console.info("createAsset successfully:"+ JSON.stringify(asset));
...@@ -312,25 +312,25 @@ The following describes how to move the first file in the result set to the recy ...@@ -312,25 +312,25 @@ The following describes how to move the first file in the result set to the recy
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset == undefined) {
console.error('asset not exist') console.error('asset not exist');
return return;
} }
// Void callback. // Void callback.
asset.trash(true).then(() => { asset.trash(true).then(() => {
console.info("trash successfully"); console.info("trash successfully");
}).catch((err) => { }).catch((err) => {
console.info("trash failed with error:"+ err); console.info("trash failed with error: " + err);
}); });
} }
``` ```
...@@ -358,19 +358,19 @@ The following describes how to rename the first file in the result set as **newt ...@@ -358,19 +358,19 @@ The following describes how to rename the first file in the result set as **newt
```ts ```ts
async function example() { async function example() {
let fileKeyObj = mediaLibrary.FileKey let fileKeyObj = mediaLibrary.FileKey;
let fileType = mediaLibrary.MediaType.FILE let fileType = mediaLibrary.MediaType.FILE;
let option = { let option = {
selections: fileKeyObj.MEDIA_TYPE + '= ?', selections: fileKeyObj.MEDIA_TYPE + '= ?',
selectionArgs: [fileType.toString()], selectionArgs: [fileType.toString()],
}; };
const context = getContext(this); const context = getContext(this);
var media = mediaLibrary.getMediaLibrary(context); let media = mediaLibrary.getMediaLibrary(context);
const fetchFileResult = await media.getFileAssets(option); const fetchFileResult = await media.getFileAssets(option);
let asset = await fetchFileResult.getFirstObject(); let asset = await fetchFileResult.getFirstObject();
if (asset == undefined) { if (asset == undefined) {
console.error('asset not exist') console.error('asset not exist');
return return;
} }
asset.displayName = 'newImage.jpg'; asset.displayName = 'newImage.jpg';
// Void callback. // Void callback.
...@@ -380,6 +380,6 @@ async function example() { ...@@ -380,6 +380,6 @@ async function example() {
return; return;
} }
console.log('fileRename successful.'); console.log('fileRename successful.');
}) });
} }
``` ```
...@@ -108,7 +108,7 @@ ...@@ -108,7 +108,7 @@
- [MissionListener](js-apis-inner-application-missionListener.md) - [MissionListener](js-apis-inner-application-missionListener.md)
- [MissionParameter](js-apis-inner-application-missionParameter.md) - [MissionParameter](js-apis-inner-application-missionParameter.md)
- [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md)
- [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) - [PermissionRequestResult](js-apis-permissionrequestresult.md)
- [ProcessData](js-apis-inner-application-processData.md) - [ProcessData](js-apis-inner-application-processData.md)
- [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md)
- [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md)
...@@ -242,19 +242,19 @@ ...@@ -242,19 +242,19 @@
- [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md)
- [@ohos.request](js-apis-request.md) - [@ohos.request](js-apis-request.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.bluetooth (Bluetooth)](js-apis-bluetooth.md)
- [@ohos.connectedTag](js-apis-connectedTag.md) - [@ohos.connectedTag (Active Tags)](js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md) - [@ohos.nfc.cardEmulation (Standard NFC Card Emulation)](js-apis-cardEmulation.md)
- [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.controller (Standard NFC)](js-apis-nfcController.md)
- [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.nfc.tag (Standard NFC Tags)](js-apis-nfcTag.md)
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc (RPC)](js-apis-rpc.md)
- [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md)
- [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md) - [@ohos.wifiManagerExt (WLAN Extension)](js-apis-wifiManagerExt.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi (To Be Deprecated)](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext (To Be Deprecated)](js-apis-wifiext.md)
- tag - tag
- [nfctech](js-apis-nfctech.md) - [nfctech (Standard NFC Technologies)](js-apis-nfctech.md)
- [tagSession](js-apis-tagSession.md) - [tagSession (Standard NFC Tag Session)](js-apis-tagSession.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
- [@ohos.accessibility.config](js-apis-accessibility-config.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md)
...@@ -314,9 +314,9 @@ ...@@ -314,9 +314,9 @@
- [@ohos.usb](js-apis-usb.md) - [@ohos.usb](js-apis-usb.md)
- [@ohos.vibrator](js-apis-vibrator.md) - [@ohos.vibrator](js-apis-vibrator.md)
- Account Management - Account Management
- [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.appAccount (App Account Management)](js-apis-appAccount.md)
- [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.distributedAccount (Distributed Account Management)](js-apis-distributed-account.md)
- [@ohos.account.osAccount](js-apis-osAccount.md) - [@ohos.account.osAccount (OS Account Management)](js-apis-osAccount.md)
- Custom Management - Custom Management
- [@ohos.configPolicy](js-apis-configPolicy.md) - [@ohos.configPolicy](js-apis-configPolicy.md)
- [@ohos.enterprise.deviceInfo](js-apis-enterprise-deviceInfo.md) - [@ohos.enterprise.deviceInfo](js-apis-enterprise-deviceInfo.md)
......
# @ohos.account.appAccount # @ohos.account.appAccount (App Account Management)
The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization.
...@@ -4883,7 +4883,7 @@ Creates an app account implicitly based on the specified account owner. This API ...@@ -4883,7 +4883,7 @@ Creates an app account implicitly based on the specified account owner. This API
| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | | options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. |
| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| | callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.|
### addAccountImplicitly<sup>deprecated</sup> ### addAccountImplicitly<sup>(deprecated)</sup>
addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
...@@ -4922,7 +4922,7 @@ Authenticates an app account to obtain the authorization token. This API uses an ...@@ -4922,7 +4922,7 @@ Authenticates an app account to obtain the authorization token. This API uses an
| options | {[key: string]: Object} | Yes | Options for the authentication. | | options | {[key: string]: Object} | Yes | Options for the authentication. |
| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| | callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.|
### authenticate<sup>deprecated</sup> ### authenticate<sup>(deprecated)</sup>
authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
......
# @ohos.application.DataShareExtensionAbility # @ohos.application.DataShareExtensionAbility (DataShare Extension Ability)
The **DataShareExtensionAbility** module provides data share services based on the Extension ability. The **DataShareExtensionAbility** module provides data share services based on the Extension ability.
...@@ -22,12 +22,11 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili ...@@ -22,12 +22,11 @@ import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbili
The URIs are in the following format: The URIs are in the following format:
**Scheme://authority/path** **Scheme://authority/path**
- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. - *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module.
- *authority*: [userinfo@]host[:port] - *authority*: [userinfo@]host[:port]
- *userinfo*: login information, which can be left unspecified. - *userinfo*: login information, which can be left unspecified.
- *host*: server address. It is the target device ID for cross-device access and empty for local device access. - *host*: server address. It is the target device ID for cross-device access and empty for local device access.
- *port*: port number of the server, which can be left unspecified. - *port*: port number of the server, which can be left unspecified.
- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. - *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional.
Example: Example:
...@@ -42,7 +41,7 @@ Example: ...@@ -42,7 +41,7 @@ Example:
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| | context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.|
...@@ -76,7 +75,8 @@ let rdbStore; ...@@ -76,7 +75,8 @@ let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility { export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want, callback) { onCreate(want, callback) {
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
}, function (err, data) { }, function (err, data) {
console.log('getRdbStore done, data : ' + data); console.log('getRdbStore done, data : ' + data);
rdbStore = data; rdbStore = data;
......
# @ohos.bluetooth # @ohos.bluetooth (Bluetooth)
The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
......
# @ohos.nfc.cardEmulation # @ohos.nfc.cardEmulation (Standard NFC Card Emulation)
The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE). The **cardEmulation** module implements Near-Field Communication (NFC) card emulation. You can use the APIs provided by this module to determine the card emulation type supported and implement Host-based Card Emulation (HCE).
...@@ -16,21 +16,40 @@ import cardEmulation from '@ohos.nfc.cardEmulation'; ...@@ -16,21 +16,40 @@ import cardEmulation from '@ohos.nfc.cardEmulation';
Enumerates the NFC card emulation types. Enumerates the NFC card emulation types.
**System capability**: SystemCapability.Communication.NFC.Core > **NOTE**
>
> This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [hasHceCapability](#hashcecapability9).
**System capability**: SystemCapability.Communication.NFC.CardEmulation
| Name| Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| HCE | 0 | HCE.| | HCE | 0 | HCE.|
| UICC | 1 | Subscriber identity module (SIM) card emulation.| | UICC | 1 | Subscriber identity module (SIM) card emulation.|
| ESE | 2 | embedded Secure Element (eSE) emulation.| | ESE | 2 | embedded Secure Element (eSE) emulation.|
## CardType<sup>9+</sup>
Enumerates the types of services used by the card emulation application.
## cardEmulation.isSupported **System capability**: SystemCapability.Communication.NFC.CardEmulation
| Name| Value| Description|
| -------- | -------- | -------- |
| PAYMENT | "payment" | Payment type.|
| OTHER | "other" | Other types.|
## isSupported
isSupported(feature: number): boolean isSupported(feature: number): boolean
Checks whether a certain type of card emulation is supported. Checks whether a certain type of card emulation is supported.
**System capability**: SystemCapability.Communication.NFC.Core > **NOTE**
>
> This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [hasHceCapability](#hashcecapability9).
**System capability**: SystemCapability.Communication.NFC.CardEmulation
**Parameters** **Parameters**
...@@ -44,68 +63,44 @@ Checks whether a certain type of card emulation is supported. ...@@ -44,68 +63,44 @@ Checks whether a certain type of card emulation is supported.
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.|
## HceService<sup>8+</sup> ## hasHceCapability<sup>9+</sup>
Implements HCE, including receiving Application Protocol Data Units (APDUs) from the peer card reader and sending a response. Before using HCE-related APIs, check whether the device supports HCE.
### startHCE<sup>8+</sup> hasHceCapability(): boolean
startHCE(aidList: string[]): boolean Checks whether HCE is supported.
Starts HCE, including setting the application to be foreground preferred and dynamically registering the application identifier (AID) list. **System capability**: SystemCapability.Communication.NFC.CardEmulation
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.Core **Return value**
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | Yes | AID list to register.|
### stopHCE<sup>8+</sup>
stopHCE(): boolean
Stops HCE, including removing the foreground preferred attribute and releasing the dynamically registered AID list.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION | **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if HCE is supported; returns **false** otherwise.|
**System capability**: SystemCapability.Communication.NFC.Core ## isDefaultService<sup>9+</sup>
### on<sup>8+</sup> isDefaultService(elementName: ElementName, type: CardType): boolean
on(type: "hceCmd", callback: AsyncCallback<number[]>): void; Checks whether an application is the default application of the specified service type.
Registers a callback to receive APDUs from the peer card reader. **System capability**: SystemCapability.Communication.NFC.CardEmulation
**Required permissions**: ohos.permission.NFC_CARD_EMULATION **Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- | | ------- | -------- | ---- | ----------------------- |
| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. | | elementName | [ElementName](js-apis-bundleManager-elementName.md#elementname) | Yes| Application description, which consists of the bundle name and component name.|
| callback | AsyncCallback<number[]> | Yes | Callback invoked to return the APDU. Each number in the callback is a hexadecimal number ranging from **0x00** to **0xFF**.| | type | [CardType](#cardtype9) | Yes| Card emulation service type.|
### sendResponse<sup>8+</sup>
sendResponse(responseApdu: number[]): void;
Sends a response to the peer card reader.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC.Core
**Parameters** **Return value**
| Name | Type | Mandatory| Description | | **Type**| **Description**|
| ------------ | -------- | ---- | -------------------------------------------------- | | -------- | -------- |
| responseApdu | number[] | Yes | Response APDU sent to the peer card reader. Each number of the APDU is a hexadecimal number ranging from **0x00** to **0xFF**.| | boolean | Returns **true** if the application is the default payment application; returns **false** otherwise.|
**Example** **Example**
...@@ -118,23 +113,16 @@ if (!isHceSupported) { ...@@ -118,23 +113,16 @@ if (!isHceSupported) {
return; return;
} }
// The device supports HCE and transimits APDUs with the remote NFC reader. var hasHceCap = cardEmulation.hasHceCapability();
var hceService = new cardEmulation.HceService(); if (!hasHceCap) {
hceService.startHCE([ console.log('this device hasHceCapability false, ignore it.');
"F0010203040506", "A0000000041010" return;
]); }
hceService.on("hceCmd", (err, res) => { var elementName = {
if(err.data === 0) { "bundleName": "com.example.myapplication",
console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res)); "abilityName": "EntryAbility",
hceService.sendResponse([0x00,0xa4,0x04,0x00, };
0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44, var isDefaultService = cardEmulation.isDefaultService(elementName, cardEmulation.CardType.PAYMENT);
0x46,0x30,0x31,0x00]); console.log('is the app is default service for this card type: ' + isDefaultService);
} else {
console.log('callback => Operation hceCmd failed. Cause: ' + err.data);
}
})
// Stop HCE when the application exits the NFC card emulation.
hceService.stopHCE();
``` ```
# @ohos.connectedTag # @ohos.connectedTag (Active Tags)
The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags. The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags.
...@@ -129,7 +129,7 @@ Writes data to this active tag. This API uses a promise to return the result. ...@@ -129,7 +129,7 @@ Writes data to this active tag. This API uses a promise to return the result.
```js ```js
import connectedTag from '@ohos.connectedTag'; import connectedTag from '@ohos.connectedTag';
var rawData = "010203"; // change it tobe correct. var rawData = "010203"; // Set it as required.
connectedTag.writeNdefTag(rawData).then(() => { connectedTag.writeNdefTag(rawData).then(() => {
console.log("connectedTag writeNdefTag Promise success."); console.log("connectedTag writeNdefTag Promise success.");
}).catch((err)=> { }).catch((err)=> {
...@@ -159,7 +159,7 @@ Writes data to this active tag. This API uses an asynchronous callback to return ...@@ -159,7 +159,7 @@ Writes data to this active tag. This API uses an asynchronous callback to return
```js ```js
import connectedTag from '@ohos.connectedTag'; import connectedTag from '@ohos.connectedTag';
var rawData = "010203"; // change it tobe correct. var rawData = "010203"; // Set it as required.
connectedTag.writeNdefTag(rawData, (err)=> { connectedTag.writeNdefTag(rawData, (err)=> {
if (err) { if (err) {
console.log("connectedTag writeNdefTag AsyncCallback err: " + err); console.log("connectedTag writeNdefTag AsyncCallback err: " + err);
...@@ -220,7 +220,7 @@ connectedTag.on("notify", (err, rfState)=> { ...@@ -220,7 +220,7 @@ connectedTag.on("notify", (err, rfState)=> {
var initStatus = connectedTag.init(); var initStatus = connectedTag.init();
console.log("connectedTag init status: " + initStatus); console.log("connectedTag init status: " + initStatus);
// Add nfc connecected tag business oprations here... // Add NFC connected tag business operations here.
// connectedTag.writeNdefTag(rawData) // connectedTag.writeNdefTag(rawData)
// connectedTag.readNdefTag() // connectedTag.readNdefTag()
......
# @ohos.account.distributedAccount # @ohos.account.distributedAccount (Distributed Account Management)
The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states.
...@@ -252,7 +252,7 @@ Sets the distributed account information. This API uses a promise to return the ...@@ -252,7 +252,7 @@ Sets the distributed account information. This API uses a promise to return the
updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback&lt;void&gt;): void updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback&lt;void&gt;): void
Updates distributed account information. This API uses an asynchronous callback to return the result. Updates the distributed account information. This API uses an asynchronous callback to return the result.
> **NOTE** > **NOTE**
> >
......
# HUKS # @ohos.security.huks (HUKS)
The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations. The **HUKS** module provides KeyStore (KS) capabilities for applications, including key management and key cryptography operations.
The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs. The keys managed by OpenHarmony Universal KeyStore (HUKS) can be imported by applications or generated by calling the HUKS APIs.
...@@ -44,7 +44,7 @@ Defines the HUKS handle structure. ...@@ -44,7 +44,7 @@ Defines the HUKS handle structure.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | ---------- | ---- | ---------------------------------------------------- | | --------- | ---------- | ---- | ---------------------------------------------------- |
| handle | number | Yes | Value of the handle. | | handle | number | Yes | Value of the handle. |
| challenge | Uint8Array | No | Challenge obtained after the [init](#huksinit) operation.| | challenge | Uint8Array | No | Challenge obtained after the [initSession](#huksinitsession9) operation.|
## HuksReturnResult<sup>9+</sup> ## HuksReturnResult<sup>9+</sup>
...@@ -74,7 +74,7 @@ Generates a key. This API uses an asynchronous callback to return the result. ...@@ -74,7 +74,7 @@ Generates a key. This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | --------------------------------------------- | | -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.|
| callback | AsyncCallback\<void> | Yes | Callback that returns no value.| | callback | AsyncCallback\<void> | Yes | Callback that returns no value.|
**Example** **Example**
...@@ -130,7 +130,7 @@ Generates a key. This API uses a promise to return the result. ...@@ -130,7 +130,7 @@ Generates a key. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ------------------------ | | -------- | --------------------------- | ---- | ------------------------ |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. The algorithm, key purpose, and key length are mandatory.|
**Example** **Example**
...@@ -288,7 +288,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the ...@@ -288,7 +288,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | --------------------------------------------- | | -------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.|
| callback | AsyncCallback\<void> | Yes | Callback that returns no value.| | callback | AsyncCallback\<void> | Yes | Callback that returns no value.|
**Example** **Example**
...@@ -356,7 +356,7 @@ Imports a key in plaintext. This API uses a promise to return the result. ...@@ -356,7 +356,7 @@ Imports a key in plaintext. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------- | ---- | ----------------------------------- | | -------- | --------------------------- | ---- | ----------------------------------- |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import. The algorithm, key purpose, and key length are mandatory.|
**Example** **Example**
...@@ -426,7 +426,7 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call ...@@ -426,7 +426,7 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call
| -------- | ---------------------------------------------------- | ---- | --------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -553,7 +553,7 @@ Obtains the certificate used to verify a key. This API uses a promise to return ...@@ -553,7 +553,7 @@ Obtains the certificate used to verify a key. This API uses a promise to return
| Type | Description | | Type | Description |
| ---------------------------------------------- | --------------------------------------------- | | ---------------------------------------------- | --------------------------------------------- |
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.| | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -675,7 +675,7 @@ Imports a wrapped key. This API uses an asynchronous callback to return the resu ...@@ -675,7 +675,7 @@ Imports a wrapped key. This API uses an asynchronous callback to return the resu
| ---------------- | --------------------------- | ---- | --------------------------------------------- | | ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the wrapped key to import. | | keyAlias | string | Yes | Alias of the wrapped key to import. |
| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.|
| callback | AsyncCallback\<void> | Yes | Callback that returns no value.| | callback | AsyncCallback\<void> | Yes | Callback that returns no value.|
**Example** **Example**
...@@ -891,7 +891,7 @@ Imports a wrapped key. This API uses a promise to return the result. ...@@ -891,7 +891,7 @@ Imports a wrapped key. This API uses a promise to return the result.
| ---------------- | --------------------------- | ---- | --------------------------------------------- | | ---------------- | --------------------------- | ---- | --------------------------------------------- |
| keyAlias | string | Yes | Alias of the wrapped key to import. | | keyAlias | string | Yes | Alias of the wrapped key to import. |
| wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. | | wrappingKeyAlias | string | Yes | Alias of the data used to unwrap the key imported. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and the wrapped key to import. The algorithm, key purpose, and key length are mandatory.|
**Example** **Example**
...@@ -926,7 +926,7 @@ Exports a key. This API uses an asynchronous callback to return the result. ...@@ -926,7 +926,7 @@ Exports a key. This API uses an asynchronous callback to return the result.
| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.|
**Example** **Example**
...@@ -968,7 +968,7 @@ Exports a key. This API uses a promise to return the result. ...@@ -968,7 +968,7 @@ Exports a key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ---------------------------------------------- | ------------------------------------------------------------ | | ---------------------------------------------- | ------------------------------------------------------------ |
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. |
**Example** **Example**
...@@ -1005,7 +1005,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res ...@@ -1005,7 +1005,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res
| -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.|
**Example** **Example**
...@@ -1047,7 +1047,7 @@ Obtains key properties. This API uses a promise to return the result. ...@@ -1047,7 +1047,7 @@ Obtains key properties. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------------------- | ------------------------------------------------------------ | | ----------------------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. | | Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result. If the operation is successful, no **err** value is returned and **properties** contains the parameters required for generating the key. If the operation fails, an error code is returned. |
**Example** **Example**
...@@ -1126,7 +1126,7 @@ Checks whether a key exists. This API uses a promise to return the result. ...@@ -1126,7 +1126,7 @@ Checks whether a key exists. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------- | --------------------------------------- | | ----------------- | --------------------------------------- |
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.|
**Example** **Example**
...@@ -1163,8 +1163,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback ...@@ -1163,8 +1163,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback
| -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------------------------- | ---- | ---------------------------------------------------- |
| keyAlias | string | Yes | Alias of the target key. | | keyAlias | string | Yes | Alias of the target key. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. | | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization. |
| callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle)> | Yes | Callback invoked to return the key operation handle.| | callback | AsyncCallback\<[HuksSessionHandle](#hukssessionhandle9)> | Yes | Callback invoked to return the handle obtained through the initialization operation.|
## huks.initSession<sup>9+</sup> ## huks.initSession<sup>9+</sup>
...@@ -1185,7 +1184,7 @@ Initializes the data for a key operation. This API uses a promise to return the ...@@ -1185,7 +1184,7 @@ Initializes the data for a key operation. This API uses a promise to return the
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksSessionHandle](#hukssessionhandle)> | Promise used to return the key operation handle.| | Promise\<[HuksSessionHandle](#hukssessionhandle9)> | Promise used to return the handle obtained through the initialization operation.|
## huks.updateSession<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
...@@ -1201,7 +1200,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to ...@@ -1201,7 +1200,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to
| -------- | ---------------------------------------------------- | ---- | -------------------------------------------- | | -------- | ---------------------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.|
## huks.updateSession<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
...@@ -1219,7 +1218,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to ...@@ -1219,7 +1218,7 @@ Updates the key operation by segment. This API uses an asynchronous callback to
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| token | Uint8Array | Yes | Token of the **Update** operation. | | token | Uint8Array | Yes | Token of the **Update** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.|
## huks.updateSession<sup>9+</sup> ## huks.updateSession<sup>9+</sup>
...@@ -1241,7 +1240,7 @@ Updates the key operation data by segment. This API uses a promise to return the ...@@ -1241,7 +1240,7 @@ Updates the key operation data by segment. This API uses a promise to return the
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| | Promise<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.|
## huks.finishSession<sup>9+</sup> ## huks.finishSession<sup>9+</sup>
...@@ -1258,7 +1257,7 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -1258,7 +1257,7 @@ Completes the key operation and releases resources. This API uses an asynchronou
| handle | number | Yes | Handle of the **Finish** operation. | | handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | Yes | Token for the **Finish** operation. | | token | Uint8Array | Yes | Token for the **Finish** operation. |
| callback | AsyncCallback<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.|
## huks.finishSession<sup>9+</sup> ## huks.finishSession<sup>9+</sup>
...@@ -1275,8 +1274,7 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -1275,8 +1274,7 @@ Completes the key operation and releases resources. This API uses an asynchronou
| handle | number | Yes | Handle of the **Finish** operation. | | handle | number | Yes | Handle of the **Finish** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation. |
| token | Uint8Array | Yes | Token for the **Finish** operation. | | token | Uint8Array | Yes | Token for the **Finish** operation. |
| callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<[HuksReturnResult](#huksreturnresult9)> | Yes | Callback invoked to return the result.|
## huks.finishSession<sup>9+</sup> ## huks.finishSession<sup>9+</sup>
...@@ -1298,8 +1296,7 @@ Completes the key operation and releases resources. This API uses a promise to r ...@@ -1298,8 +1296,7 @@ Completes the key operation and releases resources. This API uses a promise to r
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksReturnResult](#huksreturnresult)> | Promise used to return the result.| | Promise\<[HuksReturnResult](#huksreturnresult9)> | Promise used to return the result.|
## huks.abortSession<sup>9+</sup> ## huks.abortSession<sup>9+</sup>
...@@ -1605,26 +1602,26 @@ For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcod ...@@ -1605,26 +1602,26 @@ For details about the error codes, see [KUKS Error Codes](../errorcodes/errorcod
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Description | Error Code | | Name | Value| Description |
| ---------------------------------------------- | --------------------------- | -------- | | ---------------------------------------------- | -------- |--------------------------- |
| HUKS_ERR_CODE_PERMISSION_FAIL | Permission verification failed. | 201 | | HUKS_ERR_CODE_PERMISSION_FAIL | 201 | Permission verification failed. |
| HUKS_ERR_CODE_ILLEGAL_ARGUMENT | Invalid parameters are detected. | 401 | | HUKS_ERR_CODE_ILLEGAL_ARGUMENT | 401 | Invalid parameters are detected. |
| HUKS_ERR_CODE_NOT_SUPPORTED_API | The API is not supported. | 801 | | HUKS_ERR_CODE_NOT_SUPPORTED_API | 801 | The API is not supported. |
| HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | The feature is not supported. | 12000001 | | HUKS_ERR_CODE_FEATURE_NOT_SUPPORTED | 12000001 | The feature is not supported. |
| HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | Key algorithm parameters are missing. | 12000002 | | HUKS_ERR_CODE_MISSING_CRYPTO_ALG_ARGUMENT | 12000002 | Key algorithm parameters are missing. |
| HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | Invalid key algorithm parameters are detected. | 12000003 | | HUKS_ERR_CODE_INVALID_CRYPTO_ALG_ARGUMENT | 12000003 | Invalid key algorithm parameters are detected. |
| HUKS_ERR_CODE_FILE_OPERATION_FAIL | The file operation failed. | 12000004 | | HUKS_ERR_CODE_FILE_OPERATION_FAIL | 12000004 | The file operation failed. |
| HUKS_ERR_CODE_COMMUNICATION_FAIL | The communication failed. | 12000005 | | HUKS_ERR_CODE_COMMUNICATION_FAIL | 12000005 | The communication failed. |
| HUKS_ERR_CODE_CRYPTO_FAIL | Failed to operate the algorithm library. | 12000006 | | HUKS_ERR_CODE_CRYPTO_FAIL | 12000006 | Failed to operate the algorithm library. |
| HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | Failed to access the key because the key has expired.| 12000007 | | HUKS_ERR_CODE_KEY_AUTH_PERMANENTLY_INVALIDATED | 12000007 | Failed to access the key because the key has expired.|
| HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | Failed to access the key because the authentication has failed.| 12000008 | | HUKS_ERR_CODE_KEY_AUTH_VERIFY_FAILED | 12000008 | Failed to access the key because the authentication has failed.|
| HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | Key access timed out.| 12000009 | | HUKS_ERR_CODE_KEY_AUTH_TIME_OUT | 12000009 | Key access timed out.|
| HUKS_ERR_CODE_SESSION_LIMIT | The number of key operation sessions has reached the limit. | 12000010 | | HUKS_ERR_CODE_SESSION_LIMIT | 12000010 | The number of key operation sessions has reached the limit. |
| HUKS_ERR_CODE_ITEM_NOT_EXIST | The target object does not exist. | 12000011 | | HUKS_ERR_CODE_ITEM_NOT_EXIST | 12000011 | The target object does not exist. |
| HUKS_ERR_CODE_EXTERNAL_ERROR | An external error occurs. | 12000012 | | HUKS_ERR_CODE_EXTERNAL_ERROR | 12000012 | An external error occurs. |
| HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | The credential does not exist. | 12000013 | | HUKS_ERR_CODE_CREDENTIAL_NOT_EXIST | 12000013 | The credential does not exist. |
| HUKS_ERR_CODE_INSUFFICIENT_MEMORY | The memory is insufficient. | 12000014 | | HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 12000014 | The memory is insufficient. |
| HUKS_ERR_CODE_CALL_SERVICE_FAILED | Failed to call other system services. | 12000015 | | HUKS_ERR_CODE_CALL_SERVICE_FAILED | 12000015 | Failed to call other system services. |
## HuksKeyPurpose ## HuksKeyPurpose
...@@ -1710,7 +1707,7 @@ Enumerates the key sizes. ...@@ -1710,7 +1707,7 @@ Enumerates the key sizes.
| HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits | | HUKS_ECC_KEY_SIZE_384 | 384 | ECC key of 384 bits |
| HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits | | HUKS_ECC_KEY_SIZE_521 | 521 | ECC key of 521 bits |
| HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits | | HUKS_AES_KEY_SIZE_128 | 128 | Advanced Encryption Standard (AES) key of 128 bits |
| HUKS_AES_KEY_SIZE_192 | 196 | AES key of 196 bits | | HUKS_AES_KEY_SIZE_192 | 192 | AES key of 192 bits |
| HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits | | HUKS_AES_KEY_SIZE_256 | 256 | AES key of 256 bits |
| HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits | | HUKS_AES_KEY_SIZE_512 | 512 | AES key of 512 bits |
| HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits| | HUKS_CURVE25519_KEY_SIZE_256 | 256 | Curve25519 key of 256 bits|
...@@ -1983,7 +1980,7 @@ generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<Huk ...@@ -1983,7 +1980,7 @@ generateKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<Huk
Generates a key. This API uses an asynchronous callback to return the result. Generates a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -1993,7 +1990,7 @@ Generates a key. This API uses an asynchronous callback to return the result. ...@@ -1993,7 +1990,7 @@ Generates a key. This API uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Alias of the key. | | keyAlias | string | Yes | Alias of the key. |
| options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. | | options | [HuksOptions](#huksoptions) | Yes | Tags required for generating the key. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code defined in **HuksResult** is returned.|
**Example** **Example**
...@@ -2035,7 +2032,7 @@ generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -2035,7 +2032,7 @@ generateKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Generates a key. This API uses a promise to return the result. Generates a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.generateKeyItem<sup>9+</sup>](#huksgeneratekeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2050,7 +2047,7 @@ Generates a key. This API uses a promise to return the result. ...@@ -2050,7 +2047,7 @@ Generates a key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2082,14 +2079,13 @@ let options = { ...@@ -2082,14 +2079,13 @@ let options = {
let result = huks.generateKey(keyAlias, options); let result = huks.generateKey(keyAlias, options);
``` ```
## huks.deleteKey<sup>(deprecated)</sup> ## huks.deleteKey<sup>(deprecated)</sup>
deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void deleteKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Deletes a key. This API uses an asynchronous callback to return the result. Deletes a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2099,7 +2095,7 @@ Deletes a key. This API uses an asynchronous callback to return the result. ...@@ -2099,7 +2095,7 @@ Deletes a key. This API uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | -------------------------------------------------- | | -------- | ----------------------------------------- | ---- | -------------------------------------------------- |
| keyAlias | string | Yes | Key alias passed in when the key was generated. | | keyAlias | string | Yes | Key alias passed in when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2118,7 +2114,7 @@ deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -2118,7 +2114,7 @@ deleteKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Deletes a key. This API uses a promise to return the result. Deletes a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.deleteKeyItem<sup>9+</sup>](#huksdeletekeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2133,7 +2129,7 @@ Deletes a key. This API uses a promise to return the result. ...@@ -2133,7 +2129,7 @@ Deletes a key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2146,14 +2142,13 @@ let emptyOptions = { ...@@ -2146,14 +2142,13 @@ let emptyOptions = {
let result = huks.deleteKey(keyAlias, emptyOptions); let result = huks.deleteKey(keyAlias, emptyOptions);
``` ```
## huks.importKey<sup>(deprecated)</sup> ## huks.importKey<sup>(deprecated)</sup>
importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void importKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Imports a key in plaintext. This API uses an asynchronous callback to return the result. Imports a key in plaintext. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2163,7 +2158,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the ...@@ -2163,7 +2158,7 @@ Imports a key in plaintext. This API uses an asynchronous callback to return the
| -------- | ------------------------ | ---- | ------------------------------------------------- | | -------- | ------------------------ | ---- | ------------------------------------------------- |
| keyAlias | string | Yes | Alias of the key.| | keyAlias | string | Yes | Alias of the key.|
| options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.| | options | [HuksOptions](#huksoptions) | Yes | Tags required for the import and key to import.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2213,7 +2208,7 @@ importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -2213,7 +2208,7 @@ importKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Imports a key in plaintext. This API uses a promise to return the result. Imports a key in plaintext. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.importKeyItem<sup>9+</sup>](#huksimportkeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2228,7 +2223,7 @@ Imports a key in plaintext. This API uses a promise to return the result. ...@@ -2228,7 +2223,7 @@ Imports a key in plaintext. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2274,14 +2269,13 @@ let huksoptions = { ...@@ -2274,14 +2269,13 @@ let huksoptions = {
let result = huks.importKey(keyAlias, huksoptions); let result = huks.importKey(keyAlias, huksoptions);
``` ```
## huks.exportKey<sup>(deprecated)</sup> ## huks.exportKey<sup>(deprecated)</sup>
exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void exportKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Exports a key. This API uses an asynchronous callback to return the result. Exports a key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2291,7 +2285,7 @@ Exports a key. This API uses an asynchronous callback to return the result. ...@@ -2291,7 +2285,7 @@ Exports a key. This API uses an asynchronous callback to return the result.
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned.|
**Example** **Example**
...@@ -2310,7 +2304,7 @@ exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -2310,7 +2304,7 @@ exportKey(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Exports a key. This API uses a promise to return the result. Exports a key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.exportKeyItem<sup>9+</sup>](#huksexportkeyitem9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2325,7 +2319,7 @@ Exports a key. This API uses a promise to return the result. ...@@ -2325,7 +2319,7 @@ Exports a key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | ------------------------------------------------------------ | | ----------------------------------- | ------------------------------------------------------------ |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. | | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result. If the operation is successful, **HUKS_SUCCESS** is returned and **outData** contains the public key exported. If the operation fails, an error code is returned. |
**Example** **Example**
...@@ -2338,14 +2332,13 @@ let emptyOptions = { ...@@ -2338,14 +2332,13 @@ let emptyOptions = {
let result = huks.exportKey(keyAlias, emptyOptions); let result = huks.exportKey(keyAlias, emptyOptions);
``` ```
## huks.getKeyProperties<sup>(deprecated)</sup> ## huks.getKeyProperties<sup>(deprecated)</sup>
getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void getKeyProperties(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Obtains key properties. This API uses an asynchronous callback to return the result. Obtains key properties. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2355,7 +2348,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res ...@@ -2355,7 +2348,7 @@ Obtains key properties. This API uses an asynchronous callback to return the res
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. | | keyAlias | string | Yes | Key alias, which must be the same as the alias used when the key was generated. |
| options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). | | options | [HuksOptions](#huksoptions) | Yes | Empty object (leave this parameter empty). |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **errorCode** is **HUKS_SUCCESS**; otherwise, an error code is returned.|
**Example** **Example**
...@@ -2374,7 +2367,7 @@ getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult> ...@@ -2374,7 +2367,7 @@ getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\<HuksResult>
Obtains key properties. This API uses a promise to return the result. Obtains key properties. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.getKeyItemProperties<sup>9+</sup>](#huksgetkeyitemproperties9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2402,14 +2395,13 @@ let emptyOptions = { ...@@ -2402,14 +2395,13 @@ let emptyOptions = {
let result = huks.getKeyProperties(keyAlias, emptyOptions); let result = huks.getKeyProperties(keyAlias, emptyOptions);
``` ```
## huks.isKeyExist<sup>(deprecated)</sup> ## huks.isKeyExist<sup>(deprecated)</sup>
isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void isKeyExist(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<boolean>) : void
Checks whether a key exists. This API uses an asynchronous callback to return the result. Checks whether a key exists. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2438,7 +2430,7 @@ isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean> ...@@ -2438,7 +2430,7 @@ isKeyExist(keyAlias: string, options: HuksOptions) : Promise\<boolean>
Checks whether a key exists. This API uses a promise to return the result. Checks whether a key exists. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.isKeyItemExist<sup>9+</sup>](#huksiskeyitemexist9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2453,7 +2445,7 @@ Checks whether a key exists. This API uses a promise to return the result. ...@@ -2453,7 +2445,7 @@ Checks whether a key exists. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------- | --------------------------------------- | | ----------------- | --------------------------------------- |
| Promise\<boolean> | Promise used to return the result. **TRUE** means that the key exists; **FALSE** means the opposite.| | Promise\<boolean> | Promise used to return the result. The value **TRUE** means that the key exists; **FALSE** means the opposite.|
**Example** **Example**
...@@ -2472,7 +2464,7 @@ init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle ...@@ -2472,7 +2464,7 @@ init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksHandle
Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2482,8 +2474,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback ...@@ -2482,8 +2474,7 @@ Initializes the data for a key operation. This API uses an asynchronous callback
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| keyAlias | string | Yes | Alias of the target key.| | keyAlias | string | Yes | Alias of the target key.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.| | options | [HuksOptions](#huksoptions) | Yes | Parameters used for initialization.|
| callback | AsyncCallback\<[HuksHandle](#hukshandle)> | Yes | Callback invoked to return the key operation handle.| | callback | AsyncCallback\<[HuksHandle](#hukshandledeprecated)> | Yes | Callback invoked to return the handle obtained through the initialization operation.|
## huks.init<sup>(deprecated)</sup> ## huks.init<sup>(deprecated)</sup>
...@@ -2491,7 +2482,7 @@ init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle> ...@@ -2491,7 +2482,7 @@ init(keyAlias: string, options: HuksOptions) : Promise\<HuksHandle>
Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Initializes the data for a key operation. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.initSession<sup>9+</sup>](#huksinitsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2506,34 +2497,15 @@ Initializes the data for a key operation. This API uses a promise to return the ...@@ -2506,34 +2497,15 @@ Initializes the data for a key operation. This API uses a promise to return the
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksHandle](#hukshandle)> | Promise used to return the key operation handle.| | Promise\<[HuksHandle](#hukshandledeprecated)> | Promise used to return the handle obtained through the initialization operation.|
## huks.update<sup>(deprecated)</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\<HuksResult>) : void
Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-1).
**System capability**: SystemCapability.Security.Huks
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | -------------------------------------------- |
| handle | number | Yes | Handle of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.|
## huks.update<sup>(deprecated)</sup>
update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksResult>) : void
Updates the key operation by segment. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2544,15 +2516,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to ...@@ -2544,15 +2516,15 @@ Updates the key operation by segment. This API uses an asynchronous callback to
| handle | number | Yes | Handle of the **Update** operation. | | handle | number | Yes | Handle of the **Update** operation. |
| token | Uint8Array | No | Token of the **Update** operation. | | token | Uint8Array | No | Token of the **Update** operation. |
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. | | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Update** operation. |
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback invoked to return the result.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes | Callback invoked to return the result.|
## huks.update<sup>(deprecated)</sup> ## huks.update<sup>(deprecated)</sup>
update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\<HuksResult> update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\<HuksResult>;
Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Updates the key operation by segment. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-2). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.updateSession<sup>9+</sup>](#huksupdatesession9-2).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2568,8 +2540,7 @@ Updates the key operation by segment. This API uses a promise to return the resu ...@@ -2568,8 +2540,7 @@ Updates the key operation by segment. This API uses a promise to return the resu
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.|
## huks.finish<sup>(deprecated)</sup> ## huks.finish<sup>(deprecated)</sup>
...@@ -2577,7 +2548,7 @@ finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult ...@@ -2577,7 +2548,7 @@ finish(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult
Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Completes the key operation and releases resources. This API uses an asynchronous callback to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2587,8 +2558,7 @@ Completes the key operation and releases resources. This API uses an asynchronou ...@@ -2587,8 +2558,7 @@ Completes the key operation and releases resources. This API uses an asynchronou
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Finish** operation.| | handle | number | Yes | Handle of the **Finish** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Finish** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the result.|
## huks.finish<sup>(deprecated)</sup> ## huks.finish<sup>(deprecated)</sup>
...@@ -2596,7 +2566,7 @@ finish(handle: number, options: HuksOptions) : Promise\<HuksResult> ...@@ -2596,7 +2566,7 @@ finish(handle: number, options: HuksOptions) : Promise\<HuksResult>
Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together. Completes the key operation and releases resources. This API uses a promise to return the result. **huks.init**, **huks.update**, and **huks.finish** must be used together.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.finishSession<sup>9+</sup>](#huksfinishsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2611,8 +2581,7 @@ Completes the key operation and releases resources. This API uses a promise to r ...@@ -2611,8 +2581,7 @@ Completes the key operation and releases resources. This API uses a promise to r
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.|
## huks.abort<sup>(deprecated)</sup> ## huks.abort<sup>(deprecated)</sup>
...@@ -2620,7 +2589,7 @@ abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult> ...@@ -2620,7 +2589,7 @@ abort(handle: number, options: HuksOptions, callback: AsyncCallback\<HuksResult>
Aborts the use of the key. This API uses an asynchronous callback to return the result. Aborts the use of the key. This API uses an asynchronous callback to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2630,7 +2599,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the ...@@ -2630,7 +2599,7 @@ Aborts the use of the key. This API uses an asynchronous callback to return the
| -------- | ---------------------- | ---- | ------------------------------------- | | -------- | ---------------------- | ---- | ------------------------------------- |
| handle | number | Yes | Handle of the **Abort** operation.| | handle | number | Yes | Handle of the **Abort** operation.|
| options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.| | options | [HuksOptions](#huksoptions) | Yes | Parameters of the **Abort** operation.|
| callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes| Callback invoked to return the result.| | callback | AsyncCallback\<[HuksResult](#huksresultdeprecated)> | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -2731,7 +2700,7 @@ abort(handle: number, options: HuksOptions) : Promise\<HuksResult>; ...@@ -2731,7 +2700,7 @@ abort(handle: number, options: HuksOptions) : Promise\<HuksResult>;
Aborts the use of the key. This API uses a promise to return the result. Aborts the use of the key. This API uses a promise to return the result.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9-1). > **NOTE**<br>This API is deprecated since API version 9. You are advised to use [huks.abortSession<sup>9+</sup>](#huksabortsession9-1).
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
...@@ -2746,7 +2715,7 @@ Aborts the use of the key. This API uses a promise to return the result. ...@@ -2746,7 +2715,7 @@ Aborts the use of the key. This API uses a promise to return the result.
| Type | Description | | Type | Description |
| ----------------------------------- | -------------------------------------------------- | | ----------------------------------- | -------------------------------------------------- |
| Promise\<[HuksResult](#huksresult)> | Promise used to return the result.| | Promise\<[HuksResult](#huksresultdeprecated)> | Promise used to return the result.|
**Example** **Example**
...@@ -2847,7 +2816,6 @@ function huksAbort() { ...@@ -2847,7 +2816,6 @@ function huksAbort() {
} }
``` ```
## HuksHandle<sup>(deprecated)</sup> ## HuksHandle<sup>(deprecated)</sup>
Defines the HUKS handle structure. Defines the HUKS handle structure.
...@@ -2858,8 +2826,7 @@ Defines the HUKS handle structure. ...@@ -2858,8 +2826,7 @@ Defines the HUKS handle structure.
| ---------- | ---------------- | ---- | -------- | | ---------- | ---------------- | ---- | -------- |
| errorCode | number | Yes | Error code.| | errorCode | number | Yes | Error code.|
| handle | number | Yes| Value of the handle.| | handle | number | Yes| Value of the handle.|
| token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| | token | Uint8Array | No| Challenge obtained after the [init](#huksinitdeprecated) operation.|
## HuksResult<sup>(deprecated)</sup> ## HuksResult<sup>(deprecated)</sup>
...@@ -2867,8 +2834,6 @@ Defines the **HuksResult** structure. ...@@ -2867,8 +2834,6 @@ Defines the **HuksResult** structure.
**System capability**: SystemCapability.Security.Huks **System capability**: SystemCapability.Security.Huks
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ---------- | ------------------------------- | ---- | ---------------- | | ---------- | ------------------------------- | ---- | ---------------- |
| errorCode | number | Yes | Error code. | | errorCode | number | Yes | Error code. |
......
# Standard NFC # @ohos.nfc.controller (Standard NFC)
The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state.
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## **Modules to Import**
``` ```js
import controller from '@ohos.nfc.controller'; import controller from '@ohos.nfc.controller';
``` ```
...@@ -18,7 +18,7 @@ Enumerates the NFC states. ...@@ -18,7 +18,7 @@ Enumerates the NFC states.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
| Name| Default Value| Description| | Name| Value| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| STATE_OFF | 1 | NFC is closed (OFF).| | STATE_OFF | 1 | NFC is closed (OFF).|
| STATE_TURNING_ON | 2 | NFC is turning on.| | STATE_TURNING_ON | 2 | NFC is turning on.|
...@@ -31,6 +31,10 @@ isNfcAvailable(): boolean ...@@ -31,6 +31,10 @@ isNfcAvailable(): boolean
Checks whether the device supports NFC. Checks whether the device supports NFC.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use canIUse("SystemCapability.Communication.NFC.Core").
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -46,6 +50,10 @@ openNfc(): boolean ...@@ -46,6 +50,10 @@ openNfc(): boolean
Opens NFC. Opens NFC.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [enableNfc](#controllerenablenfc9).
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS **Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
...@@ -56,12 +64,34 @@ Opens NFC. ...@@ -56,12 +64,34 @@ Opens NFC.
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## controller.enableNfc<sup>9+</sup>
enableNfc(): boolean
Enables NFC.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
**System capability**: SystemCapability.Communication.NFC.Core
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100101 | NFC state is abnormal in service. |
## controller.closeNfc ## controller.closeNfc
closeNfc(): boolean closeNfc(): boolean
Closes NFC. Closes NFC.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [disableNfc](#controllerdisablenfc9).
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS **Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
...@@ -72,6 +102,24 @@ Closes NFC. ...@@ -72,6 +102,24 @@ Closes NFC.
| -------- | ------------------------------------------- | | -------- | ------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## controller.disableNfc<sup>9+</sup>
disableNfc(): boolean
Disables NFC.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS
**System capability**: SystemCapability.Communication.NFC.Core
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100101 | NFC state is abnormal in service. |
## controller.isNfcOpen ## controller.isNfcOpen
isNfcOpen(): boolean isNfcOpen(): boolean
...@@ -108,14 +156,12 @@ Subscribes to NFC state changes. A callback will be invoked to return the NFC st ...@@ -108,14 +156,12 @@ Subscribes to NFC state changes. A callback will be invoked to return the NFC st
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameter** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.|
| callback | Callback&lt;[NfcState](#nfcstate)&gt; | Yes| Callback invoked to return the NFC state.| | callback | Callback&lt;[NfcState](#nfcstate)&gt; | Yes| Callback invoked to return the NFC state.|
## controller.off('nfcStateChange') ## controller.off('nfcStateChange')
...@@ -125,42 +171,55 @@ Unsubscribes from the NFC state changes. The subscriber will not receive NFC sta ...@@ -125,42 +171,55 @@ Unsubscribes from the NFC state changes. The subscriber will not receive NFC sta
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Core
**Parameter** **Parameters**
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.|
| callback | Callback&lt;[NfcState](#nfcstate)&gt; | No| Callback for the NFC state changes. This parameter can be left blank.| | callback | Callback&lt;[NfcState](#nfcstate)&gt; | No| Callback for the NFC state changes. This parameter can be left blank.|
**Example** **Example**
```js ```js
import controller from '@ohos.nfc.controller'; import controller from '@ohos.nfc.controller';
// Define a callback key.
var NFC_STATE_CALLBACK_KEY = "nfcStateChange";
// Register the callback to receive NFC state change notifications.
controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> {
if (err) {
console.log("controller on callback err: " + err);
} else {
console.log("controller on callback nfcState: " + nfcState);
}
});
// Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS.
if (!controller.isNfcOpen()) {
var ret = controller.openNfc();
console.log("controller openNfc ret: " + ret);
}
// Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. // Register a callback to receive the NFC state change notification.
if (controller.isNfcOpen()) { controller.on("nfcStateChange", (err, nfcState)=> {
var ret = controller.closeNfc(); if (err) {
console.log("controller closeNfc ret: " + ret); console.log("controller on callback err: " + err);
} else {
console.log("controller on callback nfcState: " + nfcState);
} }
});
// Unregister the callback.
controller.off(NFC_STATE_CALLBACK_KEY); // Open NFC. The ohos.permission.MANAGE_SECURE_SETTINGS permission is required.
``` if (!controller.isNfcOpen()) {
var ret = controller.openNfc();
console.log("controller openNfc ret: " + ret);
}
// Use 'enableNfc' to enable NFC from API version 9.
try {
controller.enableNfc();
console.log("controller enableNfc success");
} catch (busiError) {
console.log("controller enableNfc busiError: " + busiError);
}
// Close NFC. The ohos.permission.MANAGE_SECURE_SETTINGS permission is required.
if (controller.isNfcOpen()) {
var ret = controller.closeNfc();
console.log("controller closeNfc ret: " + ret);
}
// Use 'disableNfc' to disable NFC from API version 9.
try {
controller.disableNfc();
console.log("controller disableNfc success");
} catch (busiError) {
console.log("controller disableNfc busiError: " + busiError);
}
// Unregister the callback.
controller.off("nfcStateChange");
```
# @ohos.nfc.tag # @ohos.nfc.tag (Standard NFC Tags)
The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags.
...@@ -48,11 +48,11 @@ Before developing applications related to tag read and write, you must declare N ...@@ -48,11 +48,11 @@ Before developing applications related to tag read and write, you must declare N
} }
``` ```
> **CAUTION**<br> > **CAUTION**<br>
1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. >
2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. > - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed.
3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. > - The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed.
4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. > - The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure.
> - The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed.
## **Modules to Import** ## **Modules to Import**
```js ```js
...@@ -73,7 +73,7 @@ onCreate(want, launchParam) { ...@@ -73,7 +73,7 @@ onCreate(want, launchParam) {
try { try {
tagInfo = tag.getTagInfo(want); tagInfo = tag.getTagInfo(want);
} catch (error) { } catch (error) {
console.log("tag.getTagInfo catched error: " + error); console.log("tag.getTagInfo caught error: " + error);
} }
if (tagInfo == null || tagInfo == undefined) { if (tagInfo == null || tagInfo == undefined) {
console.log("no TagInfo to be created, ignore it."); console.log("no TagInfo to be created, ignore it.");
...@@ -100,7 +100,7 @@ onCreate(want, launchParam) { ...@@ -100,7 +100,7 @@ onCreate(want, launchParam) {
try { try {
nfcA = tag.getNfcATag(taginfo); nfcA = tag.getNfcATag(taginfo);
} catch (error) { } catch (error) {
console.log("tag.getNfcATag catched error: " + error); console.log("tag.getNfcATag caught error: " + error);
} }
// Other code to read or write this tag. // Other code to read or write this tag.
} }
...@@ -111,7 +111,7 @@ onCreate(want, launchParam) { ...@@ -111,7 +111,7 @@ onCreate(want, launchParam) {
try { try {
isoDep = tag.getIsoDep(taginfo); isoDep = tag.getIsoDep(taginfo);
} catch (error) { } catch (error) {
console.log("tag.getIsoDep catched error: " + error); console.log("tag.getIsoDep caught error: " + error);
} }
// Other code to read or write this tag. // Other code to read or write this tag.
} }
...@@ -126,9 +126,16 @@ getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) ...@@ -126,9 +126,16 @@ getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag)
Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology.
**Required permissions**: ohos.permission.NFC_TAG > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcA](#taggetnfca9).
**System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core **Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value** **Return value**
...@@ -136,15 +143,70 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- ...@@ -136,15 +143,70 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC-
| -------- | -------- | | -------- | -------- |
| [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.| | [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.|
## tag.getNfcA<sup>9+</sup>
getNfcA(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag)
Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology.
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| [NfcATag](js-apis-nfctech.md#nfcatag) | **NfcATag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcBTag ## tag.getNfcBTag
getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag)
Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology.
**Required permissions**: ohos.permission.NFC_TAG > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcB](#taggetnfcb9).
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
## tag.getNfcB<sup>9+</sup>
getNfcB(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag)
**System capability**: SystemCapability.Communication.NFC.Core Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology.
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value** **Return value**
...@@ -152,15 +214,30 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- ...@@ -152,15 +214,30 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-
| -------- | ---------------- | | -------- | ---------------- |
| [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.| | [NfcBTag](js-apis-nfctech.md#nfcbtag) | **NfcBTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcFTag ## tag.getNfcFTag
getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag)
Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology.
**Required permissions**: ohos.permission.NFC_TAG > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcF](#taggetnfcf9).
**System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core **Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value** **Return value**
...@@ -168,15 +245,70 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- ...@@ -168,15 +245,70 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-
| -------- | ---------------- | | -------- | ---------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.| | [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
## tag.getNfcF<sup>9+</sup>
getNfcF(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag)
Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology.
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcFTag](js-apis-nfctech.md#nfcftag) | **NfcFTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getNfcVTag ## tag.getNfcVTag
getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag)
Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology.
**Required permissions**: ohos.permission.NFC_TAG > **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getNfcV](#taggetnfcv9).
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value**
| **Type**| **Description** |
| -------- | ---------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
## tag.getNfcV<sup>9+</sup>
getNfcV(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag)
Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology.
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**.
**Return value** **Return value**
...@@ -184,19 +316,27 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- ...@@ -184,19 +316,27 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-
| -------- | ---------------- | | -------- | ---------------- |
| [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
## tag.getIsoDep<sup>9+</sup> ## tag.getIsoDep<sup>9+</sup>
getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) getIsoDep(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 )
Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- | | --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | | taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
...@@ -218,13 +358,13 @@ getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) ...@@ -218,13 +358,13 @@ getNdef(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9)
Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF).
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- | | --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | | taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
...@@ -242,11 +382,11 @@ For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode ...@@ -242,11 +382,11 @@ For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode
## tag.getMifareClassic<sup>9+</sup> ## tag.getMifareClassic<sup>9+</sup>
getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9)
Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -258,7 +398,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use ...@@ -258,7 +398,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use
| **Type**| **Description** | | **Type**| **Description** |
| ----------------- | ------------------------| | ----------------- | ------------------------|
| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) | **MifareClassicTag** object obtained.| | [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.|
**Error codes** **Error codes**
...@@ -274,12 +414,12 @@ getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis ...@@ -274,12 +414,12 @@ getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis
Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------- | ---- | ---------------------------------------- | | --------- | ------------------------- | ---- | ---------------------------------------- |
| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | | taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. |
**Return value** **Return value**
...@@ -301,7 +441,7 @@ getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfc ...@@ -301,7 +441,7 @@ getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfc
Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -323,7 +463,7 @@ getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo) ...@@ -323,7 +463,7 @@ getTagInfo(want: [Want](js-apis-app-ability-want.md#Want)): [TagInfo](#taginfo)
Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -344,7 +484,7 @@ makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); ...@@ -344,7 +484,7 @@ makeUriRecord(uri: string): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on the specified URI. Creates an NDEF record based on the specified URI.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -373,7 +513,7 @@ try { ...@@ -373,7 +513,7 @@ try {
console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord);
} }
} catch (busiError) { } catch (busiError) {
console.log("ndefMessage makeUriRecord catched busiError: " + busiError); console.log("ndefMessage makeUriRecord caught busiError: " + busiError);
} }
``` ```
...@@ -383,7 +523,7 @@ makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); ...@@ -383,7 +523,7 @@ makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9);
Creates an NDEF record based on the specified text data and encoding type. Creates an NDEF record based on the specified text data and encoding type.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -414,7 +554,7 @@ try { ...@@ -414,7 +554,7 @@ try {
console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord);
} }
} catch (busiError) { } catch (busiError) {
console.log("ndefMessage makeTextRecord catched busiError: " + busiError); console.log("ndefMessage makeTextRecord caught busiError: " + busiError);
} }
``` ```
...@@ -425,7 +565,7 @@ makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9) ...@@ -425,7 +565,7 @@ makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9)
Creates an NDEF record based on the specified MIME data and type. Creates an NDEF record based on the specified MIME data and type.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -456,7 +596,7 @@ try { ...@@ -456,7 +596,7 @@ try {
console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord);
} }
} catch (busiError) { } catch (busiError) {
console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); console.log("ndefMessage makeMimeRecord caught busiError: " + busiError);
} }
``` ```
## tag.ndef.makeExternalRecord<sup>9+</sup> ## tag.ndef.makeExternalRecord<sup>9+</sup>
...@@ -465,7 +605,7 @@ makeExternalRecord(domainName: string, type: string, externalData: number[]): [N ...@@ -465,7 +605,7 @@ makeExternalRecord(domainName: string, type: string, externalData: number[]): [N
Creates an NDEF record based on application-specific data. Creates an NDEF record based on application-specific data.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -498,7 +638,7 @@ try { ...@@ -498,7 +638,7 @@ try {
console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord);
} }
} catch (busiError) { } catch (busiError) {
console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); console.log("ndefMessage makeExternalRecord caught busiError: " + busiError);
} }
``` ```
...@@ -508,7 +648,7 @@ messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): num ...@@ -508,7 +648,7 @@ messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): num
Converts an NDEF message to bytes. Converts an NDEF message to bytes.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -540,7 +680,7 @@ try { ...@@ -540,7 +680,7 @@ try {
let rawData2 = tag.ndef.messageToBytes(ndefMessage); let rawData2 = tag.ndef.messageToBytes(ndefMessage);
console.log("ndefMessage messageToBytes rawData2: " + rawData2); console.log("ndefMessage messageToBytes rawData2: " + rawData2);
} catch (busiError) { } catch (busiError) {
console.log("ndefMessage messageToBytes catched busiError: " + busiError); console.log("ndefMessage messageToBytes caught busiError: " + busiError);
} }
``` ```
## tag.ndef.createNdefMessage<sup>9+</sup> ## tag.ndef.createNdefMessage<sup>9+</sup>
...@@ -549,7 +689,7 @@ createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9 ...@@ -549,7 +689,7 @@ createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9
Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty. Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -583,7 +723,7 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#n ...@@ -583,7 +723,7 @@ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#n
Creates an NDEF message from the NDEF records list. Creates an NDEF message from the NDEF records list.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -618,7 +758,7 @@ try { ...@@ -618,7 +758,7 @@ try {
Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. Defines the **TagInfo** object, which provides information about the tag technologies supported by a card.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
...@@ -626,14 +766,15 @@ Defines the **TagInfo** object, which provides information about the tag technol ...@@ -626,14 +766,15 @@ Defines the **TagInfo** object, which provides information about the tag technol
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| | uid<sup>9+</sup> | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
| technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| | technology<sup>9+</sup> | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.|
| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.| | supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [technology](#taginfo).|
| extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.| | extrasData<sup>9+</sup> | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.<br>**System API**: This is a system API.|
| tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.| | tagRfDiscId<sup>9+</sup> | number | Yes| No| ID allocated when the tag is discovered.<br>**System API**: This is a system API.|
| remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.| | remoteTagService<sup>9+</sup> | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.<br>**System API**: This is a system API.|
## NdefRecord<sup>9+</sup> ## NdefRecord<sup>9+</sup>
Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Type**| **Readable**| **Writable**| **Description**| | **Name**| **Type**| **Readable**| **Writable**| **Description**|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
...@@ -645,7 +786,7 @@ Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. ...@@ -645,7 +786,7 @@ Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*.
## Technology Type Definition ## Technology Type Definition
Enumerates the tag technology types. Enumerates the tag technology types.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -662,7 +803,7 @@ Enumerates the tag technology types. ...@@ -662,7 +803,7 @@ Enumerates the tag technology types.
## TnfType<sup>9+</sup> ## TnfType<sup>9+</sup>
Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -677,7 +818,7 @@ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. ...@@ -677,7 +818,7 @@ Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*.
## NDEF Record RTD ## NDEF Record RTD
Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -687,7 +828,7 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ...@@ -687,7 +828,7 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND
## NfcForumType<sup>9+</sup> ## NfcForumType<sup>9+</sup>
Enumerates the NFC Forum tag types. Enumerates the NFC Forum tag types.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -700,7 +841,7 @@ Enumerates the NFC Forum tag types. ...@@ -700,7 +841,7 @@ Enumerates the NFC Forum tag types.
## MifareClassicType<sup>9+</sup> ## MifareClassicType<sup>9+</sup>
Enumerates the MIFARE Classic tag types. Enumerates the MIFARE Classic tag types.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -710,9 +851,9 @@ Enumerates the MIFARE Classic tag types. ...@@ -710,9 +851,9 @@ Enumerates the MIFARE Classic tag types.
| TYPE_PRO | 3 | MIFARE Pro.| | TYPE_PRO | 3 | MIFARE Pro.|
## MifareClassicSize<sup>9+</sup> ## MifareClassicSize<sup>9+</sup>
Enumerates the sizes of MIFARE Classic tags. Enumerates the sizes of a MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -724,11 +865,11 @@ Enumerates the sizes of MIFARE Classic tags. ...@@ -724,11 +865,11 @@ Enumerates the sizes of MIFARE Classic tags.
## MifareUltralightType<sup>9+</sup> ## MifareUltralightType<sup>9+</sup>
Enumerates the MIFARE Ultralight tag types. Enumerates the MIFARE Ultralight tag types.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
| **Name**| **Value**| **Description**| | **Name**| **Value**| **Description**|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| TYPE_UNKNOWN | 0 | Unknown type.| | TYPE_UNKNOWN | 0 | Unknown type.|
| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| | TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.|
| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| | TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.|
<!--no_check-->
# nfctech # nfctech (Standard NFC Technologies)
The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies.
...@@ -26,9 +26,7 @@ getSak(): number ...@@ -26,9 +26,7 @@ getSak(): number
Obtains the SAK value of this NFC-A tag. Obtains the SAK value of this NFC-A tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -52,9 +50,7 @@ getAtqa(): number[] ...@@ -52,9 +50,7 @@ getAtqa(): number[]
Obtains the ATQA value of this NFC-A tag. Obtains the ATQA value of this NFC-A tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -86,9 +82,7 @@ getRespAppData(): number[] ...@@ -86,9 +82,7 @@ getRespAppData(): number[]
Obtains the application data of this NFC-B tag. Obtains the application data of this NFC-B tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -112,9 +106,7 @@ getRespProtocol(): number[] ...@@ -112,9 +106,7 @@ getRespProtocol(): number[]
Obtains the protocol information of this NFC-B tag. Obtains the protocol information of this NFC-B tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -146,9 +138,7 @@ getSystemCode(): number[] ...@@ -146,9 +138,7 @@ getSystemCode(): number[]
Obtains the system code from this NFC-F tag. Obtains the system code from this NFC-F tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -172,9 +162,7 @@ getPmm(): number[] ...@@ -172,9 +162,7 @@ getPmm(): number[]
Obtains the PMm (consisting of the IC code and manufacturer parameters) information from this NFC-F tag. Obtains the PMm (consisting of the IC code and manufacturer parameters) information from this NFC-F tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -206,9 +194,7 @@ getResponseFlags(): number ...@@ -206,9 +194,7 @@ getResponseFlags(): number
Obtains the response flags from this NFC-V tag. Obtains the response flags from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -232,9 +218,7 @@ getDsfId(): number ...@@ -232,9 +218,7 @@ getDsfId(): number
Obtains the data storage format identifier (DSFID) from this NFC-V tag. Obtains the data storage format identifier (DSFID) from this NFC-V tag.
**Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Tag
**System capability**: SystemCapability.Communication.NFC.Core
**Return value** **Return value**
...@@ -266,7 +250,7 @@ getHistoricalBytes(): number[] ...@@ -266,7 +250,7 @@ getHistoricalBytes(): number[]
Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology. Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -290,7 +274,7 @@ getHiLayerResponse(): number[] ...@@ -290,7 +274,7 @@ getHiLayerResponse(): number[]
Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology. Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -316,7 +300,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T ...@@ -316,7 +300,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -367,7 +351,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call ...@@ -367,7 +351,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -419,7 +403,7 @@ getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] ...@@ -419,7 +403,7 @@ getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[]
Obtains all NDEF records. Obtains all NDEF records.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -454,7 +438,7 @@ getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) ...@@ -454,7 +438,7 @@ getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)
Obtains the NDEF tag type. Obtains the NDEF tag type.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -478,7 +462,7 @@ getNdefMessage(): [NdefMessage](#ndefmessage9) ...@@ -478,7 +462,7 @@ getNdefMessage(): [NdefMessage](#ndefmessage9)
Obtains the NDEF message from this NDEF tag. Obtains the NDEF message from this NDEF tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -501,7 +485,7 @@ isNdefWritable(): boolean; ...@@ -501,7 +485,7 @@ isNdefWritable(): boolean;
Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported. Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -527,7 +511,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu ...@@ -527,7 +511,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -577,7 +561,7 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to ...@@ -577,7 +561,7 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -629,7 +613,7 @@ Writes an NDEF message to this tag. This API uses a promise to return the result ...@@ -629,7 +613,7 @@ Writes an NDEF message to this tag. This API uses a promise to return the result
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -682,7 +666,7 @@ Writes an NDEF message to this tag. This API uses an asynchronous callback to re ...@@ -682,7 +666,7 @@ Writes an NDEF message to this tag. This API uses an asynchronous callback to re
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -738,7 +722,7 @@ Checks whether this NDEF tag can be set to read-only. ...@@ -738,7 +722,7 @@ Checks whether this NDEF tag can be set to read-only.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -772,7 +756,7 @@ Sets this NDEF tag to read-only. This API uses a promise to return the result. ...@@ -772,7 +756,7 @@ Sets this NDEF tag to read-only. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Error codes** **Error codes**
...@@ -816,7 +800,7 @@ Sets this NDEF tag to read-only. This API uses an asynchronous callback to retur ...@@ -816,7 +800,7 @@ Sets this NDEF tag to read-only. This API uses an asynchronous callback to retur
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -866,7 +850,7 @@ getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): ...@@ -866,7 +850,7 @@ getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)):
Converts an NFC Forum Type tag to a string defined in the NFC Forum. Converts an NFC Forum Type tag to a string defined in the NFC Forum.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -911,7 +895,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au ...@@ -911,7 +895,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -965,7 +949,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au ...@@ -965,7 +949,7 @@ Authenticates a sector using a key. The sector can be accessed only after the au
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1021,7 +1005,7 @@ Reads a block (16 bytes) on this tag. This API uses a promise to return the resu ...@@ -1021,7 +1005,7 @@ Reads a block (16 bytes) on this tag. This API uses a promise to return the resu
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1078,14 +1062,14 @@ Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to ...@@ -1078,14 +1062,14 @@ Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- | | -------- | ----------------------- | ---- | -------------------------------------- |
| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| | blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.|
| callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the block read.| | callback | AsyncCallback\<number[]> | Yes | Callback invoked to return the data read.|
**Error codes** **Error codes**
...@@ -1132,7 +1116,7 @@ Writes data to a block on this tag. This API uses a promise to return the result ...@@ -1132,7 +1116,7 @@ Writes data to a block on this tag. This API uses a promise to return the result
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1186,7 +1170,7 @@ Writes data to a block on this tag. This API uses an asynchronous callback to re ...@@ -1186,7 +1170,7 @@ Writes data to a block on this tag. This API uses an asynchronous callback to re
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1243,7 +1227,7 @@ Increments a block with data. This API uses a promise to return the result. ...@@ -1243,7 +1227,7 @@ Increments a block with data. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1296,7 +1280,7 @@ Increments a block with data. This API uses an asynchronous callback to return t ...@@ -1296,7 +1280,7 @@ Increments a block with data. This API uses an asynchronous callback to return t
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1352,7 +1336,7 @@ Decrements a block. This API uses a promise to return the result. ...@@ -1352,7 +1336,7 @@ Decrements a block. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1405,7 +1389,7 @@ Decrements a block. This API uses an asynchronous callback to return the result. ...@@ -1405,7 +1389,7 @@ Decrements a block. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1461,7 +1445,7 @@ Transfers data from the temporary register to a block. This API uses a promise t ...@@ -1461,7 +1445,7 @@ Transfers data from the temporary register to a block. This API uses a promise t
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1512,7 +1496,7 @@ Transfers data from the temporary register to a block. This API uses an asynchro ...@@ -1512,7 +1496,7 @@ Transfers data from the temporary register to a block. This API uses an asynchro
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1566,7 +1550,7 @@ Restores data in the temporary register from a block. This API uses a promise to ...@@ -1566,7 +1550,7 @@ Restores data in the temporary register from a block. This API uses a promise to
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1617,7 +1601,7 @@ Restores data in the temporary register from a block. This API uses an asynchron ...@@ -1617,7 +1601,7 @@ Restores data in the temporary register from a block. This API uses an asynchron
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1669,7 +1653,7 @@ getSectorCount(): number ...@@ -1669,7 +1653,7 @@ getSectorCount(): number
Obtains the number of sectors in this MIFARE Classic tag. Obtains the number of sectors in this MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -1693,7 +1677,7 @@ getBlockCountInSector(sectorIndex: number): number ...@@ -1693,7 +1677,7 @@ getBlockCountInSector(sectorIndex: number): number
Obtains the number of blocks in a sector. Obtains the number of blocks in a sector.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1729,7 +1713,7 @@ getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) ...@@ -1729,7 +1713,7 @@ getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9)
Obtains the type of this MIFARE Classic tag. Obtains the type of this MIFARE Classic tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -1753,7 +1737,7 @@ getTagSize(): number ...@@ -1753,7 +1737,7 @@ getTagSize(): number
Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9).
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -1777,7 +1761,7 @@ isEmulatedTag(): boolean ...@@ -1777,7 +1761,7 @@ isEmulatedTag(): boolean
Checks whether it is an emulated tag. Checks whether it is an emulated tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -1801,7 +1785,7 @@ getBlockIndex(sectorIndex: number): number ...@@ -1801,7 +1785,7 @@ getBlockIndex(sectorIndex: number): number
Obtains the index of the first block in a sector. Obtains the index of the first block in a sector.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1835,9 +1819,9 @@ try { ...@@ -1835,9 +1819,9 @@ try {
getSectorIndex(blockIndex: number): number getSectorIndex(blockIndex: number): number
Obtains the index of a sector that holds the specified block. Obtains the index of the sector that holds the specified block.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1883,7 +1867,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses a promise to re ...@@ -1883,7 +1867,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses a promise to re
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1941,7 +1925,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous ...@@ -1941,7 +1925,7 @@ Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -1995,7 +1979,7 @@ Writes one page (4 bytes) of data to this tag. This API uses a promise to return ...@@ -1995,7 +1979,7 @@ Writes one page (4 bytes) of data to this tag. This API uses a promise to return
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -2048,7 +2032,7 @@ Writes one page (4 bytes) of data to this tag. This API uses an asynchronous cal ...@@ -2048,7 +2032,7 @@ Writes one page (4 bytes) of data to this tag. This API uses an asynchronous cal
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -2102,7 +2086,7 @@ getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) ...@@ -2102,7 +2086,7 @@ getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9)
Obtains the type of this MIFARE Ultralight tag. Obtains the type of this MIFARE Ultralight tag.
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -2136,7 +2120,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses ...@@ -2136,7 +2120,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -2190,7 +2174,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses ...@@ -2190,7 +2174,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -2245,7 +2229,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the ...@@ -2245,7 +2229,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -2299,7 +2283,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ...@@ -2299,7 +2283,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
......
# @ohos.account.osAccount # @ohos.account.osAccount (OS Account Management)
The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account.
...@@ -155,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous ...@@ -155,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------ | | -------- | ---------------------------- | ---- | ------------------------------------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.|
**Error codes** **Error codes**
...@@ -192,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re ...@@ -192,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
| Type | Description | | Type | Description |
| :--------------------- | :--------------------------------------------------------- | | :--------------------- | :--------------------------------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.|
**Error codes** **Error codes**
...@@ -483,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous ...@@ -483,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------------- | | -------- | ---------------------------- | ---- | ------------------------------------------------------------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. If true is returned, the current account has been verified. If false is returned, the current account has not been verified.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.|
**Error codes** **Error codes**
...@@ -1690,7 +1690,7 @@ Creates an OS account and associates it with the specified domain account. This ...@@ -1690,7 +1690,7 @@ Creates an OS account and associates it with the specified domain account. This
| Type | Description | | Type | Description |
| ---------------------------------------------- | -------------------------------------- | | ---------------------------------------------- | -------------------------------------- |
| Promise&lt;[OsAccountInfo](#osaccountinfo)&gt; | Promise used to return the OS account created.| | Promise&lt;[OsAccountInfo](#osaccountinfo)&gt; | Promise used to return the information about the created OS account.|
**Error codes** **Error codes**
...@@ -2709,6 +2709,7 @@ Obtains the constraint source information of an OS account. This API uses a prom ...@@ -2709,6 +2709,7 @@ Obtains the constraint source information of an OS account. This API uses a prom
console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e));
} }
``` ```
### isMultiOsAccountEnable<sup>(deprecated)</sup> ### isMultiOsAccountEnable<sup>(deprecated)</sup>
isMultiOsAccountEnable(callback: AsyncCallback&lt;boolean&gt;): void isMultiOsAccountEnable(callback: AsyncCallback&lt;boolean&gt;): void
...@@ -2725,7 +2726,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous ...@@ -2725,7 +2726,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ------------------------------------------------------ | | -------- | ---------------------------- | ---- | ------------------------------------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.|
**Example** **Example**
...@@ -2756,7 +2757,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re ...@@ -2756,7 +2757,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re
| Type | Description | | Type | Description |
| :--------------------- | :--------------------------------------------------------- | | :--------------------- | :--------------------------------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value **false** means the opposite.|
**Example** **Example**
...@@ -3694,7 +3695,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac ...@@ -3694,7 +3695,7 @@ Obtains the OS account ID based on the SN. This API uses an asynchronous callbac
getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise&lt;number&gt; getOsAccountLocalIdBySerialNumber(serialNumber: number): Promise&lt;number&gt;
Obtains the OS account ID based on the SN. This API uses a promise to return the result. Obtains the OS account ID based on the serial number. This API uses a promise to return the result.
> **NOTE** > **NOTE**
> >
...@@ -4360,7 +4361,7 @@ Register a credential inputer. ...@@ -4360,7 +4361,7 @@ Register a credential inputer.
let authType = account_osAccount.AuthType.DOMAIN; let authType = account_osAccount.AuthType.DOMAIN;
let password = new Uint8Array([0, 0, 0, 0, 0]); let password = new Uint8Array([0, 0, 0, 0, 0]);
try { try {
InputerMgr.registerInputer(authType, { inputerMgr.registerInputer(authType, {
onGetData: (authSubType, callback) => { onGetData: (authSubType, callback) => {
callback.onSetData(authSubType, password); callback.onSetData(authSubType, password);
} }
......
# @ohos.rpc (RPC) # @ohos.rpc (RPC)
The **rpc** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver. The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> This module supports return of error codes since API version 9. > - This module supports return of error codes since API version 9.
## Modules to Import ## Modules to Import
...@@ -15,7 +14,6 @@ The **rpc** module implements communication between processes, including inter-p ...@@ -15,7 +14,6 @@ The **rpc** module implements communication between processes, including inter-p
import rpc from '@ohos.rpc'; import rpc from '@ohos.rpc';
``` ```
## ErrorCode<sup>9+</sup> ## ErrorCode<sup>9+</sup>
The APIs of this module return exceptions since API version 9. The following table lists the error codes. The APIs of this module return exceptions since API version 9. The following table lists the error codes.
...@@ -42,11 +40,11 @@ The APIs of this module return exceptions since API version 9. The following tab ...@@ -42,11 +40,11 @@ The APIs of this module return exceptions since API version 9. The following tab
## MessageSequence<sup>9+</sup> ## MessageSequence<sup>9+</sup>
Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. Provides APIs for reading and writing data in specific format. During RPC or IPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects.
### create ### create
create(): MessageSequence static create(): MessageSequence
Creates a **MessageSequence** object. This API is a static method. Creates a **MessageSequence** object. This API is a static method.
...@@ -60,7 +58,7 @@ The APIs of this module return exceptions since API version 9. The following tab ...@@ -60,7 +58,7 @@ The APIs of this module return exceptions since API version 9. The following tab
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
console.log("RpcClient: data is " + data); console.log("RpcClient: data is " + data);
``` ```
...@@ -75,7 +73,7 @@ Reclaims the **MessageSequence** object that is no longer used. ...@@ -75,7 +73,7 @@ Reclaims the **MessageSequence** object that is no longer used.
**Example** **Example**
``` ```ts
let reply = rpc.MessageSequence.create(); let reply = rpc.MessageSequence.create();
reply.reclaim(); reply.reclaim();
``` ```
...@@ -105,7 +103,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -105,7 +103,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -146,7 +144,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -146,7 +144,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -187,7 +185,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -187,7 +185,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeInterfaceToken("aaa"); data.writeInterfaceToken("aaa");
...@@ -219,23 +217,22 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -219,23 +217,22 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ------- | ----- | | ------- | ----- |
| 1900010 | read data from message sequence failed | | 1900010 | read data from message sequence failed |
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
try { try {
let interfaceToken = data.readInterfaceToken(); let interfaceToken = data.readInterfaceToken();
console.log("RpcServer: interfaceToken is " + interfaceToken); console.log("RpcServer: interfaceToken is " + interfaceToken);
} catch(error) { } catch(error) {
console.info("RpcServer: read interfaceToken failed, errorCode " + error.code); console.info("RpcServer: read interfaceToken failed, errorCode " + error.code);
console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message); console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message);
} }
return true; return true;
} }
} }
``` ```
### getSize ### getSize
...@@ -253,7 +250,7 @@ Obtains the data size of this **MessageSequence** object. ...@@ -253,7 +250,7 @@ Obtains the data size of this **MessageSequence** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let size = data.getSize(); let size = data.getSize();
console.log("RpcClient: size is " + size); console.log("RpcClient: size is " + size);
...@@ -275,7 +272,7 @@ Obtains the capacity of this **MessageSequence** object. ...@@ -275,7 +272,7 @@ Obtains the capacity of this **MessageSequence** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let result = data.getCapacity(); let result = data.getCapacity();
console.log("RpcClient: capacity is " + result); console.log("RpcClient: capacity is " + result);
...@@ -285,7 +282,7 @@ Obtains the capacity of this **MessageSequence** object. ...@@ -285,7 +282,7 @@ Obtains the capacity of this **MessageSequence** object.
setSize(size: number): void setSize(size: number): void
Sets the size of data contained in this **MessageSequence** object. Sets the size of the data contained in this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -293,11 +290,11 @@ Sets the size of data contained in this **MessageSequence** object. ...@@ -293,11 +290,11 @@ Sets the size of data contained in this **MessageSequence** object.
| Name| Type | Mandatory| Description| | Name| Type | Mandatory| Description|
| ------ | ------ | ---- | ------ | | ------ | ------ | ---- | ------ |
| size | number | Yes| Data size to set, in bytes.| | size | number | Yes | Data size to set, in bytes.|
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.setSize(16); data.setSize(16);
...@@ -332,7 +329,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -332,7 +329,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.setCapacity(100); data.setCapacity(100);
...@@ -347,7 +344,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -347,7 +344,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
getWritableBytes(): number getWritableBytes(): number
Obtains the writable capacity of this **MessageSequence** object. Obtains the writable capacity (in bytes) of this **MessageSequence** object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -355,19 +352,19 @@ Obtains the writable capacity of this **MessageSequence** object. ...@@ -355,19 +352,19 @@ Obtains the writable capacity of this **MessageSequence** object.
| Type| Description| | Type| Description|
| ------ | ------ | | ------ | ------ |
| number | **MessageSequence** writable capacity obtained, in bytes.| | number | Writable capacity of the **MessageSequence** instance, in bytes.|
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes(); let getWritableBytes = data.getWritableBytes();
console.log("RpcServer: getWritableBytes is " + getWritableBytes); console.log("RpcServer: getWritableBytes is " + getWritableBytes);
return true; return true;
} }
} }
``` ```
### getReadableBytes ### getReadableBytes
...@@ -381,18 +378,18 @@ Obtains the readable capacity of this **MessageSequence** object. ...@@ -381,18 +378,18 @@ Obtains the readable capacity of this **MessageSequence** object.
| Type| Description| | Type| Description|
| ------ | ------- | | ------ | ------- |
| number | **MessageSequence** readable capacity obtained, in bytes.| | number | Readable capacity of the **MessageSequence** instance, in bytes.|
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes(); let result = data.getReadableBytes();
console.log("RpcServer: getReadableBytes is " + result); console.log("RpcServer: getReadableBytes is " + result);
return true; return true;
} }
} }
``` ```
### getReadPosition ### getReadPosition
...@@ -411,7 +408,7 @@ Obtains the read position of this **MessageSequence** object. ...@@ -411,7 +408,7 @@ Obtains the read position of this **MessageSequence** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let readPos = data.getReadPosition(); let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos); console.log("RpcClient: readPos is " + readPos);
...@@ -433,7 +430,7 @@ Obtains the write position of this **MessageSequence** object. ...@@ -433,7 +430,7 @@ Obtains the write position of this **MessageSequence** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
data.writeInt(10); data.writeInt(10);
let bwPos = data.getWritePosition(); let bwPos = data.getWritePosition();
...@@ -456,7 +453,7 @@ Moves the read pointer to the specified position. ...@@ -456,7 +453,7 @@ Moves the read pointer to the specified position.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
data.writeInt(12); data.writeInt(12);
data.writeString("sequence"); data.writeString("sequence");
...@@ -488,7 +485,7 @@ Moves the write pointer to the specified position. ...@@ -488,7 +485,7 @@ Moves the write pointer to the specified position.
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
data.writeInt(4); data.writeInt(4);
try { try {
...@@ -526,7 +523,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -526,7 +523,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeByte(2); data.writeByte(2);
...@@ -560,7 +557,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -560,7 +557,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeByte(2); data.writeByte(2);
...@@ -601,7 +598,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -601,7 +598,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeShort(8); data.writeShort(8);
...@@ -635,7 +632,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -635,7 +632,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeShort(8); data.writeShort(8);
...@@ -676,7 +673,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -676,7 +673,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeInt(10); data.writeInt(10);
...@@ -710,7 +707,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -710,7 +707,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeInt(10); data.writeInt(10);
...@@ -751,7 +748,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -751,7 +748,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeLong(10000); data.writeLong(10000);
...@@ -785,7 +782,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -785,7 +782,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeLong(10000); data.writeLong(10000);
...@@ -826,7 +823,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -826,7 +823,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeFloat(1.2); data.writeFloat(1.2);
...@@ -860,7 +857,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -860,7 +857,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeFloat(1.2); data.writeFloat(1.2);
...@@ -901,7 +898,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -901,7 +898,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeDouble(10.2); data.writeDouble(10.2);
...@@ -935,7 +932,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -935,7 +932,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeDouble(10.2); data.writeDouble(10.2);
...@@ -976,7 +973,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -976,7 +973,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeBoolean(false); data.writeBoolean(false);
...@@ -1010,7 +1007,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1010,7 +1007,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeBoolean(false); data.writeBoolean(false);
...@@ -1051,7 +1048,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1051,7 +1048,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeChar(97); data.writeChar(97);
...@@ -1085,7 +1082,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1085,7 +1082,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeChar(97); data.writeChar(97);
...@@ -1126,7 +1123,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1126,7 +1123,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeString('abc'); data.writeString('abc');
...@@ -1160,7 +1157,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1160,7 +1157,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeString('abc'); data.writeString('abc');
...@@ -1201,7 +1198,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1201,7 +1198,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -1255,7 +1252,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1255,7 +1252,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -1310,7 +1307,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1310,7 +1307,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let ByteArrayVar = [1, 2, 3, 4, 5]; let ByteArrayVar = [1, 2, 3, 4, 5];
try { try {
...@@ -1345,7 +1342,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1345,7 +1342,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let ByteArrayVar = [1, 2, 3, 4, 5]; let ByteArrayVar = [1, 2, 3, 4, 5];
try { try {
...@@ -1387,7 +1384,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1387,7 +1384,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
let byteArrayVar = [1, 2, 3, 4, 5]; let byteArrayVar = [1, 2, 3, 4, 5];
try { try {
...@@ -1429,7 +1426,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1429,7 +1426,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeShortArray([11, 12, 13]); data.writeShortArray([11, 12, 13]);
...@@ -1463,7 +1460,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1463,7 +1460,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeShortArray([11, 12, 13]); data.writeShortArray([11, 12, 13]);
...@@ -1504,7 +1501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1504,7 +1501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeShortArray([11, 12, 13]); data.writeShortArray([11, 12, 13]);
...@@ -1545,7 +1542,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1545,7 +1542,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeIntArray([100, 111, 112]); data.writeIntArray([100, 111, 112]);
...@@ -1579,7 +1576,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1579,7 +1576,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeIntArray([100, 111, 112]); data.writeIntArray([100, 111, 112]);
...@@ -1620,7 +1617,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1620,7 +1617,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeIntArray([100, 111, 112]); data.writeIntArray([100, 111, 112]);
...@@ -1661,7 +1658,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1661,7 +1658,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeLongArray([1111, 1112, 1113]); data.writeLongArray([1111, 1112, 1113]);
...@@ -1695,7 +1692,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1695,7 +1692,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeLongArray([1111, 1112, 1113]); data.writeLongArray([1111, 1112, 1113]);
...@@ -1736,7 +1733,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1736,7 +1733,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeLongArray([1111, 1112, 1113]); data.writeLongArray([1111, 1112, 1113]);
...@@ -1777,7 +1774,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1777,7 +1774,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeFloatArray([1.2, 1.3, 1.4]); data.writeFloatArray([1.2, 1.3, 1.4]);
...@@ -1811,7 +1808,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1811,7 +1808,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeFloatArray([1.2, 1.3, 1.4]); data.writeFloatArray([1.2, 1.3, 1.4]);
...@@ -1852,7 +1849,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1852,7 +1849,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeFloatArray([1.2, 1.3, 1.4]); data.writeFloatArray([1.2, 1.3, 1.4]);
...@@ -1893,7 +1890,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1893,7 +1890,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeDoubleArray([11.1, 12.2, 13.3]); data.writeDoubleArray([11.1, 12.2, 13.3]);
...@@ -1927,7 +1924,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1927,7 +1924,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeDoubleArray([11.1, 12.2, 13.3]); data.writeDoubleArray([11.1, 12.2, 13.3]);
...@@ -1968,7 +1965,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -1968,7 +1965,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeDoubleArray([11.1, 12.2, 13.3]); data.writeDoubleArray([11.1, 12.2, 13.3]);
...@@ -2009,7 +2006,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2009,7 +2006,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeBooleanArray([false, true, false]); data.writeBooleanArray([false, true, false]);
...@@ -2043,7 +2040,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2043,7 +2040,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeBooleanArray([false, true, false]); data.writeBooleanArray([false, true, false]);
...@@ -2084,7 +2081,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2084,7 +2081,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeBooleanArray([false, true, false]); data.writeBooleanArray([false, true, false]);
...@@ -2125,7 +2122,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2125,7 +2122,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeCharArray([97, 98, 88]); data.writeCharArray([97, 98, 88]);
...@@ -2159,7 +2156,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2159,7 +2156,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeCharArray([97, 98, 88]); data.writeCharArray([97, 98, 88]);
...@@ -2200,7 +2197,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2200,7 +2197,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeCharArray([97, 98, 88]); data.writeCharArray([97, 98, 88]);
...@@ -2242,7 +2239,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2242,7 +2239,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeStringArray(["abc", "def"]); data.writeStringArray(["abc", "def"]);
...@@ -2276,7 +2273,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2276,7 +2273,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeStringArray(["abc", "def"]); data.writeStringArray(["abc", "def"]);
...@@ -2317,7 +2314,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2317,7 +2314,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let data = rpc.MessageSequence.create(); let data = rpc.MessageSequence.create();
try { try {
data.writeStringArray(["abc", "def"]); data.writeStringArray(["abc", "def"]);
...@@ -2352,7 +2349,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2352,7 +2349,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -2394,7 +2391,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2394,7 +2391,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -2411,7 +2408,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2411,7 +2408,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let option = new rpc.MessageOption(); let option = new rpc.MessageOption();
...@@ -2467,7 +2464,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2467,7 +2464,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MyParcelable { class MyParcelable {
num: number; num: number;
str: string; str: string;
...@@ -2524,7 +2521,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2524,7 +2521,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MyParcelable { class MyParcelable {
num: number; num: number;
str: string; str: string;
...@@ -2584,7 +2581,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2584,7 +2581,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -2631,7 +2628,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2631,7 +2628,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -2684,7 +2681,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2684,7 +2681,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -2712,7 +2709,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2712,7 +2709,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
static closeFileDescriptor(fd: number): void static closeFileDescriptor(fd: number): void
Closes a file descriptor. Closes a file descriptor. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -2724,7 +2721,7 @@ Closes a file descriptor. ...@@ -2724,7 +2721,7 @@ Closes a file descriptor.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let filePath = "path/to/file"; let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
...@@ -2740,7 +2737,7 @@ Closes a file descriptor. ...@@ -2740,7 +2737,7 @@ Closes a file descriptor.
static dupFileDescriptor(fd: number) :number static dupFileDescriptor(fd: number) :number
Duplicates a file descriptor. Duplicates a file descriptor. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -2766,7 +2763,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2766,7 +2763,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let filePath = "path/to/file"; let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
...@@ -2795,7 +2792,7 @@ Checks whether this **MessageSequence** object contains file descriptors. ...@@ -2795,7 +2792,7 @@ Checks whether this **MessageSequence** object contains file descriptors.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -2840,7 +2837,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2840,7 +2837,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -2853,7 +2850,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2853,7 +2850,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### readFileDescriptor ### readFileDescriptor
readFileDescriptor(): number readFileDescriptor(): number
...@@ -2878,7 +2874,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2878,7 +2874,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -2897,7 +2893,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2897,7 +2893,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### writeAshmem ### writeAshmem
writeAshmem(ashmem: Ashmem): void writeAshmem(ashmem: Ashmem): void
...@@ -2922,7 +2917,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2922,7 +2917,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let ashmem; let ashmem;
try { try {
...@@ -2964,7 +2959,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2964,7 +2959,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let ashmem; let ashmem;
try { try {
...@@ -2988,7 +2983,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -2988,7 +2983,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### getRawDataCapacity ### getRawDataCapacity
getRawDataCapacity(): number getRawDataCapacity(): number
...@@ -3005,13 +2999,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageSequenc ...@@ -3005,13 +2999,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageSequenc
**Example** **Example**
``` ```ts
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let result = sequence.getRawDataCapacity(); let result = sequence.getRawDataCapacity();
console.log("RpcTest: sequence get RawDataCapacity result is : " + result); console.log("RpcTest: sequence get RawDataCapacity result is : " + result);
``` ```
### writeRawData ### writeRawData
writeRawData(rawData: number[], size: number): void writeRawData(rawData: number[], size: number): void
...@@ -3037,7 +3030,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -3037,7 +3030,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let arr = [1, 2, 3, 4, 5]; let arr = [1, 2, 3, 4, 5];
try { try {
...@@ -3048,7 +3041,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -3048,7 +3041,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### readRawData ### readRawData
readRawData(size: number): number[] readRawData(size: number): number[]
...@@ -3079,7 +3071,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -3079,7 +3071,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let sequence = new rpc.MessageSequence(); let sequence = new rpc.MessageSequence();
let arr = [1, 2, 3, 4, 5]; let arr = [1, 2, 3, 4, 5];
try { try {
...@@ -3105,7 +3097,7 @@ Provides APIs for reading and writing data in specific format. During RPC, the s ...@@ -3105,7 +3097,7 @@ Provides APIs for reading and writing data in specific format. During RPC, the s
### create ### create
create(): MessageParcel static create(): MessageParcel
Creates a **MessageParcel** object. This method is a static method. Creates a **MessageParcel** object. This method is a static method.
...@@ -3119,7 +3111,7 @@ Creates a **MessageParcel** object. This method is a static method. ...@@ -3119,7 +3111,7 @@ Creates a **MessageParcel** object. This method is a static method.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
console.log("RpcClient: data is " + data); console.log("RpcClient: data is " + data);
``` ```
...@@ -3134,7 +3126,7 @@ Reclaims the **MessageParcel** object that is no longer used. ...@@ -3134,7 +3126,7 @@ Reclaims the **MessageParcel** object that is no longer used.
**Example** **Example**
``` ```ts
let reply = rpc.MessageParcel.create(); let reply = rpc.MessageParcel.create();
reply.reclaim(); reply.reclaim();
``` ```
...@@ -3161,7 +3153,7 @@ Serializes a remote object and writes it to this **MessageParcel** object. ...@@ -3161,7 +3153,7 @@ Serializes a remote object and writes it to this **MessageParcel** object.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -3202,7 +3194,7 @@ Reads the remote object from this **MessageParcel** object. You can use this met ...@@ -3202,7 +3194,7 @@ Reads the remote object from this **MessageParcel** object. You can use this met
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -3250,7 +3242,7 @@ Writes an interface token to this **MessageParcel** object. The remote object ca ...@@ -3250,7 +3242,7 @@ Writes an interface token to this **MessageParcel** object. The remote object ca
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeInterfaceToken("aaa"); let result = data.writeInterfaceToken("aaa");
console.log("RpcServer: writeInterfaceToken is " + result); console.log("RpcServer: writeInterfaceToken is " + result);
...@@ -3273,7 +3265,7 @@ Reads the interface token from this **MessageParcel** object. The interface toke ...@@ -3273,7 +3265,7 @@ Reads the interface token from this **MessageParcel** object. The interface toke
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let interfaceToken = data.readInterfaceToken(); let interfaceToken = data.readInterfaceToken();
...@@ -3283,7 +3275,6 @@ Reads the interface token from this **MessageParcel** object. The interface toke ...@@ -3283,7 +3275,6 @@ Reads the interface token from this **MessageParcel** object. The interface toke
} }
``` ```
### getSize ### getSize
getSize(): number getSize(): number
...@@ -3300,13 +3291,12 @@ Obtains the data size of this **MessageParcel** object. ...@@ -3300,13 +3291,12 @@ Obtains the data size of this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let size = data.getSize(); let size = data.getSize();
console.log("RpcClient: size is " + size); console.log("RpcClient: size is " + size);
``` ```
### getCapacity ### getCapacity
getCapacity(): number getCapacity(): number
...@@ -3323,13 +3313,12 @@ Obtains the capacity of this **MessageParcel** object. ...@@ -3323,13 +3313,12 @@ Obtains the capacity of this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.getCapacity(); let result = data.getCapacity();
console.log("RpcClient: capacity is " + result); console.log("RpcClient: capacity is " + result);
``` ```
### setSize ### setSize
setSize(size: number): boolean setSize(size: number): boolean
...@@ -3352,13 +3341,12 @@ Sets the size of data contained in this **MessageParcel** object. ...@@ -3352,13 +3341,12 @@ Sets the size of data contained in this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let setSize = data.setSize(16); let setSize = data.setSize(16);
console.log("RpcClient: setSize is " + setSize); console.log("RpcClient: setSize is " + setSize);
``` ```
### setCapacity ### setCapacity
setCapacity(size: number): boolean setCapacity(size: number): boolean
...@@ -3381,13 +3369,12 @@ Sets the storage capacity of this **MessageParcel** object. ...@@ -3381,13 +3369,12 @@ Sets the storage capacity of this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.setCapacity(100); let result = data.setCapacity(100);
console.log("RpcClient: setCapacity is " + result); console.log("RpcClient: setCapacity is " + result);
``` ```
### getWritableBytes ### getWritableBytes
getWritableBytes(): number getWritableBytes(): number
...@@ -3404,7 +3391,7 @@ Obtains the writable capacity of this **MessageParcel** object. ...@@ -3404,7 +3391,7 @@ Obtains the writable capacity of this **MessageParcel** object.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let getWritableBytes = data.getWritableBytes(); let getWritableBytes = data.getWritableBytes();
...@@ -3414,7 +3401,6 @@ Obtains the writable capacity of this **MessageParcel** object. ...@@ -3414,7 +3401,6 @@ Obtains the writable capacity of this **MessageParcel** object.
} }
``` ```
### getReadableBytes ### getReadableBytes
getReadableBytes(): number getReadableBytes(): number
...@@ -3431,7 +3417,7 @@ Obtains the readable capacity of this **MessageParcel** object. ...@@ -3431,7 +3417,7 @@ Obtains the readable capacity of this **MessageParcel** object.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
let result = data.getReadableBytes(); let result = data.getReadableBytes();
...@@ -3441,7 +3427,6 @@ Obtains the readable capacity of this **MessageParcel** object. ...@@ -3441,7 +3427,6 @@ Obtains the readable capacity of this **MessageParcel** object.
} }
``` ```
### getReadPosition ### getReadPosition
getReadPosition(): number getReadPosition(): number
...@@ -3458,13 +3443,12 @@ Obtains the read position of this **MessageParcel** object. ...@@ -3458,13 +3443,12 @@ Obtains the read position of this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let readPos = data.getReadPosition(); let readPos = data.getReadPosition();
console.log("RpcClient: readPos is " + readPos); console.log("RpcClient: readPos is " + readPos);
``` ```
### getWritePosition ### getWritePosition
getWritePosition(): number getWritePosition(): number
...@@ -3481,14 +3465,13 @@ Obtains the write position of this **MessageParcel** object. ...@@ -3481,14 +3465,13 @@ Obtains the write position of this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
data.writeInt(10); data.writeInt(10);
let bwPos = data.getWritePosition(); let bwPos = data.getWritePosition();
console.log("RpcClient: bwPos is " + bwPos); console.log("RpcClient: bwPos is " + bwPos);
``` ```
### rewindRead ### rewindRead
rewindRead(pos: number): boolean rewindRead(pos: number): boolean
...@@ -3511,7 +3494,7 @@ Moves the read pointer to the specified position. ...@@ -3511,7 +3494,7 @@ Moves the read pointer to the specified position.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
data.writeInt(12); data.writeInt(12);
data.writeString("parcel"); data.writeString("parcel");
...@@ -3522,7 +3505,6 @@ Moves the read pointer to the specified position. ...@@ -3522,7 +3505,6 @@ Moves the read pointer to the specified position.
console.log("RpcClient: rewindRead is " + number2); console.log("RpcClient: rewindRead is " + number2);
``` ```
### rewindWrite ### rewindWrite
rewindWrite(pos: number): boolean rewindWrite(pos: number): boolean
...@@ -3545,7 +3527,7 @@ Moves the write pointer to the specified position. ...@@ -3545,7 +3527,7 @@ Moves the write pointer to the specified position.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
data.writeInt(4); data.writeInt(4);
data.rewindWrite(0); data.rewindWrite(0);
...@@ -3554,7 +3536,6 @@ Moves the write pointer to the specified position. ...@@ -3554,7 +3536,6 @@ Moves the write pointer to the specified position.
console.log("RpcClient: rewindWrite is: " + number); console.log("RpcClient: rewindWrite is: " + number);
``` ```
### writeByte ### writeByte
writeByte(val: number): boolean writeByte(val: number): boolean
...@@ -3577,13 +3558,12 @@ Writes a Byte value to this **MessageParcel** object. ...@@ -3577,13 +3558,12 @@ Writes a Byte value to this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeByte(2); let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result); console.log("RpcClient: writeByte is: " + result);
``` ```
### readByte ### readByte
readByte(): number readByte(): number
...@@ -3600,7 +3580,7 @@ Reads the Byte value from this **MessageParcel** object. ...@@ -3600,7 +3580,7 @@ Reads the Byte value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeByte(2); let result = data.writeByte(2);
console.log("RpcClient: writeByte is: " + result); console.log("RpcClient: writeByte is: " + result);
...@@ -3608,7 +3588,6 @@ Reads the Byte value from this **MessageParcel** object. ...@@ -3608,7 +3588,6 @@ Reads the Byte value from this **MessageParcel** object.
console.log("RpcClient: readByte is: " + ret); console.log("RpcClient: readByte is: " + ret);
``` ```
### writeShort ### writeShort
writeShort(val: number): boolean writeShort(val: number): boolean
...@@ -3627,17 +3606,16 @@ Writes a Short int value to this **MessageParcel** object. ...@@ -3627,17 +3606,16 @@ Writes a Short int value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeShort(8); let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result); console.log("RpcClient: writeShort is: " + result);
``` ```
### readShort ### readShort
readShort(): number readShort(): number
...@@ -3654,7 +3632,7 @@ Reads the Short int value from this **MessageParcel** object. ...@@ -3654,7 +3632,7 @@ Reads the Short int value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeShort(8); let result = data.writeShort(8);
console.log("RpcClient: writeShort is: " + result); console.log("RpcClient: writeShort is: " + result);
...@@ -3662,7 +3640,6 @@ Reads the Short int value from this **MessageParcel** object. ...@@ -3662,7 +3640,6 @@ Reads the Short int value from this **MessageParcel** object.
console.log("RpcClient: readShort is: " + ret); console.log("RpcClient: readShort is: " + ret);
``` ```
### writeInt ### writeInt
writeInt(val: number): boolean writeInt(val: number): boolean
...@@ -3685,13 +3662,12 @@ Writes an Int value to this **MessageParcel** object. ...@@ -3685,13 +3662,12 @@ Writes an Int value to this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeInt(10); let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result); console.log("RpcClient: writeInt is " + result);
``` ```
### readInt ### readInt
readInt(): number readInt(): number
...@@ -3708,7 +3684,7 @@ Reads the Int value from this **MessageParcel** object. ...@@ -3708,7 +3684,7 @@ Reads the Int value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeInt(10); let result = data.writeInt(10);
console.log("RpcClient: writeInt is " + result); console.log("RpcClient: writeInt is " + result);
...@@ -3716,7 +3692,6 @@ Reads the Int value from this **MessageParcel** object. ...@@ -3716,7 +3692,6 @@ Reads the Int value from this **MessageParcel** object.
console.log("RpcClient: readInt is " + ret); console.log("RpcClient: readInt is " + ret);
``` ```
### writeLong ### writeLong
writeLong(val: number): boolean writeLong(val: number): boolean
...@@ -3735,17 +3710,16 @@ Writes a Long int value to this **MessageParcel** object. ...@@ -3735,17 +3710,16 @@ Writes a Long int value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeLong(10000); let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result); console.log("RpcClient: writeLong is " + result);
``` ```
### readLong ### readLong
readLong(): number readLong(): number
...@@ -3762,7 +3736,7 @@ Reads the Long int value from this **MessageParcel** object. ...@@ -3762,7 +3736,7 @@ Reads the Long int value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeLong(10000); let result = data.writeLong(10000);
console.log("RpcClient: writeLong is " + result); console.log("RpcClient: writeLong is " + result);
...@@ -3770,7 +3744,6 @@ Reads the Long int value from this **MessageParcel** object. ...@@ -3770,7 +3744,6 @@ Reads the Long int value from this **MessageParcel** object.
console.log("RpcClient: readLong is " + ret); console.log("RpcClient: readLong is " + ret);
``` ```
### writeFloat ### writeFloat
writeFloat(val: number): boolean writeFloat(val: number): boolean
...@@ -3789,17 +3762,16 @@ Writes a Float value to this **MessageParcel** object. ...@@ -3789,17 +3762,16 @@ Writes a Float value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2); let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result); console.log("RpcClient: writeFloat is " + result);
``` ```
### readFloat ### readFloat
readFloat(): number readFloat(): number
...@@ -3816,7 +3788,7 @@ Reads the Float value from this **MessageParcel** object. ...@@ -3816,7 +3788,7 @@ Reads the Float value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeFloat(1.2); let result = data.writeFloat(1.2);
console.log("RpcClient: writeFloat is " + result); console.log("RpcClient: writeFloat is " + result);
...@@ -3824,7 +3796,6 @@ Reads the Float value from this **MessageParcel** object. ...@@ -3824,7 +3796,6 @@ Reads the Float value from this **MessageParcel** object.
console.log("RpcClient: readFloat is " + ret); console.log("RpcClient: readFloat is " + ret);
``` ```
### writeDouble ### writeDouble
writeDouble(val: number): boolean writeDouble(val: number): boolean
...@@ -3843,17 +3814,16 @@ Writes a Double value to this **MessageParcel** object. ...@@ -3843,17 +3814,16 @@ Writes a Double value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2); let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result); console.log("RpcClient: writeDouble is " + result);
``` ```
### readDouble ### readDouble
readDouble(): number readDouble(): number
...@@ -3870,7 +3840,7 @@ Reads the Double value from this **MessageParcel** object. ...@@ -3870,7 +3840,7 @@ Reads the Double value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeDouble(10.2); let result = data.writeDouble(10.2);
console.log("RpcClient: writeDouble is " + result); console.log("RpcClient: writeDouble is " + result);
...@@ -3896,17 +3866,16 @@ Writes a Boolean value to this **MessageParcel** object. ...@@ -3896,17 +3866,16 @@ Writes a Boolean value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false); let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result); console.log("RpcClient: writeBoolean is " + result);
``` ```
### readBoolean ### readBoolean
readBoolean(): boolean readBoolean(): boolean
...@@ -3923,7 +3892,7 @@ Reads the Boolean value from this **MessageParcel** object. ...@@ -3923,7 +3892,7 @@ Reads the Boolean value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeBoolean(false); let result = data.writeBoolean(false);
console.log("RpcClient: writeBoolean is " + result); console.log("RpcClient: writeBoolean is " + result);
...@@ -3931,7 +3900,6 @@ Reads the Boolean value from this **MessageParcel** object. ...@@ -3931,7 +3900,6 @@ Reads the Boolean value from this **MessageParcel** object.
console.log("RpcClient: readBoolean is " + ret); console.log("RpcClient: readBoolean is " + ret);
``` ```
### writeChar ### writeChar
writeChar(val: number): boolean writeChar(val: number): boolean
...@@ -3950,17 +3918,16 @@ Writes a Char value to this **MessageParcel** object. ...@@ -3950,17 +3918,16 @@ Writes a Char value to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeChar(97); let result = data.writeChar(97);
console.log("RpcClient: writeChar is " + result); console.log("RpcClient: writeChar is " + result);
``` ```
### readChar ### readChar
readChar(): number readChar(): number
...@@ -3977,7 +3944,7 @@ Reads the Char value from this **MessageParcel** object. ...@@ -3977,7 +3944,7 @@ Reads the Char value from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeChar(97); let result = data.writeChar(97);
console.log("RpcClient: writeChar is " + result); console.log("RpcClient: writeChar is " + result);
...@@ -3985,7 +3952,6 @@ Reads the Char value from this **MessageParcel** object. ...@@ -3985,7 +3952,6 @@ Reads the Char value from this **MessageParcel** object.
console.log("RpcClient: readChar is " + ret); console.log("RpcClient: readChar is " + ret);
``` ```
### writeString ### writeString
writeString(val: string): boolean writeString(val: string): boolean
...@@ -4004,17 +3970,16 @@ Writes a string to this **MessageParcel** object. ...@@ -4004,17 +3970,16 @@ Writes a string to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeString('abc'); let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result); console.log("RpcClient: writeString is " + result);
``` ```
### readString ### readString
readString(): string readString(): string
...@@ -4031,7 +3996,7 @@ Reads the string from this **MessageParcel** object. ...@@ -4031,7 +3996,7 @@ Reads the string from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeString('abc'); let result = data.writeString('abc');
console.log("RpcClient: writeString is " + result); console.log("RpcClient: writeString is " + result);
...@@ -4039,7 +4004,6 @@ Reads the string from this **MessageParcel** object. ...@@ -4039,7 +4004,6 @@ Reads the string from this **MessageParcel** object.
console.log("RpcClient: readString is " + ret); console.log("RpcClient: readString is " + ret);
``` ```
### writeSequenceable ### writeSequenceable
writeSequenceable(val: Sequenceable): boolean writeSequenceable(val: Sequenceable): boolean
...@@ -4058,11 +4022,11 @@ Writes a sequenceable object to this **MessageParcel** object. ...@@ -4058,11 +4022,11 @@ Writes a sequenceable object to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -4087,7 +4051,6 @@ Writes a sequenceable object to this **MessageParcel** object. ...@@ -4087,7 +4051,6 @@ Writes a sequenceable object to this **MessageParcel** object.
console.log("RpcClient: writeSequenceable is " + result); console.log("RpcClient: writeSequenceable is " + result);
``` ```
### readSequenceable ### readSequenceable
readSequenceable(dataIn: Sequenceable): boolean readSequenceable(dataIn: Sequenceable): boolean
...@@ -4110,7 +4073,7 @@ Reads member variables from this **MessageParcel** object. ...@@ -4110,7 +4073,7 @@ Reads member variables from this **MessageParcel** object.
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -4138,7 +4101,6 @@ Reads member variables from this **MessageParcel** object. ...@@ -4138,7 +4101,6 @@ Reads member variables from this **MessageParcel** object.
console.log("RpcClient: writeSequenceable is " + result2); console.log("RpcClient: writeSequenceable is " + result2);
``` ```
### writeByteArray ### writeByteArray
writeByteArray(byteArray: number[]): boolean writeByteArray(byteArray: number[]): boolean
...@@ -4157,18 +4119,17 @@ Writes a byte array to this **MessageParcel** object. ...@@ -4157,18 +4119,17 @@ Writes a byte array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5]; let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar); let result = data.writeByteArray(ByteArrayVar);
console.log("RpcClient: writeByteArray is " + result); console.log("RpcClient: writeByteArray is " + result);
``` ```
### readByteArray ### readByteArray
readByteArray(dataIn: number[]): void readByteArray(dataIn: number[]): void
...@@ -4185,7 +4146,7 @@ Reads a byte array from this **MessageParcel** object. ...@@ -4185,7 +4146,7 @@ Reads a byte array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5]; let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar); let result = data.writeByteArray(ByteArrayVar);
...@@ -4194,7 +4155,6 @@ Reads a byte array from this **MessageParcel** object. ...@@ -4194,7 +4155,6 @@ Reads a byte array from this **MessageParcel** object.
data.readByteArray(array); data.readByteArray(array);
``` ```
### readByteArray ### readByteArray
readByteArray(): number[] readByteArray(): number[]
...@@ -4211,7 +4171,7 @@ Reads the byte array from this **MessageParcel** object. ...@@ -4211,7 +4171,7 @@ Reads the byte array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let ByteArrayVar = [1, 2, 3, 4, 5]; let ByteArrayVar = [1, 2, 3, 4, 5];
let result = data.writeByteArray(ByteArrayVar); let result = data.writeByteArray(ByteArrayVar);
...@@ -4220,7 +4180,6 @@ Reads the byte array from this **MessageParcel** object. ...@@ -4220,7 +4180,6 @@ Reads the byte array from this **MessageParcel** object.
console.log("RpcClient: readByteArray is " + array); console.log("RpcClient: readByteArray is " + array);
``` ```
### writeShortArray ### writeShortArray
writeShortArray(shortArray: number[]): boolean writeShortArray(shortArray: number[]): boolean
...@@ -4239,17 +4198,16 @@ Writes a short array to this **MessageParcel** object. ...@@ -4239,17 +4198,16 @@ Writes a short array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]); let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result); console.log("RpcClient: writeShortArray is " + result);
``` ```
### readShortArray ### readShortArray
readShortArray(dataIn: number[]): void readShortArray(dataIn: number[]): void
...@@ -4266,7 +4224,7 @@ Reads a short array from this **MessageParcel** object. ...@@ -4266,7 +4224,7 @@ Reads a short array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]); let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result); console.log("RpcClient: writeShortArray is " + result);
...@@ -4274,7 +4232,6 @@ Reads a short array from this **MessageParcel** object. ...@@ -4274,7 +4232,6 @@ Reads a short array from this **MessageParcel** object.
data.readShortArray(array); data.readShortArray(array);
``` ```
### readShortArray ### readShortArray
readShortArray(): number[] readShortArray(): number[]
...@@ -4291,7 +4248,7 @@ Reads the short array from this **MessageParcel** object. ...@@ -4291,7 +4248,7 @@ Reads the short array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeShortArray([11, 12, 13]); let result = data.writeShortArray([11, 12, 13]);
console.log("RpcClient: writeShortArray is " + result); console.log("RpcClient: writeShortArray is " + result);
...@@ -4299,7 +4256,6 @@ Reads the short array from this **MessageParcel** object. ...@@ -4299,7 +4256,6 @@ Reads the short array from this **MessageParcel** object.
console.log("RpcClient: readShortArray is " + array); console.log("RpcClient: readShortArray is " + array);
``` ```
### writeIntArray ### writeIntArray
writeIntArray(intArray: number[]): boolean writeIntArray(intArray: number[]): boolean
...@@ -4318,17 +4274,16 @@ Writes an integer array to this **MessageParcel** object. ...@@ -4318,17 +4274,16 @@ Writes an integer array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]); let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result); console.log("RpcClient: writeIntArray is " + result);
``` ```
### readIntArray ### readIntArray
readIntArray(dataIn: number[]): void readIntArray(dataIn: number[]): void
...@@ -4345,7 +4300,7 @@ Reads an integer array from this **MessageParcel** object. ...@@ -4345,7 +4300,7 @@ Reads an integer array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]); let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result); console.log("RpcClient: writeIntArray is " + result);
...@@ -4353,7 +4308,6 @@ Reads an integer array from this **MessageParcel** object. ...@@ -4353,7 +4308,6 @@ Reads an integer array from this **MessageParcel** object.
data.readIntArray(array); data.readIntArray(array);
``` ```
### readIntArray ### readIntArray
readIntArray(): number[] readIntArray(): number[]
...@@ -4370,7 +4324,7 @@ Reads the integer array from this **MessageParcel** object. ...@@ -4370,7 +4324,7 @@ Reads the integer array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeIntArray([100, 111, 112]); let result = data.writeIntArray([100, 111, 112]);
console.log("RpcClient: writeIntArray is " + result); console.log("RpcClient: writeIntArray is " + result);
...@@ -4378,7 +4332,6 @@ Reads the integer array from this **MessageParcel** object. ...@@ -4378,7 +4332,6 @@ Reads the integer array from this **MessageParcel** object.
console.log("RpcClient: readIntArray is " + array); console.log("RpcClient: readIntArray is " + array);
``` ```
### writeLongArray ### writeLongArray
writeLongArray(longArray: number[]): boolean writeLongArray(longArray: number[]): boolean
...@@ -4397,17 +4350,16 @@ Writes a long array to this **MessageParcel** object. ...@@ -4397,17 +4350,16 @@ Writes a long array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]); let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result); console.log("RpcClient: writeLongArray is " + result);
``` ```
### readLongArray ### readLongArray
readLongArray(dataIn: number[]): void readLongArray(dataIn: number[]): void
...@@ -4424,7 +4376,7 @@ Reads a long array from this **MessageParcel** object. ...@@ -4424,7 +4376,7 @@ Reads a long array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]); let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result); console.log("RpcClient: writeLongArray is " + result);
...@@ -4432,7 +4384,6 @@ Reads a long array from this **MessageParcel** object. ...@@ -4432,7 +4384,6 @@ Reads a long array from this **MessageParcel** object.
data.readLongArray(array); data.readLongArray(array);
``` ```
### readLongArray ### readLongArray
readLongArray(): number[] readLongArray(): number[]
...@@ -4449,7 +4400,7 @@ Reads the long array from this **MessageParcel** object. ...@@ -4449,7 +4400,7 @@ Reads the long array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeLongArray([1111, 1112, 1113]); let result = data.writeLongArray([1111, 1112, 1113]);
console.log("RpcClient: writeLongArray is " + result); console.log("RpcClient: writeLongArray is " + result);
...@@ -4457,7 +4408,6 @@ Reads the long array from this **MessageParcel** object. ...@@ -4457,7 +4408,6 @@ Reads the long array from this **MessageParcel** object.
console.log("RpcClient: readLongArray is " + array); console.log("RpcClient: readLongArray is " + array);
``` ```
### writeFloatArray ### writeFloatArray
writeFloatArray(floatArray: number[]): boolean writeFloatArray(floatArray: number[]): boolean
...@@ -4476,17 +4426,16 @@ Writes a FloatArray to this **MessageParcel** object. ...@@ -4476,17 +4426,16 @@ Writes a FloatArray to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]); let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result); console.log("RpcClient: writeFloatArray is " + result);
``` ```
### readFloatArray ### readFloatArray
readFloatArray(dataIn: number[]): void readFloatArray(dataIn: number[]): void
...@@ -4503,7 +4452,7 @@ Reads a FloatArray from this **MessageParcel** object. ...@@ -4503,7 +4452,7 @@ Reads a FloatArray from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]); let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result); console.log("RpcClient: writeFloatArray is " + result);
...@@ -4511,7 +4460,6 @@ Reads a FloatArray from this **MessageParcel** object. ...@@ -4511,7 +4460,6 @@ Reads a FloatArray from this **MessageParcel** object.
data.readFloatArray(array); data.readFloatArray(array);
``` ```
### readFloatArray ### readFloatArray
readFloatArray(): number[] readFloatArray(): number[]
...@@ -4528,7 +4476,7 @@ Reads the FloatArray from this **MessageParcel** object. ...@@ -4528,7 +4476,7 @@ Reads the FloatArray from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeFloatArray([1.2, 1.3, 1.4]); let result = data.writeFloatArray([1.2, 1.3, 1.4]);
console.log("RpcClient: writeFloatArray is " + result); console.log("RpcClient: writeFloatArray is " + result);
...@@ -4536,7 +4484,6 @@ Reads the FloatArray from this **MessageParcel** object. ...@@ -4536,7 +4484,6 @@ Reads the FloatArray from this **MessageParcel** object.
console.log("RpcClient: readFloatArray is " + array); console.log("RpcClient: readFloatArray is " + array);
``` ```
### writeDoubleArray ### writeDoubleArray
writeDoubleArray(doubleArray: number[]): boolean writeDoubleArray(doubleArray: number[]): boolean
...@@ -4555,17 +4502,16 @@ Writes a DoubleArray to this **MessageParcel** object. ...@@ -4555,17 +4502,16 @@ Writes a DoubleArray to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------- | | ------- | ----------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]); let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result); console.log("RpcClient: writeDoubleArray is " + result);
``` ```
### readDoubleArray ### readDoubleArray
readDoubleArray(dataIn: number[]): void readDoubleArray(dataIn: number[]): void
...@@ -4582,7 +4528,7 @@ Reads a DoubleArray from this **MessageParcel** object. ...@@ -4582,7 +4528,7 @@ Reads a DoubleArray from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]); let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result); console.log("RpcClient: writeDoubleArray is " + result);
...@@ -4590,7 +4536,6 @@ Reads a DoubleArray from this **MessageParcel** object. ...@@ -4590,7 +4536,6 @@ Reads a DoubleArray from this **MessageParcel** object.
data.readDoubleArray(array); data.readDoubleArray(array);
``` ```
### readDoubleArray ### readDoubleArray
readDoubleArray(): number[] readDoubleArray(): number[]
...@@ -4607,7 +4552,7 @@ Reads the DoubleArray from this **MessageParcel** object. ...@@ -4607,7 +4552,7 @@ Reads the DoubleArray from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeDoubleArray([11.1, 12.2, 13.3]); let result = data.writeDoubleArray([11.1, 12.2, 13.3]);
console.log("RpcClient: writeDoubleArray is " + result); console.log("RpcClient: writeDoubleArray is " + result);
...@@ -4615,7 +4560,6 @@ Reads the DoubleArray from this **MessageParcel** object. ...@@ -4615,7 +4560,6 @@ Reads the DoubleArray from this **MessageParcel** object.
console.log("RpcClient: readDoubleArray is " + array); console.log("RpcClient: readDoubleArray is " + array);
``` ```
### writeBooleanArray ### writeBooleanArray
writeBooleanArray(booleanArray: boolean[]): boolean writeBooleanArray(booleanArray: boolean[]): boolean
...@@ -4634,17 +4578,16 @@ Writes a Boolean array to this **MessageParcel** object. ...@@ -4634,17 +4578,16 @@ Writes a Boolean array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]); let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result); console.log("RpcClient: writeBooleanArray is " + result);
``` ```
### readBooleanArray ### readBooleanArray
readBooleanArray(dataIn: boolean[]): void readBooleanArray(dataIn: boolean[]): void
...@@ -4661,7 +4604,7 @@ Reads a Boolean array from this **MessageParcel** object. ...@@ -4661,7 +4604,7 @@ Reads a Boolean array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]); let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result); console.log("RpcClient: writeBooleanArray is " + result);
...@@ -4669,7 +4612,6 @@ Reads a Boolean array from this **MessageParcel** object. ...@@ -4669,7 +4612,6 @@ Reads a Boolean array from this **MessageParcel** object.
data.readBooleanArray(array); data.readBooleanArray(array);
``` ```
### readBooleanArray ### readBooleanArray
readBooleanArray(): boolean[] readBooleanArray(): boolean[]
...@@ -4686,7 +4628,7 @@ Reads the Boolean array from this **MessageParcel** object. ...@@ -4686,7 +4628,7 @@ Reads the Boolean array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeBooleanArray([false, true, false]); let result = data.writeBooleanArray([false, true, false]);
console.log("RpcClient: writeBooleanArray is " + result); console.log("RpcClient: writeBooleanArray is " + result);
...@@ -4694,7 +4636,6 @@ Reads the Boolean array from this **MessageParcel** object. ...@@ -4694,7 +4636,6 @@ Reads the Boolean array from this **MessageParcel** object.
console.log("RpcClient: readBooleanArray is " + array); console.log("RpcClient: readBooleanArray is " + array);
``` ```
### writeCharArray ### writeCharArray
writeCharArray(charArray: number[]): boolean writeCharArray(charArray: number[]): boolean
...@@ -4713,17 +4654,16 @@ Writes a character array to this **MessageParcel** object. ...@@ -4713,17 +4654,16 @@ Writes a character array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 88]); let result = data.writeCharArray([97, 98, 88]);
console.log("RpcClient: writeCharArray is " + result); console.log("RpcClient: writeCharArray is " + result);
``` ```
### readCharArray ### readCharArray
readCharArray(dataIn: number[]): void readCharArray(dataIn: number[]): void
...@@ -4740,7 +4680,7 @@ Reads a character array from this **MessageParcel** object. ...@@ -4740,7 +4680,7 @@ Reads a character array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 99]); let result = data.writeCharArray([97, 98, 99]);
console.log("RpcClient: writeCharArray is " + result); console.log("RpcClient: writeCharArray is " + result);
...@@ -4748,7 +4688,6 @@ Reads a character array from this **MessageParcel** object. ...@@ -4748,7 +4688,6 @@ Reads a character array from this **MessageParcel** object.
data.readCharArray(array); data.readCharArray(array);
``` ```
### readCharArray ### readCharArray
readCharArray(): number[] readCharArray(): number[]
...@@ -4765,7 +4704,7 @@ Reads the character array from this **MessageParcel** object. ...@@ -4765,7 +4704,7 @@ Reads the character array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeCharArray([97, 98, 99]); let result = data.writeCharArray([97, 98, 99]);
console.log("RpcClient: writeCharArray is " + result); console.log("RpcClient: writeCharArray is " + result);
...@@ -4773,7 +4712,6 @@ Reads the character array from this **MessageParcel** object. ...@@ -4773,7 +4712,6 @@ Reads the character array from this **MessageParcel** object.
console.log("RpcClient: readCharArray is " + array); console.log("RpcClient: readCharArray is " + array);
``` ```
### writeStringArray ### writeStringArray
writeStringArray(stringArray: string[]): boolean writeStringArray(stringArray: string[]): boolean
...@@ -4792,17 +4730,16 @@ Writes a string array to this **MessageParcel** object. ...@@ -4792,17 +4730,16 @@ Writes a string array to this **MessageParcel** object.
| Type | Description| | Type | Description|
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]); let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result); console.log("RpcClient: writeStringArray is " + result);
``` ```
### readStringArray ### readStringArray
readStringArray(dataIn: string[]): void readStringArray(dataIn: string[]): void
...@@ -4819,7 +4756,7 @@ Reads a string array from this **MessageParcel** object. ...@@ -4819,7 +4756,7 @@ Reads a string array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]); let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result); console.log("RpcClient: writeStringArray is " + result);
...@@ -4827,7 +4764,6 @@ Reads a string array from this **MessageParcel** object. ...@@ -4827,7 +4764,6 @@ Reads a string array from this **MessageParcel** object.
data.readStringArray(array); data.readStringArray(array);
``` ```
### readStringArray ### readStringArray
readStringArray(): string[] readStringArray(): string[]
...@@ -4844,7 +4780,7 @@ Reads the string array from this **MessageParcel** object. ...@@ -4844,7 +4780,7 @@ Reads the string array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let data = rpc.MessageParcel.create(); let data = rpc.MessageParcel.create();
let result = data.writeStringArray(["abc", "def"]); let result = data.writeStringArray(["abc", "def"]);
console.log("RpcClient: writeStringArray is " + result); console.log("RpcClient: writeStringArray is " + result);
...@@ -4852,7 +4788,6 @@ Reads the string array from this **MessageParcel** object. ...@@ -4852,7 +4788,6 @@ Reads the string array from this **MessageParcel** object.
console.log("RpcClient: readStringArray is " + array); console.log("RpcClient: readStringArray is " + array);
``` ```
### writeNoException<sup>8+</sup> ### writeNoException<sup>8+</sup>
writeNoException(): void writeNoException(): void
...@@ -4863,7 +4798,7 @@ Writes information to this **MessageParcel** object indicating that no exception ...@@ -4863,7 +4798,7 @@ Writes information to this **MessageParcel** object indicating that no exception
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -4905,7 +4840,7 @@ Reads the exception information from this **MessageParcel** object. ...@@ -4905,7 +4840,7 @@ Reads the exception information from this **MessageParcel** object.
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -4922,7 +4857,7 @@ Reads the exception information from this **MessageParcel** object. ...@@ -4922,7 +4857,7 @@ Reads the exception information from this **MessageParcel** object.
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let option = new rpc.MessageOption(); let option = new rpc.MessageOption();
...@@ -4967,11 +4902,11 @@ Writes a sequenceable array to this **MessageParcel** object. ...@@ -4967,11 +4902,11 @@ Writes a sequenceable array to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | --------------------------------- | | ------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -4999,7 +4934,6 @@ Writes a sequenceable array to this **MessageParcel** object. ...@@ -4999,7 +4934,6 @@ Writes a sequenceable array to this **MessageParcel** object.
console.log("RpcClient: writeSequenceableArray is " + result); console.log("RpcClient: writeSequenceableArray is " + result);
``` ```
### readSequenceableArray<sup>8+</sup> ### readSequenceableArray<sup>8+</sup>
readSequenceableArray(sequenceableArray: Sequenceable[]): void readSequenceableArray(sequenceableArray: Sequenceable[]): void
...@@ -5016,7 +4950,7 @@ Reads a sequenceable array from this **MessageParcel** object. ...@@ -5016,7 +4950,7 @@ Reads a sequenceable array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -5046,7 +4980,6 @@ Reads a sequenceable array from this **MessageParcel** object. ...@@ -5046,7 +4980,6 @@ Reads a sequenceable array from this **MessageParcel** object.
data.readSequenceableArray(b); data.readSequenceableArray(b);
``` ```
### writeRemoteObjectArray<sup>8+</sup> ### writeRemoteObjectArray<sup>8+</sup>
writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean
...@@ -5065,11 +4998,11 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. ...@@ -5065,11 +4998,11 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | -------------------------------------------------------------------------------------------------------------------- | | ------- | -------------------------------------------------------------------------------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -5099,7 +5032,6 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object. ...@@ -5099,7 +5032,6 @@ Writes an array of **IRemoteObject** objects to this **MessageParcel** object.
console.log("RpcClient: writeRemoteObjectArray is " + result); console.log("RpcClient: writeRemoteObjectArray is " + result);
``` ```
### readRemoteObjectArray<sup>8+</sup> ### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(objects: IRemoteObject[]): void readRemoteObjectArray(objects: IRemoteObject[]): void
...@@ -5116,7 +5048,7 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. ...@@ -5116,7 +5048,7 @@ Reads an **IRemoteObject** array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -5147,7 +5079,6 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. ...@@ -5147,7 +5079,6 @@ Reads an **IRemoteObject** array from this **MessageParcel** object.
data.readRemoteObjectArray(b); data.readRemoteObjectArray(b);
``` ```
### readRemoteObjectArray<sup>8+</sup> ### readRemoteObjectArray<sup>8+</sup>
readRemoteObjectArray(): IRemoteObject[] readRemoteObjectArray(): IRemoteObject[]
...@@ -5164,7 +5095,7 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. ...@@ -5164,7 +5095,7 @@ Reads the **IRemoteObject** array from this **MessageParcel** object.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -5196,12 +5127,11 @@ Reads the **IRemoteObject** array from this **MessageParcel** object. ...@@ -5196,12 +5127,11 @@ Reads the **IRemoteObject** array from this **MessageParcel** object.
console.log("RpcClient: readRemoteObjectArray is " + b); console.log("RpcClient: readRemoteObjectArray is " + b);
``` ```
### closeFileDescriptor<sup>8+</sup> ### closeFileDescriptor<sup>8+</sup>
static closeFileDescriptor(fd: number): void static closeFileDescriptor(fd: number): void
Closes a file descriptor. Closes a file descriptor. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -5213,19 +5143,18 @@ Closes a file descriptor. ...@@ -5213,19 +5143,18 @@ Closes a file descriptor.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let filePath = "path/to/file"; let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
rpc.MessageParcel.closeFileDescriptor(fd); rpc.MessageParcel.closeFileDescriptor(fd);
``` ```
### dupFileDescriptor<sup>8+</sup> ### dupFileDescriptor<sup>8+</sup>
static dupFileDescriptor(fd: number) :number static dupFileDescriptor(fd: number) :number
Duplicates a file descriptor. Duplicates a file descriptor. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -5243,14 +5172,13 @@ Duplicates a file descriptor. ...@@ -5243,14 +5172,13 @@ Duplicates a file descriptor.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let filePath = "path/to/file"; let filePath = "path/to/file";
let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666);
let newFd = rpc.MessageParcel.dupFileDescriptor(fd); let newFd = rpc.MessageParcel.dupFileDescriptor(fd);
``` ```
### containFileDescriptors<sup>8+</sup> ### containFileDescriptors<sup>8+</sup>
containFileDescriptors(): boolean containFileDescriptors(): boolean
...@@ -5263,11 +5191,11 @@ Checks whether this **MessageParcel** object contains a file descriptor. ...@@ -5263,11 +5191,11 @@ Checks whether this **MessageParcel** object contains a file descriptor.
| Type | Description | | Type | Description |
| ------- | ------------------------------------------------------------------ | | ------- | ------------------------------------------------------------------ |
| boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| | boolean |Returns **true** if the **MessageSequence** object contains a file descriptor; returns **false** otherwise.|
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -5279,7 +5207,6 @@ Checks whether this **MessageParcel** object contains a file descriptor. ...@@ -5279,7 +5207,6 @@ Checks whether this **MessageParcel** object contains a file descriptor.
console.log("RpcTest: parcel after write fd containFd result is : " + containFD); console.log("RpcTest: parcel after write fd containFd result is : " + containFD);
``` ```
### writeFileDescriptor<sup>8+</sup> ### writeFileDescriptor<sup>8+</sup>
writeFileDescriptor(fd: number): boolean writeFileDescriptor(fd: number): boolean
...@@ -5302,7 +5229,7 @@ Writes a file descriptor to this **MessageParcel** object. ...@@ -5302,7 +5229,7 @@ Writes a file descriptor to this **MessageParcel** object.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -5311,7 +5238,6 @@ Writes a file descriptor to this **MessageParcel** object. ...@@ -5311,7 +5238,6 @@ Writes a file descriptor to this **MessageParcel** object.
console.log("RpcTest: parcel writeFd result is : " + writeResult); console.log("RpcTest: parcel writeFd result is : " + writeResult);
``` ```
### readFileDescriptor<sup>8+</sup> ### readFileDescriptor<sup>8+</sup>
readFileDescriptor(): number readFileDescriptor(): number
...@@ -5328,7 +5254,7 @@ Reads the file descriptor from this **MessageParcel** object. ...@@ -5328,7 +5254,7 @@ Reads the file descriptor from this **MessageParcel** object.
**Example** **Example**
``` ```ts
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let filePath = "path/to/file"; let filePath = "path/to/file";
...@@ -5338,7 +5264,6 @@ Reads the file descriptor from this **MessageParcel** object. ...@@ -5338,7 +5264,6 @@ Reads the file descriptor from this **MessageParcel** object.
console.log("RpcTest: parcel read fd is : " + readFD); console.log("RpcTest: parcel read fd is : " + readFD);
``` ```
### writeAshmem<sup>8+</sup> ### writeAshmem<sup>8+</sup>
writeAshmem(ashmem: Ashmem): boolean writeAshmem(ashmem: Ashmem): boolean
...@@ -5357,18 +5282,17 @@ Writes an anonymous shared object to this **MessageParcel** object. ...@@ -5357,18 +5282,17 @@ Writes an anonymous shared object to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | -------------------------------------------------------------------- | | ------- | -------------------------------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem); let isWriteSuccess = parcel.writeAshmem(ashmem);
console.log("RpcTest: write ashmem to result is : " + isWriteSuccess); console.log("RpcTest: write ashmem to result is : " + isWriteSuccess);
``` ```
### readAshmem<sup>8+</sup> ### readAshmem<sup>8+</sup>
readAshmem(): Ashmem readAshmem(): Ashmem
...@@ -5385,7 +5309,7 @@ Reads the anonymous shared object from this **MessageParcel** object. ...@@ -5385,7 +5309,7 @@ Reads the anonymous shared object from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024);
let isWriteSuccess = parcel.writeAshmem(ashmem); let isWriteSuccess = parcel.writeAshmem(ashmem);
...@@ -5394,7 +5318,6 @@ Reads the anonymous shared object from this **MessageParcel** object. ...@@ -5394,7 +5318,6 @@ Reads the anonymous shared object from this **MessageParcel** object.
console.log("RpcTest: read ashmem to result is : " + readAshmem); console.log("RpcTest: read ashmem to result is : " + readAshmem);
``` ```
### getRawDataCapacity<sup>8+</sup> ### getRawDataCapacity<sup>8+</sup>
getRawDataCapacity(): number getRawDataCapacity(): number
...@@ -5411,13 +5334,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* ...@@ -5411,13 +5334,12 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel*
**Example** **Example**
``` ```ts
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let result = parcel.getRawDataCapacity(); let result = parcel.getRawDataCapacity();
console.log("RpcTest: parcel get RawDataCapacity result is : " + result); console.log("RpcTest: parcel get RawDataCapacity result is : " + result);
``` ```
### writeRawData<sup>8+</sup> ### writeRawData<sup>8+</sup>
writeRawData(rawData: number[], size: number): boolean writeRawData(rawData: number[], size: number): boolean
...@@ -5437,18 +5359,17 @@ Writes raw data to this **MessageParcel** object. ...@@ -5437,18 +5359,17 @@ Writes raw data to this **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let arr = [1, 2, 3, 4, 5]; let arr = [1, 2, 3, 4, 5];
let isWriteSuccess = parcel.writeRawData(arr, arr.length); let isWriteSuccess = parcel.writeRawData(arr, arr.length);
console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess); console.log("RpcTest: parcel write raw data result is : " + isWriteSuccess);
``` ```
### readRawData<sup>8+</sup> ### readRawData<sup>8+</sup>
readRawData(size: number): number[] readRawData(size: number): number[]
...@@ -5471,7 +5392,7 @@ Reads raw data from this **MessageParcel** object. ...@@ -5471,7 +5392,7 @@ Reads raw data from this **MessageParcel** object.
**Example** **Example**
``` ```ts
let parcel = new rpc.MessageParcel(); let parcel = new rpc.MessageParcel();
let arr = [1, 2, 3, 4, 5]; let arr = [1, 2, 3, 4, 5];
let isWriteSuccess = parcel.writeRawData(arr, arr.length); let isWriteSuccess = parcel.writeRawData(arr, arr.length);
...@@ -5480,7 +5401,6 @@ Reads raw data from this **MessageParcel** object. ...@@ -5480,7 +5401,6 @@ Reads raw data from this **MessageParcel** object.
console.log("RpcTest: parcel read raw data result is : " + result); console.log("RpcTest: parcel read raw data result is : " + result);
``` ```
## Parcelable<sup>9+</sup> ## Parcelable<sup>9+</sup>
Writes an object to a **MessageSequence** and reads it from the **MessageSequence** during IPC. Writes an object to a **MessageSequence** and reads it from the **MessageSequence** during IPC.
...@@ -5504,10 +5424,9 @@ Marshals this **Parcelable** object into a **MessageSequence** object. ...@@ -5504,10 +5424,9 @@ Marshals this **Parcelable** object into a **MessageSequence** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MyParcelable { class MyParcelable {
num: number; num: number;
str: string; str: string;
...@@ -5535,7 +5454,6 @@ Marshals this **Parcelable** object into a **MessageSequence** object. ...@@ -5535,7 +5454,6 @@ Marshals this **Parcelable** object into a **MessageSequence** object.
console.log("RpcClient: readParcelable is " + result2); console.log("RpcClient: readParcelable is " + result2);
``` ```
### unmarshalling ### unmarshalling
unmarshalling(dataIn: MessageSequence): boolean unmarshalling(dataIn: MessageSequence): boolean
...@@ -5558,7 +5476,7 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object. ...@@ -5558,7 +5476,7 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object.
**Example** **Example**
``` ```ts
class MyParcelable { class MyParcelable {
num: number; num: number;
str: string; str: string;
...@@ -5586,7 +5504,6 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object. ...@@ -5586,7 +5504,6 @@ Unmarshals this **Parcelable** object from a **MessageSequence** object.
console.log("RpcClient: readParcelable is " + result2); console.log("RpcClient: readParcelable is " + result2);
``` ```
## Sequenceable<sup>(deprecated)</sup> ## Sequenceable<sup>(deprecated)</sup>
>This class is no longer maintained since API version 9. You are advised to use the [Parcelable](#parcelable9). >This class is no longer maintained since API version 9. You are advised to use the [Parcelable](#parcelable9).
...@@ -5612,10 +5529,9 @@ Marshals the sequenceable object into a **MessageParcel** object. ...@@ -5612,10 +5529,9 @@ Marshals the sequenceable object into a **MessageParcel** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -5643,7 +5559,6 @@ Marshals the sequenceable object into a **MessageParcel** object. ...@@ -5643,7 +5559,6 @@ Marshals the sequenceable object into a **MessageParcel** object.
console.log("RpcClient: readSequenceable is " + result2); console.log("RpcClient: readSequenceable is " + result2);
``` ```
### unmarshalling ### unmarshalling
unmarshalling(dataIn: MessageParcel): boolean unmarshalling(dataIn: MessageParcel): boolean
...@@ -5666,7 +5581,7 @@ Unmarshals this sequenceable object from a **MessageParcel** object. ...@@ -5666,7 +5581,7 @@ Unmarshals this sequenceable object from a **MessageParcel** object.
**Example** **Example**
``` ```ts
class MySequenceable { class MySequenceable {
num: number; num: number;
str: string; str: string;
...@@ -5694,7 +5609,6 @@ Unmarshals this sequenceable object from a **MessageParcel** object. ...@@ -5694,7 +5609,6 @@ Unmarshals this sequenceable object from a **MessageParcel** object.
console.log("RpcClient: readSequenceable is " + result2); console.log("RpcClient: readSequenceable is " + result2);
``` ```
## IRemoteBroker ## IRemoteBroker
Provides the holder of a remote proxy object. Provides the holder of a remote proxy object.
...@@ -5715,17 +5629,38 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl ...@@ -5715,17 +5629,38 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
**Example** **Example**
``` ```ts
class TestAbility extends rpc.RemoteObject { class TestAbility extends rpc.RemoteObject {
asObject() { asObject() {
return this; return this;
} }
} }
let remoteObject = new TestAbility().asObject();
``` ```
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility";
let proxy;
let connect = {
onConnect: function (elementName, remoteProxy) {
console.log("RpcClient: js onConnect called.");
proxy = remoteProxy;
},
onDisconnect: function (elementName) {
console.log("RpcClient: onDisconnect");
},
onFailed: function () {
console.log("RpcClient: onFailed");
}
};
let want = {
"bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.EntryAbility",
};
FA.connectAbility(want, connect);
class TestProxy { class TestProxy {
remote: rpc.RemoteObject; remote: rpc.RemoteObject;
constructor(remote) { constructor(remote) {
...@@ -5735,6 +5670,8 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl ...@@ -5735,6 +5670,8 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl
return this.remote; return this.remote;
} }
} }
let iRemoteObject = new TestProxy(proxy).asObject();
``` ```
## DeathRecipient ## DeathRecipient
...@@ -5751,7 +5688,7 @@ Called to perform subsequent operations when a death notification of the remote ...@@ -5751,7 +5688,7 @@ Called to perform subsequent operations when a death notification of the remote
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -5795,7 +5732,7 @@ Provides methods to query of obtain interface descriptors, add or delete death n ...@@ -5795,7 +5732,7 @@ Provides methods to query of obtain interface descriptors, add or delete death n
getLocalInterface(descriptor: string): IRemoteBroker getLocalInterface(descriptor: string): IRemoteBroker
Obtains the interface. Obtains the interface descriptor.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -5817,7 +5754,7 @@ Obtains the interface. ...@@ -5817,7 +5754,7 @@ Obtains the interface.
queryLocalInterface(descriptor: string): IRemoteBroker queryLocalInterface(descriptor: string): IRemoteBroker
Obtains the interface. Queries the interface descriptor.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -5833,7 +5770,6 @@ Obtains the interface. ...@@ -5833,7 +5770,6 @@ Obtains the interface.
| ------------- | --------------------------------------------- | | ------------- | --------------------------------------------- |
| IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.|
### sendRequest<sup>(deprecated)</sup> ### sendRequest<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -5857,7 +5793,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -5857,7 +5793,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
...@@ -5928,7 +5864,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -5928,7 +5864,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. | | callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -5949,12 +5884,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -5949,12 +5884,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. | | callback | AsyncCallback&lt;SendRequestResult&gt; | Yes | Callback for receiving the sending result. |
### registerDeathRecipient<sup>9+</sup> ### registerDeathRecipient<sup>9+</sup>
registerDeathRecipient(recipient: DeathRecipient, flags: number): void registerDeathRecipient(recipient: DeathRecipient, flags: number): void
Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -5962,7 +5896,7 @@ Adds a callback for receiving death notifications of the remote object. This met ...@@ -5962,7 +5896,7 @@ Adds a callback for receiving death notifications of the remote object. This met
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------- | ---- | -------------- | | --------- | --------------------------------- | ---- | -------------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.|
| flags | number | Yes | Flag of the death notification.| | flags | number | Yes | Flag of the death notification.|
**Error Code** **Error Code**
...@@ -5973,7 +5907,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -5973,7 +5907,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ------- | -------- | | ------- | -------- |
| 1900008 | proxy or remote object is invalid | | 1900008 | proxy or remote object is invalid |
### addDeathrecipient<sup>(deprecated)</sup> ### addDeathrecipient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). >This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9).
...@@ -5995,14 +5928,14 @@ Adds a callback for receiving death notifications of the remote object. This met ...@@ -5995,14 +5928,14 @@ Adds a callback for receiving death notifications of the remote object. This met
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.|
### unregisterDeathRecipient<sup>9+</sup> ### unregisterDeathRecipient<sup>9+</sup>
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void
Removes the callback used to receive death notifications of the remote object. Unregisters the callback used to receive death notifications of the remote object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -6010,7 +5943,7 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6010,7 +5943,7 @@ Removes the callback used to receive death notifications of the remote object.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------- | ---- | -------------- | | --------- | --------------------------------- | ---- | -------------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.|
| flags | number | Yes | Flag of the death notification.| | flags | number | Yes | Flag of the death notification.|
**Error Code** **Error Code**
...@@ -6021,7 +5954,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6021,7 +5954,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
| ------- | -------- | | ------- | -------- |
| 1900008 | proxy or remote object is invalid | | 1900008 | proxy or remote object is invalid |
### removeDeathRecipient<sup>(deprecated)</sup> ### removeDeathRecipient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). >This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9).
...@@ -6043,8 +5975,7 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6043,8 +5975,7 @@ Removes the callback used to receive death notifications of the remote object.
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| | boolean | Returns **true** if the callback is removed; returns **false** otherwise.|
### getDescriptor<sup>9+</sup> ### getDescriptor<sup>9+</sup>
...@@ -6115,7 +6046,6 @@ Provides APIs to implement **IRemoteObject**. ...@@ -6115,7 +6046,6 @@ Provides APIs to implement **IRemoteObject**.
| MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. | | MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. |
| MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. | | MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. |
### sendRequest<sup>(deprecated)</sup> ### sendRequest<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -6139,11 +6069,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6139,11 +6069,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6160,7 +6090,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6160,7 +6090,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let option = new rpc.MessageOption(); let option = new rpc.MessageOption();
...@@ -6181,7 +6111,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6181,7 +6111,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
reply.reclaim(); reply.reclaim();
``` ```
### sendMessageRequest<sup>9+</sup> ### sendMessageRequest<sup>9+</sup>
sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise&lt;RequestResult&gt; sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise&lt;RequestResult&gt;
...@@ -6207,7 +6136,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6207,7 +6136,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6224,7 +6153,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6224,7 +6153,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let option = new rpc.MessageOption(); let option = new rpc.MessageOption();
...@@ -6251,7 +6180,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6251,7 +6180,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
}); });
``` ```
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -6279,7 +6207,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6279,7 +6207,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6296,7 +6224,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6296,7 +6224,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let option = new rpc.MessageOption(); let option = new rpc.MessageOption();
...@@ -6341,10 +6269,9 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6341,10 +6269,9 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
| options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. |
| callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. | | callback | AsyncCallback&lt;RequestResult&gt; | Yes | Callback for receiving the sending result. |
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6361,7 +6288,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6361,7 +6288,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
function sendRequestCallback(result) { function sendRequestCallback(result) {
if (result.errCode === 0) { if (result.errCode === 0) {
...@@ -6390,7 +6317,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -6390,7 +6317,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
} }
``` ```
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -6413,7 +6339,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6413,7 +6339,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6430,7 +6356,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6430,7 +6356,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
function sendRequestCallback(result) { function sendRequestCallback(result) {
if (result.errCode === 0) { if (result.errCode === 0) {
...@@ -6454,7 +6380,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -6454,7 +6380,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
proxy.sendRequest(1, data, reply, option, sendRequestCallback); proxy.sendRequest(1, data, reply, option, sendRequestCallback);
``` ```
### getLocalInterface<sup>9+</sup> ### getLocalInterface<sup>9+</sup>
getLocalInterface(interface: string): IRemoteBroker getLocalInterface(interface: string): IRemoteBroker
...@@ -6485,7 +6410,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6485,7 +6410,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6502,7 +6427,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6502,7 +6427,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}; };
let want = { let want = {
"bundleName":"com.ohos.server", "bundleName":"com.ohos.server",
"abilityName":"com.ohos.server.MainAbility", "abilityName":"com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
try { try {
...@@ -6514,7 +6439,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6514,7 +6439,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### queryLocalInterface<sup>(deprecated)</sup> ### queryLocalInterface<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). >This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9).
...@@ -6539,7 +6463,7 @@ Obtains the **LocalInterface** object of an interface token. ...@@ -6539,7 +6463,7 @@ Obtains the **LocalInterface** object of an interface token.
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6556,19 +6480,18 @@ Obtains the **LocalInterface** object of an interface token. ...@@ -6556,19 +6480,18 @@ Obtains the **LocalInterface** object of an interface token.
}; };
let want = { let want = {
"bundleName":"com.ohos.server", "bundleName":"com.ohos.server",
"abilityName":"com.ohos.server.MainAbility", "abilityName":"com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let broker = proxy.queryLocalInterface("testObject"); let broker = proxy.queryLocalInterface("testObject");
console.log("RpcClient: queryLocalInterface is " + broker); console.log("RpcClient: queryLocalInterface is " + broker);
``` ```
### registerDeathRecipient<sup>9+</sup> ### registerDeathRecipient<sup>9+</sup>
registerDeathRecipient(recipient: DeathRecipient, flags: number): void registerDeathRecipient(recipient: DeathRecipient, flags: number): void
Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. Registers a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -6576,7 +6499,7 @@ Adds a callback for receiving death notifications of the remote object. This met ...@@ -6576,7 +6499,7 @@ Adds a callback for receiving death notifications of the remote object. This met
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------- | ---- | -------------- | | --------- | --------------------------------- | ---- | -------------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to register.|
| flags | number | Yes | Flag of the death notification.| | flags | number | Yes | Flag of the death notification.|
**Error Code** **Error Code**
...@@ -6589,7 +6512,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6589,7 +6512,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6606,7 +6529,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6606,7 +6529,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
class MyDeathRecipient { class MyDeathRecipient {
...@@ -6623,7 +6546,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6623,7 +6546,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### addDeathRecippient<sup>(deprecated)</sup> ### addDeathRecippient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). >This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9).
...@@ -6645,11 +6567,11 @@ Adds a callback for receiving the death notifications of the remote object, incl ...@@ -6645,11 +6567,11 @@ Adds a callback for receiving the death notifications of the remote object, incl
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| | boolean | Returns **true** if the callback is added successfully; return **false** otherwise.|
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6666,7 +6588,7 @@ Adds a callback for receiving the death notifications of the remote object, incl ...@@ -6666,7 +6588,7 @@ Adds a callback for receiving the death notifications of the remote object, incl
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
class MyDeathRecipient { class MyDeathRecipient {
...@@ -6682,7 +6604,7 @@ Adds a callback for receiving the death notifications of the remote object, incl ...@@ -6682,7 +6604,7 @@ Adds a callback for receiving the death notifications of the remote object, incl
unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean
Removes the callback used to receive death notifications of the remote object. Unregisters the callback used to receive death notifications of the remote object.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -6690,7 +6612,7 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6690,7 +6612,7 @@ Removes the callback used to receive death notifications of the remote object.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------- | ---- | -------------- | | --------- | --------------------------------- | ---- | -------------- |
| recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to unregister.|
| flags | number | Yes | Flag of the death notification.| | flags | number | Yes | Flag of the death notification.|
**Error Code** **Error Code**
...@@ -6703,7 +6625,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6703,7 +6625,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6720,7 +6642,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6720,7 +6642,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
class MyDeathRecipient { class MyDeathRecipient {
...@@ -6738,7 +6660,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6738,7 +6660,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### removeDeathRecipient<sup>(deprecated)</sup> ### removeDeathRecipient<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). >This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9).
...@@ -6760,11 +6681,11 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6760,11 +6681,11 @@ Removes the callback used to receive death notifications of the remote object.
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| | boolean | Returns **true** if the callback is removed; returns **false** otherwise.|
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6781,7 +6702,7 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6781,7 +6702,7 @@ Removes the callback used to receive death notifications of the remote object.
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
class MyDeathRecipient { class MyDeathRecipient {
...@@ -6794,7 +6715,6 @@ Removes the callback used to receive death notifications of the remote object. ...@@ -6794,7 +6715,6 @@ Removes the callback used to receive death notifications of the remote object.
proxy.removeDeathRecipient(deathRecipient, 0); proxy.removeDeathRecipient(deathRecipient, 0);
``` ```
### getDescriptor<sup>9+</sup> ### getDescriptor<sup>9+</sup>
getDescriptor(): string getDescriptor(): string
...@@ -6820,7 +6740,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6820,7 +6740,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6837,7 +6757,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6837,7 +6757,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
try { try {
...@@ -6849,7 +6769,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -6849,7 +6769,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### getInterfaceDescriptor<sup>(deprecated)</sup> ### getInterfaceDescriptor<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). >This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9).
...@@ -6868,7 +6787,7 @@ Obtains the interface descriptor of this proxy object. ...@@ -6868,7 +6787,7 @@ Obtains the interface descriptor of this proxy object.
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6885,14 +6804,13 @@ Obtains the interface descriptor of this proxy object. ...@@ -6885,14 +6804,13 @@ Obtains the interface descriptor of this proxy object.
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let descriptor = proxy.getInterfaceDescriptor(); let descriptor = proxy.getInterfaceDescriptor();
console.log("RpcClient: descriptor is " + descriptor); console.log("RpcClient: descriptor is " + descriptor);
``` ```
### isObjectDead ### isObjectDead
isObjectDead(): boolean isObjectDead(): boolean
...@@ -6909,7 +6827,7 @@ Checks whether the **RemoteObject** is dead. ...@@ -6909,7 +6827,7 @@ Checks whether the **RemoteObject** is dead.
**Example** **Example**
``` ```ts
import FA from "@ohos.ability.featureAbility"; import FA from "@ohos.ability.featureAbility";
let proxy; let proxy;
let connect = { let connect = {
...@@ -6926,14 +6844,13 @@ Checks whether the **RemoteObject** is dead. ...@@ -6926,14 +6844,13 @@ Checks whether the **RemoteObject** is dead.
}; };
let want = { let want = {
"bundleName": "com.ohos.server", "bundleName": "com.ohos.server",
"abilityName": "com.ohos.server.MainAbility", "abilityName": "com.ohos.server.EntryAbility",
}; };
FA.connectAbility(want, connect); FA.connectAbility(want, connect);
let isDead = proxy.isObjectDead(); let isDead = proxy.isObjectDead();
console.log("RpcClient: isObjectDead is " + isDead); console.log("RpcClient: isObjectDead is " + isDead);
``` ```
## MessageOption ## MessageOption
Provides common message options (flag and wait time). Use the specified flag to construct the **MessageOption** object. Provides common message options (flag and wait time). Use the specified flag to construct the **MessageOption** object.
...@@ -6963,6 +6880,16 @@ A constructor used to create a **MessageOption** object. ...@@ -6963,6 +6880,16 @@ A constructor used to create a **MessageOption** object.
| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.|
**Example**
```ts
class TestRemoteObject extends rpc.MessageOption {
constructor(async) {
super(async);
}
}
```
### constructor ### constructor
constructor(syncFlags?: number, waitTime?: number) constructor(syncFlags?: number, waitTime?: number)
...@@ -6978,7 +6905,15 @@ A constructor used to create a **MessageOption** object. ...@@ -6978,7 +6905,15 @@ A constructor used to create a **MessageOption** object.
| syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. |
| waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.|
**Example**
```ts
class TestRemoteObject extends rpc.MessageOption {
constructor(syncFlags,waitTime) {
super(syncFlags,waitTime);
}
}
```
### isAsync<sup>9+</sup> ### isAsync<sup>9+</sup>
isAsync(): boolean; isAsync(): boolean;
...@@ -6991,8 +6926,14 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously. ...@@ -6991,8 +6926,14 @@ Checks whether **SendMessageRequest** is called synchronously or asynchronously.
| Type | Description | | Type | Description |
| ------- | ------------------------------------ | | ------- | ------------------------------------ |
| boolean | Call mode obtained.| | boolean | Returns **true** if **SendMessageRequest** is called synchronously; returns **false** if **SendMessageRequest** is called asynchronously.|
**Example**
```ts
let option = new rpc.MessageOption();
let isAsync = option.isAsync();
```
### setAsync<sup>9+</sup> ### setAsync<sup>9+</sup>
...@@ -7002,6 +6943,13 @@ Sets whether **SendMessageRequest** is called synchronously or asynchronously. ...@@ -7002,6 +6943,13 @@ Sets whether **SendMessageRequest** is called synchronously or asynchronously.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
**Example**
```ts
let option = new rpc.MessageOption();
let setAsync = option.setAsync(true);
console.log("Set synchronization flag");
```
### getFlags ### getFlags
...@@ -7017,6 +6965,22 @@ Obtains the call flag, which can be synchronous or asynchronous. ...@@ -7017,6 +6965,22 @@ Obtains the call flag, which can be synchronous or asynchronous.
| ------ | ------------------------------------ | | ------ | ------------------------------------ |
| number | Call mode obtained.| | number | Call mode obtained.|
**Example**
```ts
try {
let option = new rpc.MessageOption();
console.info("create object successfully.");
let flog = option.getFlags();
console.info("run getFlags success, flog is " + flog);
option.setFlags(1)
console.info("run setFlags success");
let flog2 = option.getFlags();
console.info("run getFlags success, flog2 is " + flog2);
} catch (error) {
console.info("error " + error);
}
```
### setFlags ### setFlags
...@@ -7032,6 +6996,19 @@ Sets the call flag, which can be synchronous or asynchronous. ...@@ -7032,6 +6996,19 @@ Sets the call flag, which can be synchronous or asynchronous.
| ------ | ------ | ---- | ------------------------ | | ------ | ------ | ---- | ------------------------ |
| flags | number | Yes | Call flag to set.| | flags | number | Yes | Call flag to set.|
**Example**
```ts
try {
let option = new rpc.MessageOption();
option.setFlags(1)
console.info("run setFlags success");
let flog = option.getFlags();
console.info("run getFlags success, flog is " + flog);
} catch (error) {
console.info("error " + error);
}
```
### getWaitTime ### getWaitTime
...@@ -7047,6 +7024,20 @@ Obtains the maximum wait time for this RPC call. ...@@ -7047,6 +7024,20 @@ Obtains the maximum wait time for this RPC call.
| ------ | ----------------- | | ------ | ----------------- |
| number | Maximum wait time obtained.| | number | Maximum wait time obtained.|
**Example**
```ts
try {
let option = new rpc.MessageOption();
let time = option.getWaitTime();
console.info("run getWaitTime success");
option.setWaitTime(16);
let time2 = option.getWaitTime();
console.info("run getWaitTime success, time is " + time);
} catch (error) {
console.info("error " + error);
}
```
### setWaitTime ### setWaitTime
...@@ -7062,6 +7053,18 @@ Sets the maximum wait time for this RPC call. ...@@ -7062,6 +7053,18 @@ Sets the maximum wait time for this RPC call.
| -------- | ------ | ---- | --------------------- | | -------- | ------ | ---- | --------------------- |
| waitTime | number | Yes | Maximum wait time to set.| | waitTime | number | Yes | Maximum wait time to set.|
**Example**
```ts
try {
let option = new rpc.MessageOption();
option.setWaitTime(16);
let time = option.getWaitTime();
console.info("run getWaitTime success, time is " + time);
} catch (error) {
console.info("error " + error);
}
```
## IPCSkeleton ## IPCSkeleton
...@@ -7071,7 +7074,7 @@ Obtains IPC context information, including the UID and PID, local and remote dev ...@@ -7071,7 +7074,7 @@ Obtains IPC context information, including the UID and PID, local and remote dev
static getContextObject(): IRemoteObject static getContextObject(): IRemoteObject
Obtains the system capability manager. Obtains the system capability manager. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7083,17 +7086,16 @@ Obtains the system capability manager. ...@@ -7083,17 +7086,16 @@ Obtains the system capability manager.
**Example** **Example**
``` ```ts
let samgr = rpc.IPCSkeleton.getContextObject(); let samgr = rpc.IPCSkeleton.getContextObject();
console.log("RpcServer: getContextObject result: " + samgr); console.log("RpcServer: getContextObject result: " + samgr);
``` ```
### getCallingPid ### getCallingPid
static getCallingPid(): number static getCallingPid(): number
Obtains the PID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned. Obtains the PID of the caller. This API is a static method, which is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the PID of the process will be returned.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7105,7 +7107,7 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob ...@@ -7105,7 +7107,7 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callerPid = rpc.IPCSkeleton.getCallingPid(); let callerPid = rpc.IPCSkeleton.getCallingPid();
...@@ -7115,12 +7117,11 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob ...@@ -7115,12 +7117,11 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob
} }
``` ```
### getCallingUid ### getCallingUid
static getCallingUid(): number static getCallingUid(): number
Obtains the UID of the caller. This method is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned. Obtains the UID of the caller. This API is a static method, which is invoked by the **RemoteObject** object in the **onRemoteRequest** method. If this method is not invoked in the IPC context (**onRemoteRequest**), the UID of the process will be returned.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7132,7 +7133,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob ...@@ -7132,7 +7133,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callerUid = rpc.IPCSkeleton.getCallingUid(); let callerUid = rpc.IPCSkeleton.getCallingUid();
...@@ -7142,7 +7143,6 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob ...@@ -7142,7 +7143,6 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob
} }
``` ```
### getCallingTokenId<sup>8+</sup> ### getCallingTokenId<sup>8+</sup>
static getCallingTokenId(): number; static getCallingTokenId(): number;
...@@ -7151,16 +7151,15 @@ Obtains the caller's token ID, which is used to verify the caller identity. ...@@ -7151,16 +7151,15 @@ Obtains the caller's token ID, which is used to verify the caller identity.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | --------------------- | | ------ | --------------------- |
| number | Token ID of the caller obtained.| | number | Token ID of the caller obtained.|
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); let callerTokenId = rpc.IPCSkeleton.getCallingTokenId();
...@@ -7187,7 +7186,7 @@ Obtains the ID of the device hosting the caller's process. ...@@ -7187,7 +7186,7 @@ Obtains the ID of the device hosting the caller's process.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID();
...@@ -7197,12 +7196,11 @@ Obtains the ID of the device hosting the caller's process. ...@@ -7197,12 +7196,11 @@ Obtains the ID of the device hosting the caller's process.
} }
``` ```
### getLocalDeviceID ### getLocalDeviceID
static getLocalDeviceID(): string static getLocalDeviceID(): string
Obtains the local device ID. Obtains the local device ID. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7214,7 +7212,7 @@ Obtains the local device ID. ...@@ -7214,7 +7212,7 @@ Obtains the local device ID.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID(); let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID();
...@@ -7224,12 +7222,11 @@ Obtains the local device ID. ...@@ -7224,12 +7222,11 @@ Obtains the local device ID.
} }
``` ```
### isLocalCalling ### isLocalCalling
static isLocalCalling(): boolean static isLocalCalling(): boolean
Checks whether the remote process is a process of the local device. Checks whether the remote process is a process of the local device. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7241,7 +7238,7 @@ Checks whether the remote process is a process of the local device. ...@@ -7241,7 +7238,7 @@ Checks whether the remote process is a process of the local device.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let isLocalCalling = rpc.IPCSkeleton.isLocalCalling(); let isLocalCalling = rpc.IPCSkeleton.isLocalCalling();
...@@ -7251,12 +7248,11 @@ Checks whether the remote process is a process of the local device. ...@@ -7251,12 +7248,11 @@ Checks whether the remote process is a process of the local device.
} }
``` ```
### flushCmdBuffer<sup>9+</sup> ### flushCmdBuffer<sup>9+</sup>
static flushCmdBuffer(object: IRemoteObject): void static flushCmdBuffer(object: IRemoteObject): void
Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. This API is a static method. It is recommended that this method be called before any time-sensitive operation is performed.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7269,7 +7265,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp ...@@ -7269,7 +7265,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7284,14 +7280,13 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp ...@@ -7284,14 +7280,13 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp
} }
``` ```
### flushCommands<sup>(deprecated)</sup> ### flushCommands<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [flushCmdBuffer](#flushcmdbuffer9). >This API is no longer maintained since API version 9. You are advised to use [flushCmdBuffer](#flushcmdbuffer9).
static flushCommands(object: IRemoteObject): number static flushCommands(object: IRemoteObject): number
Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. This API is a static method. It is recommended that this method be called before any time-sensitive operation is performed.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7309,7 +7304,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp ...@@ -7309,7 +7304,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -7338,7 +7333,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp ...@@ -7338,7 +7333,7 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp
static resetCallingIdentity(): string static resetCallingIdentity(): string
Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. Changes the UID and PID of the remote user to the UID and PID of the local user. This API is a static method. You can use it in scenarios such as identity authentication.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7350,7 +7345,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. ...@@ -7350,7 +7345,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity();
...@@ -7365,7 +7360,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. ...@@ -7365,7 +7360,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user.
static restoreCallingIdentity(identity: string): void static restoreCallingIdentity(identity: string): void
Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. Changes the UID and PID of the remote user to the UID and PID of the local user. This API is a static method. You can use it in scenarios such as identity authentication.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7377,7 +7372,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. ...@@ -7377,7 +7372,7 @@ Changes the UID and PID of the remote user to the UID and PID of the local user.
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = null; let callingIdentity = null;
...@@ -7392,14 +7387,13 @@ Changes the UID and PID of the remote user to the UID and PID of the local user. ...@@ -7392,14 +7387,13 @@ Changes the UID and PID of the remote user to the UID and PID of the local user.
} }
``` ```
### setCallingIdentity<sup>(deprecated)</sup> ### setCallingIdentity<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [restoreCallingIdentity](#restorecallingidentity9). >This API is no longer maintained since API version 9. You are advised to use [restoreCallingIdentity](#restorecallingidentity9).
static setCallingIdentity(identity: string): boolean static setCallingIdentity(identity: string): boolean
Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. Restores the UID and PID of the remote user. This API is a static method. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -7417,7 +7411,7 @@ Restores the UID and PID of the remote user. It is usually called when the UID a ...@@ -7417,7 +7411,7 @@ Restores the UID and PID of the remote user. It is usually called when the UID a
**Example** **Example**
``` ```ts
class Stub extends rpc.RemoteObject { class Stub extends rpc.RemoteObject {
onRemoteMessageRequest(code, data, reply, option) { onRemoteMessageRequest(code, data, reply, option) {
let callingIdentity = null; let callingIdentity = null;
...@@ -7433,7 +7427,6 @@ Restores the UID and PID of the remote user. It is usually called when the UID a ...@@ -7433,7 +7427,6 @@ Restores the UID and PID of the remote user. It is usually called when the UID a
} }
``` ```
## RemoteObject ## RemoteObject
Provides methods to implement **RemoteObject**. The service provider must inherit from this class. Provides methods to implement **RemoteObject**. The service provider must inherit from this class.
...@@ -7476,11 +7469,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -7476,11 +7469,11 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
| Type | Description | | Type | Description |
| ------- | --------------------------------------------- | | ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the message is sent successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -7519,7 +7512,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -7519,7 +7512,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
reply.reclaim(); reply.reclaim();
``` ```
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -7547,7 +7539,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -7547,7 +7539,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -7617,7 +7609,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -7617,7 +7609,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7648,7 +7640,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -7648,7 +7640,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
}); });
``` ```
### sendMessageRequest<sup>9+</sup> ### sendMessageRequest<sup>9+</sup>
sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback&lt;RequestResult&gt;): void sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback&lt;RequestResult&gt;): void
...@@ -7669,7 +7660,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -7669,7 +7660,7 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7697,7 +7688,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn ...@@ -7697,7 +7688,6 @@ Sends a **MessageSequence** message to the remote process in synchronous or asyn
testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback); testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback);
``` ```
### sendRequest<sup>8+(deprecated)</sup> ### sendRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9).
...@@ -7720,7 +7710,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -7720,7 +7710,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -7762,7 +7752,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ...@@ -7762,7 +7752,6 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch
testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback); testRemoteObject.sendRequest(1, data, reply, option, sendRequestCallback);
``` ```
### onRemoteRequest<sup>8+(deprecated)</sup> ### onRemoteRequest<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [onRemoteMessageRequest](#onremotemessagerequest9). >This API is no longer maintained since API version 9. You are advised to use [onRemoteMessageRequest](#onremotemessagerequest9).
...@@ -7790,7 +7779,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7790,7 +7779,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Example** **Example**
```ets ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -7847,12 +7836,12 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7847,12 +7836,12 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
| Type | Description | | Type | Description |
| ----------------- | ---------------------------------------------------------------------------------------------- | | ----------------- | ---------------------------------------------------------------------------------------------- |
| boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. The value **true** means the operation is successful; the value **false** means the opposite.|
| Promise\<boolean> | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | | Promise\<boolean> | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. |
**Example**: Overload **onRemoteMessageRequest** to process requests synchronously. **Example**: Overload **onRemoteMessageRequest** to process requests synchronously.
```ets ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7872,7 +7861,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7872,7 +7861,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Example**: Overload **onRemoteMessageRequest** to process requests asynchronously. **Example**: Overload **onRemoteMessageRequest** to process requests asynchronously.
```ets ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7895,7 +7884,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7895,7 +7884,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests synchronously. **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests synchronously.
```ets ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7926,7 +7915,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7926,7 +7915,7 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
**Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests asynchronously. **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests asynchronously.
```ets ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7957,7 +7946,6 @@ Provides a response to **sendMessageRequest()**. The server processes the reques ...@@ -7957,7 +7946,6 @@ Provides a response to **sendMessageRequest()**. The server processes the reques
} }
``` ```
### getCallingUid ### getCallingUid
getCallingUid(): number getCallingUid(): number
...@@ -7973,7 +7961,7 @@ Obtains the UID of the remote process. ...@@ -7973,7 +7961,7 @@ Obtains the UID of the remote process.
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -7999,7 +7987,7 @@ Obtains the PID of the remote process. ...@@ -7999,7 +7987,7 @@ Obtains the PID of the remote process.
**Example** **Example**
``` ```ts
class TestRemoteObject extends rpc.RemoteObject { class TestRemoteObject extends rpc.RemoteObject {
constructor(descriptor) { constructor(descriptor) {
super(descriptor); super(descriptor);
...@@ -8013,7 +8001,7 @@ Obtains the PID of the remote process. ...@@ -8013,7 +8001,7 @@ Obtains the PID of the remote process.
getLocalInterface(descriptor: string): IRemoteBroker getLocalInterface(descriptor: string): IRemoteBroker
Obtains the interface. Obtains the interface descriptor.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -8032,7 +8020,7 @@ Obtains the interface. ...@@ -8032,7 +8020,7 @@ Obtains the interface.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8057,7 +8045,6 @@ Obtains the interface. ...@@ -8057,7 +8045,6 @@ Obtains the interface.
} }
``` ```
### queryLocalInterface<sup>(deprecated)</sup> ### queryLocalInterface<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). >This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9).
...@@ -8082,7 +8069,7 @@ Checks whether the remote object corresponding to the specified interface token ...@@ -8082,7 +8069,7 @@ Checks whether the remote object corresponding to the specified interface token
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8106,7 +8093,6 @@ Checks whether the remote object corresponding to the specified interface token ...@@ -8106,7 +8093,6 @@ Checks whether the remote object corresponding to the specified interface token
let broker = testRemoteObject.queryLocalInterface("testObject"); let broker = testRemoteObject.queryLocalInterface("testObject");
``` ```
### getDescriptor<sup>9+</sup> ### getDescriptor<sup>9+</sup>
getDescriptor(): string getDescriptor(): string
...@@ -8131,7 +8117,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8131,7 +8117,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8157,7 +8143,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8157,7 +8143,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
console.log("RpcServer: descriptor is: " + descriptor); console.log("RpcServer: descriptor is: " + descriptor);
``` ```
### getInterfaceDescriptor<sup>(deprecated)</sup> ### getInterfaceDescriptor<sup>(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). >This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9).
...@@ -8176,7 +8161,7 @@ Obtains the interface descriptor. ...@@ -8176,7 +8161,7 @@ Obtains the interface descriptor.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8201,7 +8186,6 @@ Obtains the interface descriptor. ...@@ -8201,7 +8186,6 @@ Obtains the interface descriptor.
console.log("RpcServer: descriptor is: " + descriptor); console.log("RpcServer: descriptor is: " + descriptor);
``` ```
### modifyLocalInterface<sup>9+</sup> ### modifyLocalInterface<sup>9+</sup>
modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void
...@@ -8217,10 +8201,9 @@ Binds an interface descriptor to an **IRemoteBroker** object. ...@@ -8217,10 +8201,9 @@ Binds an interface descriptor to an **IRemoteBroker** object.
| localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. |
| descriptor | string | Yes | Interface descriptor.| | descriptor | string | Yes | Interface descriptor.|
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8267,7 +8250,7 @@ Binds an interface descriptor to an **IRemoteBroker** object. ...@@ -8267,7 +8250,7 @@ Binds an interface descriptor to an **IRemoteBroker** object.
**Example** **Example**
``` ```ts
class MyDeathRecipient { class MyDeathRecipient {
onRemoteDied() { onRemoteDied() {
console.log("server died"); console.log("server died");
...@@ -8294,15 +8277,14 @@ Binds an interface descriptor to an **IRemoteBroker** object. ...@@ -8294,15 +8277,14 @@ Binds an interface descriptor to an **IRemoteBroker** object.
let testRemoteObject = new TestRemoteObject("testObject"); let testRemoteObject = new TestRemoteObject("testObject");
``` ```
## Ashmem<sup>8+</sup> ## Ashmem<sup>8+</sup>
Provides methods related to anonymous shared memory objects, including creating, closing, mapping, and unmapping an **Ashmem** object, reading data from and writing data to an **Ashmem** object, obtaining the **Ashmem** size, and setting **Ashmem** protection. Provides methods related to anonymous shared memory objects, including creating, closing, mapping, and unmapping an **Ashmem** object, reading data from and writing data to an **Ashmem** object, obtaining the **Ashmem** size, and setting **Ashmem** protection.
The table below describes the protection types of the mapped memory.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
The table below describes the protection types of the mapped memory.
| Name | Value | Description | | Name | Value | Description |
| ---------- | --- | ------------------ | | ---------- | --- | ------------------ |
| PROT_EXEC | 4 | The mapped memory is executable. | | PROT_EXEC | 4 | The mapped memory is executable. |
...@@ -8310,12 +8292,11 @@ The table below describes the protection types of the mapped memory. ...@@ -8310,12 +8292,11 @@ The table below describes the protection types of the mapped memory.
| PROT_READ | 1 | The mapped memory is readable. | | PROT_READ | 1 | The mapped memory is readable. |
| PROT_WRITE | 2 | The mapped memory is writeable. | | PROT_WRITE | 2 | The mapped memory is writeable. |
### create<sup>9+</sup> ### create<sup>9+</sup>
static create(name: string, size: number): Ashmem static create(name: string, size: number): Ashmem
Creates an **Ashmem** object with the specified name and size. Creates an **Ashmem** object with the specified name and size. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -8332,10 +8313,9 @@ Creates an **Ashmem** object with the specified name and size. ...@@ -8332,10 +8313,9 @@ Creates an **Ashmem** object with the specified name and size.
| ------ | ---------------------------------------------- | | ------ | ---------------------------------------------- |
| Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.|
**Example** **Example**
``` ```ts
let ashmem; let ashmem;
try { try {
ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
...@@ -8347,14 +8327,13 @@ Creates an **Ashmem** object with the specified name and size. ...@@ -8347,14 +8327,13 @@ Creates an **Ashmem** object with the specified name and size.
console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size); console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size);
``` ```
### createAshmem<sup>8+(deprecated)</sup> ### createAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [create](#create9). >This API is no longer maintained since API version 9. You are advised to use [create](#create9).
static createAshmem(name: string, size: number): Ashmem static createAshmem(name: string, size: number): Ashmem
Creates an **Ashmem** object with the specified name and size. Creates an **Ashmem** object with the specified name and size. This API is a static method.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -8373,18 +8352,17 @@ Creates an **Ashmem** object with the specified name and size. ...@@ -8373,18 +8352,17 @@ Creates an **Ashmem** object with the specified name and size.
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize(); let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size); console.log("RpcTest: get ashemm by createAshmem : " + ashmem + " size is : " + size);
``` ```
### create<sup>9+</sup> ### create<sup>9+</sup>
static create(ashmem: Ashmem): Ashmem static create(ashmem: Ashmem): Ashmem
Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. Creates an **Ashmem** object by copying the file descriptor of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -8403,7 +8381,7 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing ...@@ -8403,7 +8381,7 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing
**Example** **Example**
``` ```ts
let ashmem2; let ashmem2;
try { try {
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
...@@ -8416,14 +8394,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing ...@@ -8416,14 +8394,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing
console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size); console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size);
``` ```
### createAshmemFromExisting<sup>8+(deprecated)</sup> ### createAshmemFromExisting<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [create](#create9). >This API is no longer maintained since API version 9. You are advised to use [create](#create9).
static createAshmemFromExisting(ashmem: Ashmem): Ashmem static createAshmemFromExisting(ashmem: Ashmem): Ashmem
Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. Creates an **Ashmem** object by copying the file descriptor of an existing **Ashmem** object. The two **Ashmem** objects point to the same shared memory region.
**System capability**: SystemCapability.Communication.IPC.Core **System capability**: SystemCapability.Communication.IPC.Core
...@@ -8441,14 +8418,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing ...@@ -8441,14 +8418,13 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem); let ashmem2 = rpc.Ashmem.createAshmemFromExisting(ashmem);
let size = ashmem2.getAshmemSize(); let size = ashmem2.getAshmemSize();
console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size); console.log("RpcTest: get ashemm by createAshmemFromExisting : " + ashmem2 + " size is : " + size);
``` ```
### closeAshmem<sup>8+</sup> ### closeAshmem<sup>8+</sup>
closeAshmem(): void closeAshmem(): void
...@@ -8459,12 +8435,11 @@ Closes this **Ashmem** object. ...@@ -8459,12 +8435,11 @@ Closes this **Ashmem** object.
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.closeAshmem(); ashmem.closeAshmem();
``` ```
### unmapAshmem<sup>8+</sup> ### unmapAshmem<sup>8+</sup>
unmapAshmem(): void unmapAshmem(): void
...@@ -8475,12 +8450,11 @@ Deletes the mappings for the specified address range of this **Ashmem** object. ...@@ -8475,12 +8450,11 @@ Deletes the mappings for the specified address range of this **Ashmem** object.
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.unmapAshmem(); ashmem.unmapAshmem();
``` ```
### getAshmemSize<sup>8+</sup> ### getAshmemSize<sup>8+</sup>
getAshmemSize(): number getAshmemSize(): number
...@@ -8497,13 +8471,12 @@ Obtains the memory size of this **Ashmem** object. ...@@ -8497,13 +8471,12 @@ Obtains the memory size of this **Ashmem** object.
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let size = ashmem.getAshmemSize(); let size = ashmem.getAshmemSize();
console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size); console.log("RpcTest: get ashmem is " + ashmem + " size is : " + size);
``` ```
### mapTypedAshmem<sup>9+</sup> ### mapTypedAshmem<sup>9+</sup>
mapTypedAshmem(mapType: number): void mapTypedAshmem(mapType: number): void
...@@ -8528,7 +8501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8528,7 +8501,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try { try {
ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE);
...@@ -8538,7 +8511,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8538,7 +8511,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### mapAshmem<sup>8+(deprecated)</sup> ### mapAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [mapTypedAshmem](#maptypedashmem9). >This API is no longer maintained since API version 9. You are advised to use [mapTypedAshmem](#maptypedashmem9).
...@@ -8559,17 +8531,16 @@ Creates the shared file mapping on the virtual address space of this process. Th ...@@ -8559,17 +8531,16 @@ Creates the shared file mapping on the virtual address space of this process. Th
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapReadAndWrite = ashmem.mapAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); let mapReadAndWrite = ashmem.mapAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE);
console.log("RpcTest: map ashmem result is : " + mapReadAndWrite); console.log("RpcTest: map ashmem result is : " + mapReadAndWrite);
``` ```
### mapReadWriteAshmem<sup>9+</sup> ### mapReadWriteAshmem<sup>9+</sup>
mapReadWriteAshmem(): void mapReadWriteAshmem(): void
...@@ -8588,7 +8559,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8588,7 +8559,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try { try {
ashmem.mapReadWriteAshmem(); ashmem.mapReadWriteAshmem();
...@@ -8598,7 +8569,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8598,7 +8569,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### mapReadAndWriteAshmem<sup>8+(deprecated)</sup> ### mapReadAndWriteAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [mapReadWriteAshmem](#mapreadwriteashmem9). >This API is no longer maintained since API version 9. You are advised to use [mapReadWriteAshmem](#mapreadwriteashmem9).
...@@ -8613,17 +8583,16 @@ Maps the shared file to the readable and writable virtual address space of the p ...@@ -8613,17 +8583,16 @@ Maps the shared file to the readable and writable virtual address space of the p
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem(); let mapResult = ashmem.mapReadAndWriteAshmem();
console.log("RpcTest: map ashmem result is : " + mapResult); console.log("RpcTest: map ashmem result is : " + mapResult);
``` ```
### mapReadonlyAshmem<sup>9+</sup> ### mapReadonlyAshmem<sup>9+</sup>
mapReadonlyAshmem(): void mapReadonlyAshmem(): void
...@@ -8642,7 +8611,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8642,7 +8611,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try { try {
ashmem.mapReadonlyAshmem(); ashmem.mapReadonlyAshmem();
...@@ -8652,7 +8621,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8652,7 +8621,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### mapReadOnlyAshmem<sup>8+(deprecated)</sup> ### mapReadOnlyAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [mapReadonlyAshmem](#mapreadonlyashmem9). >This API is no longer maintained since API version 9. You are advised to use [mapReadonlyAshmem](#mapreadonlyashmem9).
...@@ -8667,17 +8635,16 @@ Maps the shared file to the read-only virtual address space of the process. ...@@ -8667,17 +8635,16 @@ Maps the shared file to the read-only virtual address space of the process.
| Type | Description | | Type | Description |
| ------- | ----------------------------------------- | | ------- | ----------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the mapping is created; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadOnlyAshmem(); let mapResult = ashmem.mapReadOnlyAshmem();
console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult); console.log("RpcTest: Ashmem mapReadOnlyAshmem result is : " + mapResult);
``` ```
### setProtectionType<sup>9+</sup> ### setProtectionType<sup>9+</sup>
setProtectionType(protectionType: number): void setProtectionType(protectionType: number): void
...@@ -8702,7 +8669,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8702,7 +8669,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
try { try {
ashmem.setProtection(ashmem.PROT_READ); ashmem.setProtection(ashmem.PROT_READ);
...@@ -8712,7 +8679,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8712,7 +8679,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### setProtection<sup>8+(deprecated)</sup> ### setProtection<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [setProtectionType](#setprotectiontype9). >This API is no longer maintained since API version 9. You are advised to use [setProtectionType](#setprotectiontype9).
...@@ -8737,13 +8703,12 @@ Sets the protection level of the memory region to which the shared file is mappe ...@@ -8737,13 +8703,12 @@ Sets the protection level of the memory region to which the shared file is mappe
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let result = ashmem.setProtection(ashmem.PROT_READ); let result = ashmem.setProtection(ashmem.PROT_READ);
console.log("RpcTest: Ashmem setProtection result is : " + result); console.log("RpcTest: Ashmem setProtection result is : " + result);
``` ```
### writeAshmem<sup>9+</sup> ### writeAshmem<sup>9+</sup>
writeAshmem(buf: number[], size: number, offset: number): void writeAshmem(buf: number[], size: number, offset: number): void
...@@ -8770,7 +8735,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8770,7 +8735,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.mapReadWriteAshmem(); ashmem.mapReadWriteAshmem();
var ByteArrayVar = [1, 2, 3, 4, 5]; var ByteArrayVar = [1, 2, 3, 4, 5];
...@@ -8782,7 +8747,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8782,7 +8747,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### writeToAshmem<sup>8+(deprecated)</sup> ### writeToAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [writeAshmem](#writeashmem9). >This API is no longer maintained since API version 9. You are advised to use [writeAshmem](#writeashmem9).
...@@ -8805,11 +8769,11 @@ Writes data to the shared file associated with this **Ashmem** object. ...@@ -8805,11 +8769,11 @@ Writes data to the shared file associated with this **Ashmem** object.
| Type | Description | | Type | Description |
| ------- | ----------------------------------------------------------------------------------------- | | ------- | ----------------------------------------------------------------------------------------- |
| boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| | boolean | Returns **true** if the data is written successfully; returns **false** otherwise.|
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem(); let mapResult = ashmem.mapReadAndWriteAshmem();
console.info("RpcTest map ashmem result is " + mapResult); console.info("RpcTest map ashmem result is " + mapResult);
...@@ -8818,7 +8782,6 @@ Writes data to the shared file associated with this **Ashmem** object. ...@@ -8818,7 +8782,6 @@ Writes data to the shared file associated with this **Ashmem** object.
console.log("RpcTest: write to Ashmem result is : " + writeResult); console.log("RpcTest: write to Ashmem result is : " + writeResult);
``` ```
### readAshmem<sup>9+</sup> ### readAshmem<sup>9+</sup>
readAshmem(size: number, offset: number): number[] readAshmem(size: number, offset: number): number[]
...@@ -8850,7 +8813,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8850,7 +8813,7 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); let ashmem = rpc.Ashmem.create("ashmem", 1024*1024);
ashmem.mapReadWriteAshmem(); ashmem.mapReadWriteAshmem();
var ByteArrayVar = [1, 2, 3, 4, 5]; var ByteArrayVar = [1, 2, 3, 4, 5];
...@@ -8864,7 +8827,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode ...@@ -8864,7 +8827,6 @@ For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode
} }
``` ```
### readFromAshmem<sup>8+(deprecated)</sup> ### readFromAshmem<sup>8+(deprecated)</sup>
>This API is no longer maintained since API version 9. You are advised to use [readAshmem](#readashmem9). >This API is no longer maintained since API version 9. You are advised to use [readAshmem](#readashmem9).
...@@ -8890,7 +8852,7 @@ Reads data from the shared file associated with this **Ashmem** object. ...@@ -8890,7 +8852,7 @@ Reads data from the shared file associated with this **Ashmem** object.
**Example** **Example**
``` ```ts
let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024);
let mapResult = ashmem.mapReadAndWriteAshmem(); let mapResult = ashmem.mapReadAndWriteAshmem();
console.info("RpcTest map ashmem result is " + mapResult); console.info("RpcTest map ashmem result is " + mapResult);
...@@ -8899,4 +8861,5 @@ Reads data from the shared file associated with this **Ashmem** object. ...@@ -8899,4 +8861,5 @@ Reads data from the shared file associated with this **Ashmem** object.
console.log("RpcTest: write to Ashmem result is : " + writeResult); console.log("RpcTest: write to Ashmem result is : " + writeResult);
let readResult = ashmem.readFromAshmem(5, 0); let readResult = ashmem.readFromAshmem(5, 0);
console.log("RpcTest: read to Ashmem result is : " + readResult); console.log("RpcTest: read to Ashmem result is : " + readResult);
``` ```
# tagSession # tagSession (Standard NFC Tag Session)
The **tagSession** module provides common APIs for establishing connections and transferring data. The **tagSession** module provides common APIs for establishing connections and transferring data.
...@@ -26,9 +26,12 @@ getTagInfo(): tag.TagInfo ...@@ -26,9 +26,12 @@ getTagInfo(): tag.TagInfo
Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tag.getTagInfo](js-apis-nfcTag.md#taggettaginfo9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -54,9 +57,12 @@ connectTag(): boolean; ...@@ -54,9 +57,12 @@ connectTag(): boolean;
Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.connect](#tagsessionconnect9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -76,15 +82,52 @@ let connectStatus = tag.getIsoDep(tagInfo).connectTag(); ...@@ -76,15 +82,52 @@ let connectStatus = tag.getIsoDep(tagInfo).connectTag();
console.log("connectStatus: " + connectStatus); console.log("connectStatus: " + connectStatus);
``` ```
### tagSession.connect<sup>9+</sup>
connect(): void;
Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
try {
tag.getIsoDep(tagInfo).connect();
console.log("tag connect success");
} catch (busiError) {
console.log("tag connect busiError: " + busiError);
}
```
### tagSession.reset() ### tagSession.reset()
reset(): void reset(): void
Resets the connection to this tag. Resets the connection to this tag.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.resetConnection](#tagsessionresetconnection9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Example** **Example**
...@@ -97,15 +140,52 @@ import tag from '@ohos.nfc.tag'; ...@@ -97,15 +140,52 @@ import tag from '@ohos.nfc.tag';
tag.getIsoDep(tagInfo).reset(); tag.getIsoDep(tagInfo).reset();
``` ```
### tagSession.resetConnection()<sup>9+</sup>
resetConnection(): void
Resets the connection to this tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
try {
tag.getIsoDep(tagInfo).resetConnection();
console.log("tag resetConnection success");
} catch (busiError) {
console.log("tag resetConnection busiError: " + busiError);
}
```
### tagSession.isTagConnected ### tagSession.isTagConnected
isTagConnected(): boolean isTagConnected(): boolean
Checks whether the tag is connected. Checks whether the tag is connected.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.isConnected](#tagsessionisconnected9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -125,15 +205,50 @@ let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); ...@@ -125,15 +205,50 @@ let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected();
console.log("isTagConnected: " + isTagConnected); console.log("isTagConnected: " + isTagConnected);
``` ```
### tagSession.isConnected<sup>9+</sup>
isConnected(): boolean
Checks whether the tag is connected.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| boolean | Returns **true** if the tag is connected; returns **false** otherwise.|
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
try {
var isConnected = tag.getIsoDep(tagInfo).isConnected();
console.log("tag isConnected = " + isConnected);
} catch (busiError) {
console.log("tag isConnected busiError: " + busiError);
}
```
### tagSession.getMaxSendLength ### tagSession.getMaxSendLength
getMaxSendLength(): number getMaxSendLength(): number
Obtains the maximum length of the data that can be sent to this tag. Obtains the maximum length of the data that can be sent to this tag.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.getMaxTransmitSize](#tagsessiongetmaxtransmitsize9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -152,15 +267,57 @@ let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); ...@@ -152,15 +267,57 @@ let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength();
console.log("tag maxSendLen: " + maxSendLen); console.log("tag maxSendLen: " + maxSendLen);
``` ```
### tagSession.getMaxTransmitSize<sup>9+</sup>
getMaxTransmitSize(): number
Obtains the maximum length of the data that can be sent to this tag.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| number | Maximum data length obtained. The value cannot be a negative number.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
try {
var maxTransmitSize = tag.getIsoDep(tagInfo).getMaxTransmitSize();
console.log("tag maxTransmitSize = " + maxTransmitSize);
} catch (busiError) {
console.log("tag getMaxTransmitSize busiError: " + busiError);
}
```
### tagSession.getSendDataTimeout ### tagSession.getSendDataTimeout
getSendDataTimeout(): number getSendDataTimeout(): number
Obtains the timeout period for sending data to this tag, in milliseconds. Obtains the timeout period for sending data to this tag, in milliseconds.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.getTimeout](#tagsessiongettimeout9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Return value** **Return value**
...@@ -180,15 +337,58 @@ let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); ...@@ -180,15 +337,58 @@ let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout();
console.log("tag sendDataTimeout: " + sendDataTimeout); console.log("tag sendDataTimeout: " + sendDataTimeout);
``` ```
### tagSession.getTimeout<sup>9+</sup>
getTimeout(): number
Obtains the timeout period for sending data to this tag, in milliseconds.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
try {
var timeout = tag.getIsoDep(tagInfo).getTimeout();
console.log("tag timeout = " + timeout);
} catch (busiError) {
console.log("tag getTimeout busiError: " + busiError);
}
```
### tagSession.setSendDataTimeout ### tagSession.setSendDataTimeout
setSendDataTimeout(timeout: number): boolean setSendDataTimeout(timeout: number): boolean
Sets the timeout period for sending data to this tag, in milliseconds. Sets the timeout period for sending data to this tag, in milliseconds.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.setTimeout](#tagsessionsettimeout9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -215,15 +415,59 @@ let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); ...@@ -215,15 +415,59 @@ let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs);
console.log("tag setSendDataTimeout setStatus: " + setStatus); console.log("tag setSendDataTimeout setStatus: " + setStatus);
``` ```
### tagSession.setTimeout<sup>9+</sup>
setTimeout(timeout: number): void
Sets the timeout period for sending data to this tag, in milliseconds.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
let timeoutMs = 700; // Change it as required.
try {
tag.getIsoDep(tagInfo).setTimeout(timeoutMs);
console.log("tag setTimeout success");
} catch (busiError) {
console.log("tag setTimeout busiError: " + busiError);
}
```
### tagSession.sendData ### tagSession.sendData
sendData(data: number[]): Promise<number[]> sendData(data: number[]): Promise<number[]>
Sends data to this tag. This API uses a promise to return the result. Sends data to this tag. This API uses a promise to return the result.
> **NOTE**
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tagSession.transmit](#tagsessiontransmit9).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -267,9 +511,12 @@ sendData(data: number[], callback: AsyncCallback<number[]>): void ...@@ -267,9 +511,12 @@ sendData(data: number[], callback: AsyncCallback<number[]>): void
Sends data to this tag. This API uses an asynchronous callback to return the result. Sends data to this tag. This API uses an asynchronous callback to return the result.
> **NOTE**
> This parameter is supported since API version 7 and discarded since API version 9. You are advised to use [tagSession.transmit](#tagsessiontransmit9-1).
**Required permissions**: ohos.permission.NFC_TAG **Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Core **System capability**: SystemCapability.Communication.NFC.Tag
**Parameters** **Parameters**
...@@ -303,3 +550,123 @@ tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { ...@@ -303,3 +550,123 @@ tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> {
} }
}); });
``` ```
### tagSession.transmit<sup>9+</sup>
transmit(data: number[]): Promise<number[]>
Transmits data to this tag. This API uses a promise to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| data | number[] | Yes| Data to transmit. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**. |
**Return value**
| **Type**| **Description** |
| ------------------ | --------------------------|
| Promise<number[]> | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
// Connect to the tag if it is not connected.
try {
if (!tag.getIsoDep(tagInfo).isConnected()) {
tag.getIsoDep(tagInfo).connect();
}
} catch (busiError) {
console.log("tag connect busiError: " + busiError);
return;
}
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required.
try {
tag.getIsoDep(tagInfo).transmit(cmdData).then((response) => {
console.log("tagSession transmit Promise response: " + response);
}).catch((err)=> {
console.log("tagSession transmit Promise err: " + err);
});
} catch (busiError) {
console.log("tag transmit busiError: " + busiError);
return;
}
```
### tagSession.transmit<sup>9+</sup>
transmit(data: number[], callback: AsyncCallback<number[]>): void
Transmits data to this tag. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.NFC_TAG
**System capability**: SystemCapability.Communication.NFC.Tag
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------- |
| data | number[] | Yes| Data to transmit. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**. |
| callback | AsyncCallback<number[]> | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.|
**Error codes**
For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md).
| ID| Error Message|
| ------- | -------|
| 3100201 | Tag running state is abnormal in service. |
**Example**
```js
import tag from '@ohos.nfc.tag';
// tagInfo is an object provided by the NFC service when a tag is dispatched.
// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags.
// Connect to the tag if it is not connected.
try {
if (!tag.getIsoDep(tagInfo).isConnected()) {
tag.getIsoDep(tagInfo).connect();
}
} catch (busiError) {
console.log("tag connect busiError: " + busiError);
return;
}
let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required.
try {
tag.getIsoDep(tagInfo).transmit(cmdData, (err, response)=> {
if (err) {
console.log("tagSession transmit AsyncCallback err: " + err);
} else {
console.log("tagSession transmit AsyncCallback response: " + response);
}
});
} catch (busiError) {
console.log("tag transmit busiError: " + busiError);
return;
}
```
...@@ -38,6 +38,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and ...@@ -38,6 +38,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and
**Example** **Example**
```ts ```ts
// The userFileManager instance obtained is a global object. It is used by default in subsequent operations. If the code snippet is not added, an error will be reported indicating that mgr is not defined.
const context = getContext(this); const context = getContext(this);
let mgr = userFileManager.getUserFileMgr(context); let mgr = userFileManager.getUserFileMgr(context);
``` ```
...@@ -127,7 +128,7 @@ async function example() { ...@@ -127,7 +128,7 @@ async function example() {
predicates: predicates predicates: predicates
}; };
try { try {
var fetchResult = await mgr.getPhotoAssets(fetchOptions); let fetchResult = await mgr.getPhotoAssets(fetchOptions);
if (fetchResult != undefined) { if (fetchResult != undefined) {
console.info('fetchResult success'); console.info('fetchResult success');
let fileAsset = await fetchResult.getFirstObject(); let fileAsset = await fetchResult.getFirstObject();
...@@ -410,7 +411,7 @@ Obtains the system album. This API uses a promise to return the result. ...@@ -410,7 +411,7 @@ Obtains the system album. This API uses a promise to return the result.
async function example() { async function example() {
console.info('getPrivateAlbumDemo'); console.info('getPrivateAlbumDemo');
try { try {
var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); let fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH);
let trashAlbum = await fetchResult.getFirstObject(); let trashAlbum = await fetchResult.getFirstObject();
console.info('first album.albumName = ' + trashAlbum.albumName); console.info('first album.albumName = ' + trashAlbum.albumName);
} catch (err) { } catch (err) {
......
...@@ -179,7 +179,7 @@ try { ...@@ -179,7 +179,7 @@ try {
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
// Do something; // Do something;
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
// Do something; // Do something.
default: default:
// Do others. // Do others.
} }
......
...@@ -263,7 +263,7 @@ Represents the WLAN configuration. ...@@ -263,7 +263,7 @@ Represents the WLAN configuration.
## IpType<sup>7+</sup> ## IpType<sup>7+</sup>
Enumerate the IP address types. Enumerates the IP address types.
**System API**: This is a system API. **System API**: This is a system API.
......
# WLAN # WLAN
The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN.
> **NOTE** > **NOTE**
...@@ -1038,7 +1037,7 @@ Removes the specified network configuration. ...@@ -1038,7 +1037,7 @@ Removes the specified network configuration.
| **Name**| **Type**| **Mandatory**| **Description**| | **Name**| **Type**| **Mandatory**| **Description**|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| id | number | Yes| ID of the network configuration to remove.| | id | number | Yes| ID of the network configuration to remove.|
**Return value** **Return value**
...@@ -1788,7 +1787,7 @@ Unregisters the WLAN state change events. ...@@ -1788,7 +1787,7 @@ Unregisters the WLAN state change events.
``` ```
## wifi.on('wifiConnectionChange')<sup>7+</sup> ## wifi.on('wifiConnectionChange')<sup>9+</sup>
on(type: "wifiConnectionChange", callback: Callback&lt;number&gt;): void on(type: "wifiConnectionChange", callback: Callback&lt;number&gt;): void
......
# WLAN Extension Interface # WLAN Extension Interface
This **wifiext** module provides WLAN extension interfaces for non-universal products. This **wifiext** module provides WLAN extension interfaces for non-universal products.
> **NOTE** > **NOTE**
...@@ -26,9 +25,9 @@ Enables the WLAN hotspot. ...@@ -26,9 +25,9 @@ Enables the WLAN hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.disableHotspot ## wifiext.disableHotspot
...@@ -43,9 +42,9 @@ Disables the WLAN hotspot. ...@@ -43,9 +42,9 @@ Disables the WLAN hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.getSupportedPowerModel ## wifiext.getSupportedPowerModel
...@@ -60,9 +59,9 @@ Obtains the supported power models. This API uses a promise to return the result ...@@ -60,9 +59,9 @@ Obtains the supported power models. This API uses a promise to return the result
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.| | Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
## PowerModel ## PowerModel
...@@ -90,9 +89,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re ...@@ -90,9 +89,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.|
## wifiext.getPowerModel ## wifiext.getPowerModel
...@@ -107,9 +106,9 @@ Obtains the power model. This API uses a promise to return the result. ...@@ -107,9 +106,9 @@ Obtains the power model. This API uses a promise to return the result.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.| | Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
## wifiext.getPowerModel ## wifiext.getPowerModel
...@@ -124,16 +123,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re ...@@ -124,16 +123,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.|
## wifiext.setPowerModel ## wifiext.setPowerModel
setPowerModel(model: PowerModel) : boolean; setPowerModel(model: PowerModel) : boolean;
Sets the power model. Sets the power model.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
...@@ -141,12 +140,12 @@ setPowerModel(model: PowerModel) : boolean; ...@@ -141,12 +140,12 @@ setPowerModel(model: PowerModel) : boolean;
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.| | model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
# @ohos.wifiext # @ohos.wifiext (WLAN Extension)
This **wifiext** module provides WLAN extension interfaces for non-universal products. This **wifiext** module provides WLAN extension interfaces for non-universal products.
...@@ -26,9 +26,9 @@ Enables the WLAN hotspot. ...@@ -26,9 +26,9 @@ Enables the WLAN hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.disableHotspot ## wifiext.disableHotspot
...@@ -43,9 +43,9 @@ Disables the WLAN hotspot. ...@@ -43,9 +43,9 @@ Disables the WLAN hotspot.
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
## wifiext.getSupportedPowerModel ## wifiext.getSupportedPowerModel
...@@ -60,9 +60,9 @@ Obtains the supported power models. This API uses a promise to return the result ...@@ -60,9 +60,9 @@ Obtains the supported power models. This API uses a promise to return the result
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.| | Promise&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Promise used to return the power models obtained.|
## PowerModel ## PowerModel
...@@ -90,9 +90,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re ...@@ -90,9 +90,9 @@ Obtains the supported power models. This API uses an asynchronous callback to re
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;Array&lt;[PowerModel](#powermodel)&gt;&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.|
## wifiext.getPowerModel ## wifiext.getPowerModel
...@@ -107,9 +107,9 @@ Obtains the power model. This API uses a promise to return the result. ...@@ -107,9 +107,9 @@ Obtains the power model. This API uses a promise to return the result.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.| | Promise&lt;[PowerModel](#powermodel)&gt; | Promise used to return the power model obtained.|
## wifiext.getPowerModel ## wifiext.getPowerModel
...@@ -124,16 +124,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re ...@@ -124,16 +124,16 @@ Obtains the power model. This API uses an asynchronous callback to return the re
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| | callback | AsyncCallback&lt;[PowerModel](#powermodel)&gt; | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.|
## wifiext.setPowerModel ## wifiext.setPowerModel
setPowerModel(model: PowerModel) : boolean; setPowerModel(model: PowerModel) : boolean;
Sets the power model. Sets the power model.
**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT **Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT
...@@ -141,12 +141,12 @@ setPowerModel(model: PowerModel) : boolean; ...@@ -141,12 +141,12 @@ setPowerModel(model: PowerModel) : boolean;
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| model | [PowerModel](#powermodel) | Yes| Power model to set.| | model | [PowerModel](#powermodel) | Yes| Power model to set.|
**Return value** **Return value**
| **Type**| **Description**| | **Type**| **Description**|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
**Error Message** **Error Message**
NFC opening or closing state is abnormal in service. NFC state is abnormal in service.
**Description** **Description**
...@@ -12,11 +12,13 @@ The NFC service fails to enable or disable NFC. ...@@ -12,11 +12,13 @@ The NFC service fails to enable or disable NFC.
**Possible Causes** **Possible Causes**
Communication with the NFC service failed. 1. Communication with the NFC service failed.
2. The NFC chip communication is abnormal.
**Solution** **Solution**
Enable or disable NFC again. 1. Enable or disable NFC again.
2. Enable or disable NFC again or restart the device, and try again.
## 3100201 ## 3100201
......
...@@ -9,10 +9,14 @@ The HUKS provides the capability of randomly generating keys for services. For a ...@@ -9,10 +9,14 @@ The HUKS provides the capability of randomly generating keys for services. For a
Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, a key attribute set in **options**, and **callback** to result the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md). Use [huks.generateKeyItem(keyAlias,options,callback)](../reference/apis/js-apis-huks.md#huksgeneratekeyitem9) to generate a key. You need to pass in the key alias in **keyAlias**, a key attribute set in **options**, and **callback** to result the result asynchronously. For details about the APIs, see [HUKS](../reference/apis/js-apis-huks.md).
1. Determine the key alias. 1. Determine the key alias.
2. Initialize the key attributes.<br>Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key attributes. Use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory. 2. Initialize the key attributes.<br>Use [HuksParam](../reference/apis/js-apis-huks.md#huksparam) to encapsulate key attributes. Use a **HuksParam** array to assign values to the **properties** field of [HuksOptions](../reference/apis/js-apis-huks.md#huksoptions). The parameters [HuksKeyAlg](../reference/apis/js-apis-huks.md#hukskeyalg), [HuksKeySize](../reference/apis/js-apis-huks.md#hukskeysize), and [HuksKeyPurpose](../reference/apis/js-apis-huks.md#hukskeypurpose) are mandatory.
3. Pass in the key alias and key parameter set to generate a key. 3. Pass in the key alias and key parameter set to generate a key.
> **NOTE** > **NOTE**
> >
> The key alias cannot exceed 64 bytes. > The key alias cannot exceed 64 bytes.
...@@ -209,7 +213,7 @@ Compared with import of plaintext, secure import has complex key material and op ...@@ -209,7 +213,7 @@ Compared with import of plaintext, secure import has complex key material and op
**Figure 1** Development process of secure import **Figure 2** Development process of secure import
![huks_import_wrapped_key](figures/huks_import_wrapped_key.png) ![huks_import_wrapped_key](figures/huks_import_wrapped_key.png)
...@@ -225,9 +229,9 @@ You need to use the APIs for generating a key, exporting a public key, importing ...@@ -225,9 +229,9 @@ You need to use the APIs for generating a key, exporting a public key, importing
| API | Description | | API | Description |
| -------------------------------------- | ----------------------------| | -------------------------------------- | ----------------------------|
|generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void| Generates a key.| |generateKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void| Generates a key.|
|exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<HuksReturnResult>) : void| Exports the public key of a key pair.| |exportKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksReturnResult>) : void| Exports the public key of a key pair.|
|importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void|Imports a wrapped key.| |importWrappedKeyItem(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void|Imports a wrapped key.|
|deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback<void>) : void|Deletes a key.| |deleteKeyItem(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<void>) : void|Deletes a key.|
>**NOTE**<br>The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **Length<sub>Data</sub>-Data** format. Specifically, the application needs to apply for a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table. >**NOTE**<br>The public key plaintext material returned by **exportKeyItem()** is encapsulated in X.509 format, and the key material to be imported by **importWrappedKeyItem()** must be encapsulated in **Length<sub>Data</sub>-Data** format. Specifically, the application needs to apply for a Uint8Array and encapsulate the Uint8Array in the sequence listed in the following table.
...@@ -2081,55 +2085,57 @@ If secondary user identity authentication is enabled for a key, initialize the k ...@@ -2081,55 +2085,57 @@ If secondary user identity authentication is enabled for a key, initialize the k
| Name | Value | Description | | Name | Value | Description |
| ------------------------------- |---|------------------------ | | ------------------------------- |---|------------------------ |
| HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication. | | HUKS_USER_AUTH_TYPE_FINGERPRINT |0x0001 | Fingerprint authentication. |
| HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication. | | HUKS_USER_AUTH_TYPE_FACE |0x0002 | Facial authentication.|
| HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. | | HUKS_USER_AUTH_TYPE_PIN |0x0004 | PIN authentication. |
> **NOTE** > **NOTE**
> >
> You can specify any or a combination of the three authentication types. > You can specify any or a combination of the three authentication types.
**Table 4** Secure access types **Table 4** Secure access types
| Name | Value | Description | | Name | Value | Description |
| --------------------------------------- | ----- | ------------------------------------------------------------ | | --------------------------------------- | ---- | ------------------------------------------------ |
| HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. | | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD | 1 | Invalidates the key after the screen lock password is cleared. |
| HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication. | | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL | 2 | Invalidates the key after a biometric enrollment is added. The user authentication types must include the biometric authentication.|
| | | |
> **NOTE** > **NOTE**
> >
> **HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD** and **HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL** are mutually exclusive. > **HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD** and **HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL** are mutually exclusive.
**Table 5** Challenge types **Table 5** Challenge types
| Name | Value | Description | | Name | Value | Description |
| ------------------------------- | ---- | ------------------------------ | | ------------------------------- | ---- | ------------------------------ |
| HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.| | HUKS_CHALLENGE_TYPE_NORMAL | 0 | Normal challenge, which requires an independent user authentication for each use of the key.|
| HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.| | HUKS_CHALLENGE_TYPE_CUSTOM | 1 | Custom challenge, which supports only one user authentication for multiple keys.|
| HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.| | HUKS_CHALLENGE_TYPE_NONE | 2 | No challenge is required during user authentication.|
> **NOTICE** > **NOTICE**
> >
> The three challenge types are mutually exclusive. > The three challenge types are mutually exclusive.
> >
> If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed only within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds. > If the challenge type is **HUKS_CHALLENGE_TYPE_NONE**, no challenge is required. However, the key can be accessed only within a specified time period (set by **HUKS_TAG_AUTH_TIMEOUT**) after a successful authentication. The maximum value of **HUKS_TAG_AUTH_TIMEOUT** is 60 seconds.
2. To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported.
**Table 6** APIs for using a key
| API | Description |
| -------------------------------------- | ----------------------------|
|initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void| Initializes the key session and obtains the challenge value.|
|updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void| Operates data by segment and passes the authentication token.|
|finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void| Finalizes the key session.|
2. To use a key, initialize the key session, and determine whether a challenge is required based on the challenge type specified when the key is generated or imported.
**Table 6** APIs for using a key
| API | Description |
|-------------- | ------------------------------------ |
| initSession(keyAlias: string, options: HuksOptions, callback: AsyncCallback\<HuksSessionHandle>) : void |Initializes the key session and obtains the challenge value.|
| updateSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void| Operates data by segment and passes the authentication token.|
| finishSession(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\<HuksReturnResult>) : void | Finalizes the key session.|
**How to Develop** **How to Develop**
1. Generate a key and specify user authentication attributes. 1. Generate a key and specify user authentication attributes.
```ts ```ts
import huks from '@ohos.security.huks'; import huks from '@ohos.security.huks';
......
...@@ -76,7 +76,7 @@ Allows an application to read telephony information. ...@@ -76,7 +76,7 @@ Allows an application to read telephony information.
## ohos.permission.REQUIRE_FORM ## ohos.permission.REQUIRE_FORM
Allows an application to obtain widgets. Allows an application to obtain the Ability Form.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -166,7 +166,7 @@ Allows an application to set the system time zone. ...@@ -166,7 +166,7 @@ Allows an application to set the system time zone.
## ohos.permission.DOWNLOAD_SESSION_MANAGER ## ohos.permission.DOWNLOAD_SESSION_MANAGER
Allows an application to manage download sessions. Allows an application to manage the download sessions.
**Permission level**: system_core **Permission level**: system_core
...@@ -436,7 +436,7 @@ Allows an application to obtain the sensitive permissions that have been granted ...@@ -436,7 +436,7 @@ Allows an application to obtain the sensitive permissions that have been granted
## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION ## ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS_EXTENSION
Allows an application to set the attributes of applications of other users. Allows an application to set attributes for the applications of other users.
**Permission level**: system_core **Permission level**: system_core
...@@ -546,7 +546,7 @@ Allows an application to start Feature abilities in the background. ...@@ -546,7 +546,7 @@ Allows an application to start Feature abilities in the background.
## ohos.permission.BUNDLE_ACTIVE_INFO ## ohos.permission.BUNDLE_ACTIVE_INFO
Allows an application to obtain how long other applications have been running in the foreground or background. Allows an application to obtain how long other applications have been running in the foreground or background.
**Permission level**: system_basic **Permission level**: system_basic
...@@ -606,7 +606,7 @@ Allows an application to use agent-powered reminders. ...@@ -606,7 +606,7 @@ Allows an application to use agent-powered reminders.
## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR ## ohos.permission.CONTROL_TASK_SYNC_ANIMATOR
Allows applications to use sync task animations. Allows an application to use sync task animations.
**Permission level**: system_core **Permission level**: system_core
...@@ -616,7 +616,7 @@ Allows applications to use sync task animations. ...@@ -616,7 +616,7 @@ Allows applications to use sync task animations.
## ohos.permission.INPUT_MONITORING ## ohos.permission.INPUT_MONITORING
Allows an application to listen for input events. Only the system signed applications can apply for this permission. Allows an application to listen for input events. Only the system signed applications can apply for this permission.
**Permission level**: system_core **Permission level**: system_core
...@@ -924,6 +924,16 @@ Allows the device administrator application to obtain device information. ...@@ -924,6 +924,16 @@ Allows the device administrator application to obtain device information.
**Enable ACL**: TRUE **Enable ACL**: TRUE
## ohos.permission.ENTERPRISE_RESET_DEVICE
Allows the device administrator to restore factory settings of the device.
**Permission level**: system_basic
**Authorization mode**: system_grant
**Enable ACL**: TRUE
## ohos.permission.NFC_TAG ## ohos.permission.NFC_TAG
Allows an application to read NFC tag information. Allows an application to read NFC tag information.
...@@ -1156,7 +1166,7 @@ Allows an application to obtain the approximate location information of a device ...@@ -1156,7 +1166,7 @@ Allows an application to obtain the approximate location information of a device
## ohos.permission.MEDIA_LOCATION ## ohos.permission.MEDIA_LOCATION
Allow an application to access geographical locations in the user's media file. Allows an application to access geographical locations in the user's media file.
**Permission level**: normal **Permission level**: normal
...@@ -1603,3 +1613,13 @@ Allows an application to publish system common events. ...@@ -1603,3 +1613,13 @@ Allows an application to publish system common events.
**Authorization mode**: system_grant **Authorization mode**: system_grant
**Enable ACL**: TRUE **Enable ACL**: TRUE
## ohos.permission.ACCESS_SCREEN_LOCK_INNER
Allows an application to call the system API of the lock screen service.
**Permission level**: system_core
**Authorization mode**: system_grant
**Enable ACL**: FALSE
# User Authentication Overview # User Authentication Overview
OpenHarmony provides biometric recognition that can be used for identity authentication in device unlocking, application login, and payment. ## UserAuth Module
OpenHarmony provides both 2D and 3D facial recognition. You can provide either or both of them on your device based on the hardware and technology applied on the device. 3D facial recognition is superior to 2D facial recognition in terms of recognition rate and anti-counterfeiting capability. However, you can use 3D facial recognition only if your device supports capabilities such as 3D structured light and 3D Time of Flight \(TOF\). The **UserAuth** module provides user authentication capabilities. You can use the APIs provided by this module to authenticate users in scenarios, such as device unlocking, payment, and application logins.
Currently, user authentication comes with facial recognition and fingerprint recognition capabilities. The specific capabilities supported by a device vary depending on the hardware and technology implementation.
## Basic Concepts ## Basic Concepts
Biometric recognition \(also known as biometric authentication\) uses optical, acoustical, and biological sensors, as well as the biological statistics mechanism to identify individuals. - Facial recognition is a biometric recognition technology that identifies individuals based on their facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize the human faces.
Facial recognition is a biometric recognition technology that identifies individuals based on facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize the human faces. - Fingerprint recognition is a biometric recognition technology that identifies individuals based on fingerprint ridge patterns. When the user places their finger against the fingerprint sensor, the sensor captures the fingerprint image of the user, and transmits it to the fingerprint recognition module for processing, which then compares the fingerprint image with the fingerprint information pre-registered by the user to identify the user identity.
## Working Principles ## Working Principles
Facial recognition establishes a secure channel between a camera and a trusted execution environment \(TEE\). Through this channel, face image data is transmitted to the TEE. This protects against any attack from the rich execution environment \(REE\) as the face image data cannot be obtained from the REE. The face image collection, characteristic extraction, alive human body detection, and characteristic comparison are all completed in the TEE. The TEE implements security isolation based on the trust zone. The external face framework only initiates face authentication and processes authentication results. It does not process the human face data. During facial or fingerprint recognition, the feature collecting device transmits the collected biometrics information to the Trusted Execution Environment (TEE) directly through a secure channel. This security mechanism prevents malware from attacking the Rich Execution Environment (REE). Processing of the biometrics information, from alive human body detection to characteristic extraction, storage, and comparison, is all done in the TEE, where security isolation is implemented based on the trust zone. The service framework that provides APIs only deals with authentication requests and authentication results. It does not process the biometrics information.
Facial characteristics are stored in the TEE, which uses strong cryptographic algorithms to encrypt and protect the integrity of facial characteristics. The collected and stored facial characteristics will not be transferred out of the TEE without user authorization. This ensures that system or third-party applications cannot obtain facial characteristics, or send or back them up to any external storage medium. Biometrics information is stored in trust zones in a TEE, which uses strong cryptographic algorithms to encrypt and protect the integrity of the information. The collected and stored biometrics information will not be transferred out of the TEE without user authorization. That is, no application can obtain the biometrics information or send it to any external storage medium without user authorization.
## Constraints ## Constraints
- OpenHarmony only supports facial recognition and local authentication, and does not support an authentication UI. - Only facial and fingerprint recognition is currently available and can only be executed on a local device. Moreover, no authentication UI is provided.
- To use biometric recognition, a device must have a camera with a face image pixel greater than 100x100. - To implement user authentication, a device must have a component for collecting the biometrics information, and the face image must be greater than 100 x 100 pixels.
- The device must have a TEE, where encrypted facial characteristics are stored. - The device must have a TEE, where encrypted biometrics information is stored.
- Facial recognition may not work for people with similar looks and children whose facial features keep changing. If you are concerned about this, consider using other authentication modes. - Facial recognition may not work for people with similar looks and children whose facial characteristics keep changing. If you are concerned about this, consider using other authentication modes.
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
Facial authentication provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app logins. It uses biometric recognition technologies to identify individuals based on facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize human faces. Facial authentication is also called facial recognition. The figure below shows the architecture of facial authentication. Facial authentication provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app logins. It uses biometric recognition technologies to identify individuals based on facial characteristics. A camera is used to collect images or video streams that contain human faces, and automatically detect, track, and recognize human faces. Facial authentication is also called facial recognition. The figure below shows the architecture of facial authentication.
The face authentication (Face_auth) driver is developed based on the Hardware Driver Foundation (HDF). It shields hardware differences and provides stable facial authentication capabilities for the user authentication framework (User_auth) and Face_auth service. The facial authentication capabilities include obtaining facial recognition executor list, executor information, and template information by template ID, comparing face image template information of the executor and that of User_auth, enrolling or deleting face image templates, and performing facial authentication. The face authentication (Face_auth) driver is developed based on the Hardware Driver Foundation (HDF). It shields hardware differences and provides stable facial authentication capabilities for the user authentication framework (User_auth) and Face_auth service. The facial authentication capabilities include obtaining facial recognition executor list, executor information, and template information by template ID, comparing face image template information of the executor and that of User_auth, enrolling or deleting face images, and performing facial authentication.
**Figure 1** Facial authentication architecture **Figure 1** Facial authentication architecture
...@@ -21,7 +21,7 @@ The identity authentication consists of User_auth and basic authentication servi ...@@ -21,7 +21,7 @@ The identity authentication consists of User_auth and basic authentication servi
- Executor security level - Executor security level
Security level required for the execution environment of an executor. Security level of the runtime environment when an executor provides capabilities.
- Executor role - Executor role
...@@ -39,9 +39,9 @@ The identity authentication consists of User_auth and basic authentication servi ...@@ -39,9 +39,9 @@ The identity authentication consists of User_auth and basic authentication servi
To ensure user data security and authentication result accuracy, measures must be taken to protect the integrity of the key information exchanged between User_auth and basic authentication services. Public keys must be exchanged when the executor provided by a basic authentication service interworks with User_auth. To ensure user data security and authentication result accuracy, measures must be taken to protect the integrity of the key information exchanged between User_auth and basic authentication services. Public keys must be exchanged when the executor provided by a basic authentication service interworks with User_auth.
The executor uses the User_auth public key to verify scheduling instructions. The executor uses the User_auth public key to verify scheduling instructions.
User_auth uses the executor public key to verify the authentication result accuracy and the integrity of the information exchanged with the executor. User_auth uses the executor public key to verify the authentication result accuracy and the integrity of the information exchanged with the executor.
- Authentication credential template - Authentication credential template
...@@ -51,6 +51,22 @@ The identity authentication consists of User_auth and basic authentication servi ...@@ -51,6 +51,22 @@ The identity authentication consists of User_auth and basic authentication servi
User_auth manages the mappings between user identities and credential IDs in a unified manner. When connecting to User_auth, the executor obtains the template ID list from User_auth and updates its template ID list based on the template ID list obtained. User_auth manages the mappings between user identities and credential IDs in a unified manner. When connecting to User_auth, the executor obtains the template ID list from User_auth and updates its template ID list based on the template ID list obtained.
- HAPs
In a broad sense, OpenHarmony Ability Packages (HAPs) are application packages that can be installed on OpenHarmony. In this document, the HAPs only refer to the upper-layer applications of the Face_auth driver.
- IDL interface
An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. This document describes how to use the client and server generated by the IDL interface to implement communication between the Face_auth service and driver. For details, see [IDL](https://gitee.com/openharmony/ability_idl_tool/blob/master/README.md).
- IPC
Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other. For details, see [IPC](https://gitee.com/openharmony/communication_ipc/blob/master/README.md).
- HDI
The hardware device interface (HDI) is located between the basic system service layer and the device driver layer. It provides APIs for abstracting hardware device functions, which shields underlying hardware device differences for system services. For details, see [HDI Specifications](../../design/hdi-design-specifications.md).
### Working Principles ### Working Principles
The Face_auth driver provides basic facial authentication capabilities for the User_auth and Face_auth service to ensure successful facial authentication. The Face_auth driver provides basic facial authentication capabilities for the User_auth and Face_auth service to ensure successful facial authentication.
...@@ -74,19 +90,23 @@ The Face_auth driver provides basic facial authentication capabilities for the U ...@@ -74,19 +90,23 @@ The Face_auth driver provides basic facial authentication capabilities for the U
### Available APIs ### Available APIs
The following table describes the C++ APIs generated from the Interface Definition Language (IDL) interface description. For details about the interface declaration, see the .idl file in **/drivers/interface/face_auth/v1_0/**.
**Table 1** describes the HDI APIs for face credential enrollment, authentication, recognition, and deletion. **Table 2** describes the callbacks used to return the executor operation result to the framework or return the authentication tip information to upper-layer applications.
**Table 1** Available APIs **Table 1** Available APIs
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ----------------------------------- | ---------------------------------- |
| GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. | | GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. |
| GetExecutorInfo(ExecutorInfo& info) | Obtains the executor information, including the executor type, executor role, authentication type, security level, and executor public key.| | GetExecutorInfo(ExecutorInfo& info) | Obtains the executor information, including the executor type, executor role, authentication type, security level, and executor public key.|
| GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about a face image template based on the specified template ID. | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about a face image template based on the specified template ID. |
| OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.| | OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.|
| Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls a face image template. | | Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls a face image. |
| Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Performs facial authentication. | | Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Performs facial authentication. |
| Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Performs facial identification. | | Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Performs facial identification. |
| Delete(const std::vector<uint64_t>& templateIdList) | Deletes a face image template. | | Delete(const std::vector<uint64_t>& templateIdList) | Deletes a face image. |
| Cancel(uint64_t scheduleId) | Cancels a face enrolling, authentication, or identification operation based on the **scheduleId**. | | Cancel(uint64_t scheduleId) | Cancels a face enrollment, authentication, or identification operation based on the **scheduleId**. |
| SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Sends commands to the Face_auth service. | | SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Sends commands to the Face_auth service. |
**Table 2** Callbacks **Table 2** Callbacks
...@@ -102,15 +122,15 @@ The following uses the Hi3516D V300 development board as an example to demonstra ...@@ -102,15 +122,15 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined ```undefined
// drivers/peripheral/face_auth // drivers/peripheral/face_auth
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── bundle.json # Module description file ├── bundle.json # Component description file
└── hdi_service # Face_auth driver implementation └── hdi_service # Face_auth driver implementation
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── include # Header files ├── include # Header files
└── src └── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs ├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── face_auth_interface_driver.cpp # Face_auth driver entry ├── face_auth_interface_driver.cpp # Face_auth driver entry
└── face_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list └── face_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list
``` ```
The development procedure is as follows: The development procedure is as follows:
...@@ -214,7 +234,7 @@ The development procedure is as follows: ...@@ -214,7 +234,7 @@ The development procedure is as follows:
HDF_INIT(g_faceAuthInterfaceDriverEntry); HDF_INIT(g_faceAuthInterfaceDriverEntry);
``` ```
2. Implement the API for obtaining the executor list. For details about the code, see [face_auth_interface_service.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/face_auth/hdi_service/src/face_auth_interface_service.cpp). 2. Implement the APIs for obtaining the executor list. For details about the code, see [face_auth_interface_service.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/face_auth/hdi_service/src/face_auth_interface_service.cpp).
```c++ ```c++
// Executor implementation class // Executor implementation class
...@@ -267,7 +287,7 @@ The development procedure is as follows: ...@@ -267,7 +287,7 @@ The development procedure is as follows:
} }
``` ```
3. Implement each function of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/face_auth/hdi_service/src/executor_impl.cpp). 3. Implement the functions of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/face_auth/hdi_service/src/executor_impl.cpp).
```c++ ```c++
// Obtain the executor information. // Obtain the executor information.
...@@ -423,65 +443,59 @@ The development procedure is as follows: ...@@ -423,65 +443,59 @@ The development procedure is as follows:
Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The sample code for verifying and canceling the authentication is as follows: Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The sample code for verifying and canceling the authentication is as follows:
```js ```js
// API version 8 // API version 9
import userIAM_userAuth from '@ohos.userIAM.userAuth'; import userIAM_userAuth from '@ohos.userIAM.userAuth';
let auth = new userIAM_userAuth.UserAuth();
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
export default { let authType = userIAM_userAuth.UserAuthType.FACE;
getVersion() { let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
console.info("start to get version");
let version = this.auth.getVersion(); // Obtain an authentication object.
console.info("auth version = " + version); let auth;
}, try {
auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
startAuth() { console.log("get auth instance success");
console.info("start auth"); } catch (error) {
this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { console.log("get auth instance failed" + error);
onResult: (result, extraInfo) => { }
try {
console.info("auth onResult result = " + result); // Subscribe to the authentication result.
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); try {
if (result == userIAM_userAuth.ResultCode.SUCCESS) { auth.on("result", {
// Add the logic to be executed when the authentication is successful. callback: (result: userIAM_userAuth.AuthResultInfo) => {
} else { console.log("authV9 result " + result.result);
// Add the logic to be executed when the authentication fails. console.log("authV9 token " + result.token);
} console.log("authV9 remainAttempts " + result.remainAttempts);
} catch (e) { console.log("authV9 lockoutDuration " + result.lockoutDuration);
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
try {
console.info("auth onAcquireInfo module = " + module);
console.info("auth onAcquireInfo acquire = " + acquire);
console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
} catch (e) {
console.info("auth onAcquireInfo error = " + e);
}
}
});
},
cancelAuth() {
console.info("start cancel auth");
// Obtain contextId using auth().
let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
console.info("auth onResult result = " + result);
},
onAcquireInfo: (module, acquire, extraInfo) => {
console.info("auth onAcquireInfo module = " + module);
} }
}); });
let cancelCode = this.auth.cancel(contextId); console.log("subscribe authentication event success");
if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { } catch (error) {
console.info("Authentication canceled successfully"); console.log("subscribe authentication event failed " + error);
} else {
console.error("failed to cancel authentication");
}
} }
}
``` // Start user authentication.
try {
auth.start();
console.info("authV9 start auth success");
} catch (error) {
console.info("authV9 start auth failed, error = " + error);
}
// Cancel the authentication.
try {
auth.cancel();
console.info("Authentication canceled successfully");
} catch (error) {
console.info("cancel auth failed, error = " + error);
}
// Unsubscribe from the authentication result.
try {
auth.off("result");
console.info("cancel subscribe authentication event success");
} catch (error) {
console.info("cancel subscribe authentication event failed, error = " + error);
}
```
...@@ -21,7 +21,7 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -21,7 +21,7 @@ The identity authentication consists of the User_auth framework and basic authen
- Executor security level - Executor security level
Security level required for the execution environment of an executor. Security level of the runtime environment when an executor provides capabilities.
- Executor role - Executor role
...@@ -39,9 +39,9 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -39,9 +39,9 @@ The identity authentication consists of the User_auth framework and basic authen
To ensure user data security and authentication result accuracy, measures must be taken to protect the integrity of the key information exchanged between User_auth and basic authentication services. Public keys must be exchanged when the executor provided by a basic authentication service interworks with User_auth. To ensure user data security and authentication result accuracy, measures must be taken to protect the integrity of the key information exchanged between User_auth and basic authentication services. Public keys must be exchanged when the executor provided by a basic authentication service interworks with User_auth.
The executor uses the User_auth public key to verify scheduling instructions. The executor uses the User_auth public key to verify scheduling instructions.
User_auth uses the executor public key to verify the authentication result accuracy and the integrity of the information exchanged with the executor. User_auth uses the executor public key to verify the authentication result accuracy and the integrity of the information exchanged with the executor.
- Authentication credential - Authentication credential
...@@ -53,23 +53,23 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -53,23 +53,23 @@ The identity authentication consists of the User_auth framework and basic authen
- HAPs - HAPs
OpenHarmony Ability Packages (HAPs) represent the upper-layer applications of the Fingerprint_auth driver in this document. In a broad sense, OpenHarmony Ability Packages (HAPs) are application packages that can be installed on OpenHarmony. In this document, the HAPs only refer to the upper-layer applications of the Face_auth driver.
- IDL interface - IDL interface
An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. In this document, the IDL interface implements communication between the Fingerprint_auth service and the driver. An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. This document describes how to use the client and server generated by the IDL interface to implement communication between the Fingerprint_auth service and driver. For details, see [IDL](https://gitee.com/openharmony/ability_idl_tool/blob/master/README.md).
- IPC - IPC
Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other. Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other. For details, see [IPC](https://gitee.com/openharmony/communication_ipc/blob/master/README.md).
### Working Principles - HDI
The fingerprint_auth driver provides stable basic fingerprint authentication capabilities for the upper-layer User_auth framework and Fingerprint_auth service to ensure successful fingerprint authentication on devices. The hardware device interface (HDI) is located between the basic system service layer and the device driver layer. It provides APIs for abstracting hardware device functions, which shields underlying hardware device differences for system services. For details, see [HDI Specifications](../../design/hdi-design-specifications.md).
The figure below shows the interaction between the Fingerprint_auth service and the Fingerprint_auth driver. ### Working Principles
The Fingerprint_auth service obtains the executor information by using **GetExecutorInfo()** and registers the executor with the User_auth framework. The Fingerprint_auth service exchanges information with the Fingerprint_auth driver for authentication, identification, and query through the executor APIs. The fingerprint_auth driver provides stable basic fingerprint authentication capabilities for the upper-layer User_auth framework and Fingerprint_auth service to ensure successful fingerprint authentication on devices. The figure below shows the interaction between the Fingerprint_auth service and the Fingerprint_auth driver. The Fingerprint_auth service obtains executor information by using **GetExecutorInfo()** and registers the executor with the User_auth framework. The Fingerprint_auth service exchanges information with the Fingerprint_auth driver for authentication, identification, and query through the executor APIs.
You can develop drivers to call Hardware Device Interface (HDI) APIs based on the HDF and the chip you use. You can develop drivers to call Hardware Device Interface (HDI) APIs based on the HDF and the chip you use.
**Figure 2** Interaction between the Fingerprint_auth service and Fingerprint_auth driver **Figure 2** Interaction between the Fingerprint_auth service and Fingerprint_auth driver
...@@ -88,19 +88,22 @@ The fingerprint_auth driver provides stable basic fingerprint authentication cap ...@@ -88,19 +88,22 @@ The fingerprint_auth driver provides stable basic fingerprint authentication cap
### Available APIs ### Available APIs
The following table describes the C++ APIs generated from the Interface Definition Language (IDL) interface description. For details about the interface declaration, see the .idl file in **/drivers/interface/fingerprint_auth/v1_0/**.
**Table 1** describes the HDI APIs for fingerprint credential enrollment, authentication, recognition, and deletion. **Table 2** describes the callbacks used to return the executor operation result to the framework or return the authentication tip information to upper-layer applications.
**Table 1** Available APIs **Table 1** Available APIs
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | -------------------------------- | ----------------------------------- |
| GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. | | GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. |
| GetExecutorInfo(ExecutorInfo& info) | Obtains the executor information, including the executor type, executor role, authentication type, security level, and executor public key.| | GetExecutorInfo(ExecutorInfo& info) | Obtains the executor information, including the executor type, executor role, authentication type, security level, and executor public key.|
| GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about the template based on the specified ID. | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about the template based on the specified ID. |
| OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.| | OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& frameworkPublicKey, const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.|
| Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls a fingerprint template. | | Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Enrolls a fingerprint. |
| Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Authenticates a fingerprint template. | | Authenticate(uint64_t scheduleId, const std::vector<uint64_t>& templateIdList,<br> const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Authenticates a fingerprint. |
| Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Identifies a fingerprint template. | | Identify(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Identifies a fingerprint. |
| Delete(const std::vector<uint64_t>& templateIdList) | Deletes a fingerprint template. | | Delete(const std::vector<uint64_t>& templateIdList) | Deletes a fingerprint. |
| Cancel(uint64_t scheduleId) | Cancels a fingerprint enrolling, authentication, or identification operation based on the **scheduleId**. | | Cancel(uint64_t scheduleId) | Cancels a fingerprint enrollment, authentication, or identification operation based on the **scheduleId**. |
| SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Sends commands to the Fingerprint_auth driver. | | SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br> const sptr<IExecutorCallback>& callbackObj) | Sends commands to the Fingerprint_auth driver. |
**Table 2** Callbacks **Table 2** Callbacks
...@@ -116,12 +119,12 @@ The following uses the Hi3516D V300 development board as an example to demonstra ...@@ -116,12 +119,12 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined ```undefined
// drivers/peripheral/fingerprint_auth // drivers/peripheral/fingerprint_auth
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── bundle.json # Module description file ├── bundle.json # Component description file
└── hdi_service # Fingerprint_auth driver implementation └── hdi_service # Fingerprint_auth driver implementation
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── include # Header files ├── include # Header files
└── src └── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs ├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── fingerprint_auth_interface_driver.cpp # Fingerprint_auth driver entry ├── fingerprint_auth_interface_driver.cpp # Fingerprint_auth driver entry
└── fingerprint_auth_interface_service.cpp # Implementation of the API for obtaining the executor list └── fingerprint_auth_interface_service.cpp # Implementation of the API for obtaining the executor list
...@@ -281,7 +284,7 @@ The development procedure is as follows: ...@@ -281,7 +284,7 @@ The development procedure is as follows:
} }
``` ```
3. Implement each function of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/executor_impl.cpp).<br>The sample code is as follows: 3. Implement functions of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/fingerprint_auth/hdi_service/src/executor_impl.cpp).<br>The sample code is as follows:
```c++ ```c++
// Obtain the executor information. // Obtain the executor information.
...@@ -364,7 +367,7 @@ The development procedure is as follows: ...@@ -364,7 +367,7 @@ The development procedure is as follows:
return HDF_SUCCESS; return HDF_SUCCESS;
} }
// Delete a fingerprint template. // Delete fingerprints.
int32_t Delete(const std::vector<uint64_t>& templateIdList) int32_t Delete(const std::vector<uint64_t>& templateIdList)
{ {
IAM_LOGI("interface mock start"); IAM_LOGI("interface mock start");
...@@ -435,50 +438,61 @@ The development procedure is as follows: ...@@ -435,50 +438,61 @@ The development procedure is as follows:
### Verification ### Verification
Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The JavaScript application invokes the Fingerprint_auth driver via the Fingerprint_auth service. Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The JavaScript application invokes the Fingerprint_auth driver via the Fingerprint_auth service. The sample code is as follows:
The sample code is as follows: ```js
// API version 9
```js import userIAM_userAuth from '@ohos.userIAM.userAuth';
// API version 8
import userIAM_userAuth from '@ohos.userIAM.userAuth'; let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
let auth = new userIAM_userAuth.UserAuth(); let authType = userIAM_userAuth.UserAuthType.FINGERPRINT;
let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
export default {
getVersion() { // Obtain an authentication object.
console.info("start to get version"); let auth;
let version = this.auth.getVersion(); try {
console.info("auth version = " + version); auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
}, console.log("get auth instance success");
} catch (error) {
startAuth() { console.log("get auth instance failed" + error);
console.info("start auth"); }
// auth is an API that can be called. You can set the authentication type to FINGERPRINT to check whether the driver is successfully registered with the framework and whether the authentication APIs are implemented as expected. result holds the authentication result.
this.auth.auth(null, userIAM_userAuth.UserAuthType.FINGERPRINT, userIAM_userAuth.AuthTrustLevel.ATL1, { // Subscribe to the authentication result.
onResult: (result, extraInfo) => { try {
try { auth.on("result", {
console.info("auth onResult result = " + result); callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); console.log("authV9 result " + result.result);
if (result == userIAM_userAuth.ResultCode.SUCCESS) { console.log("authV9 token " + result.token);
// Add the logic to be executed when the authentication is successful. console.log("authV9 remainAttempts " + result.remainAttempts);
} else { console.log("authV9 lockoutDuration " + result.lockoutDuration);
// Add the logic to be executed when the authentication fails.
}
} catch (e) {
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
try {
console.info("auth onAcquireInfo module = " + module);
console.info("auth onAcquireInfo acquire = " + acquire);
console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
} catch (e) {
console.info("auth onAcquireInfo error = " + e);
}
} }
}); });
console.log("subscribe authentication event success");
} catch (error) {
console.log("subscribe authentication event failed " + error);
} }
}
``` // Start user authentication.
try {
auth.start();
console.info("authV9 start auth success");
} catch (error) {
console.info("authV9 start auth failed, error = " + error);
}
// Cancel the authentication.
try {
auth.cancel();
console.info("cancel auth success");
} catch (error) {
console.info("cancel auth failed, error = " + error);
}
// Unsubscribe from the authentication result.
try {
auth.off("result");
console.info("cancel subscribe authentication event success");
} catch (error) {
console.info("cancel subscribe authentication event failed, error = " + error);
}
```
...@@ -21,7 +21,7 @@ The identity authentication consists of User_auth and basic authentication servi ...@@ -21,7 +21,7 @@ The identity authentication consists of User_auth and basic authentication servi
- Executor security level - Executor security level
Security level required for the execution environment of an executor. Security level of the runtime environment when an executor provides capabilities.
- Executor role - Executor role
...@@ -52,6 +52,18 @@ The identity authentication consists of User_auth and basic authentication servi ...@@ -52,6 +52,18 @@ The identity authentication consists of User_auth and basic authentication servi
User_auth manages the mappings between user identities and credential IDs in a unified manner. When connecting to User_auth, the executor obtains the template ID list from User_auth and updates its template ID list based on the template ID list obtained. User_auth manages the mappings between user identities and credential IDs in a unified manner. When connecting to User_auth, the executor obtains the template ID list from User_auth and updates its template ID list based on the template ID list obtained.
- IDL interface
An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. This document describes how to use the client and server generated by the IDL interface to implement communication between the Pin_auth service and driver. For details, see [IDL](https://gitee.com/openharmony/ability_idl_tool/blob/master/README.md).
- IPC
Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other. For details, see [IPC](https://gitee.com/openharmony/communication_ipc/blob/master/README.md).
- HDI
The hardware device interface (HDI) is located between the basic system service layer and the device driver layer. It provides APIs for abstracting hardware device functions, which shields underlying hardware device differences for system services. For details, see [HDI Specifications](../../design/hdi-design-specifications.md).
### Working Principles ### Working Principles
The Pin_auth driver provides basic PIN authentication capabilities for the upper-layer User_auth and Pin_auth service to ensure successful PIN authentication. You can develop drivers to call Hardware Device Interface (HDI) APIs based on the HDF and the chip you use. The Pin_auth driver provides basic PIN authentication capabilities for the upper-layer User_auth and Pin_auth service to ensure successful PIN authentication. You can develop drivers to call Hardware Device Interface (HDI) APIs based on the HDF and the chip you use.
...@@ -61,7 +73,8 @@ The Pin_auth driver provides basic PIN authentication capabilities for the upper ...@@ -61,7 +73,8 @@ The Pin_auth driver provides basic PIN authentication capabilities for the upper
![image](figures/pin_auth_service_and_driver_interaction.png "interaction between the pin_auth service and driver") ![image](figures/pin_auth_service_and_driver_interaction.png "interaction between the pin_auth service and driver")
### Constraints ### Constraints
PIN authentication must be implemented in a Trusted Execution Environment (TEE), and the confidential information, such as PINs and credentials, must be stored in a TEE. PIN authentication must be implemented in a Trusted Execution Environment (TEE), and the confidential information, such as PINs and credentials, must be encrypted and stored in a TEE.
## Development Guidelines ## Development Guidelines
### When to Use ### When to Use
...@@ -69,20 +82,23 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_ ...@@ -69,20 +82,23 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_
### Available APIs ### Available APIs
The following table describes the C++ APIs generated from the Interface Definition Language (IDL) interface description. For details about the interface declaration, see the .idl file in **/drivers/interface/pin_auth/v1_0/**.
**Table 1** describes the HDI APIs for PIN credential enrollment, authentication, and deletion. **Table 2** describes the callbacks used to return the executor operation result to the framework or return the PIN entered by the user.
**Table 1** Available APIs **Table 1** Available APIs
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------- |
| GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list. | | GetExecutorList(std::vector<sptr<IExecutor>>& executorList) | Obtains the executor list.|
| GetExecutorInfo(ExecutorInfo& info) | Obtains information about an executor. | | GetExecutorInfo(ExecutorInfo& info) | Obtains information about an executor. |
| GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about a template. | | GetTemplateInfo(uint64_t templateId, TemplateInfo& info) | Obtains information about a template. |
| OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br>const std::vector<uint8_t>& frameworkPublicKey,<br>const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.| | OnRegisterFinish(const std::vector<uint64_t>& templateIdList,<br>const std::vector<uint8_t>& frameworkPublicKey,<br>const std::vector<uint8_t>& extraInfo) | Obtains the public key and template ID list from User_auth after the executor is registered successfully.|
| OnSetData(uint64_t scheduleId, uint64_t authSubType, <br>const std::vector<uint8_t> &data) | Called to return the subtype and anonymized data of PIN authentication. | | OnSetData(uint64_t scheduleId, uint64_t authSubType, <br>const std::vector<uint8_t> &data) | Called to return the subtype of the PIN enrolled by the user and the anonymization PIN data. |
| Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br>const sptr<IExecutorCallback>& callbackObj) | Enrolls a PIN. | | Enroll(uint64_t scheduleId, const std::vector<uint8_t>& extraInfo,<br>const sptr<IExecutorCallback>& callbackObj) | Enrolls a PIN. |
| Authenticate(uint64_t scheduleId, uint64_t templateId, const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Starts PIN authentication. | | Authenticate(uint64_t scheduleId, uint64_t templateId, const std::vector<uint8_t>& extraInfo, const sptr<IExecutorCallback>& callbackObj) | Starts PIN authentication. |
| Delete(uint64_t templateId) | Deletes a PIN template. | | Delete(uint64_t templateId) | Deletes a PIN template. |
| Cancel(uint64_t scheduleId) | Cancels an operation. | | Cancel(uint64_t scheduleId) | Cancels an operation. |
| SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br>const sptr<IExecutorCallback>& callbackObj) | Reserved. | | SendCommand(int32_t commandId, const std::vector<uint8_t>& extraInfo,<br>const sptr<IExecutorCallback>& callbackObj) | Reserved. |
**Table 2** Callbacks **Table 2** Callbacks
...@@ -93,27 +109,25 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_ ...@@ -93,27 +109,25 @@ The Pin_auth driver provides basic PIN authentication capabilities for the User_
### How to Develop ### How to Develop
The following uses the RK3568 platform as an example to demonstrate how to develop the Pin_auth driver. The following uses the RK3568 platform as an example to demonstrate how to develop the Pin_auth driver. <br/>The directory structure is as follows:
The directory structure is as follows:
```text ```text
// drivers/peripheral/pin_auth // drivers/peripheral/pin_auth
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── bundle.json # Module description file ├── bundle.json # Component description file
├── test # Test cases ├── test # Test cases
└── hdi_service # Pin_auth driver implementation └── hdi_service # Pin_auth driver implementation
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── adaptor # Implementation of related algorithms ├── adaptor # Implementation of related algorithms
├── common # Implementation of common interfaces ├── common # Implementation of common interfaces
├── database # Database implementation ├── database # Database implementation
├── main # Entry for implementing PIN-related functions ├── main # Entry for implementing PIN-related functions
└── service # Entry for implementing the Pin_auth driver └── service # Entry for implementing the Pin_auth driver
├── inc # Header files ├── inc # Header files
└── src └── src # Source files
├── executor_impl.cpp # Implementation of authentication and enrollment APIs ├── executor_impl.cpp # Implementation of authentication and enrollment APIs
├── pin_auth_interface_driver.cpp # Pin_auth driver entry ├── pin_auth_interface_driver.cpp # Pin_auth driver entry
└── pin_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list └── pin_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list
``` ```
The development procedure is as follows: The development procedure is as follows:
...@@ -293,7 +307,7 @@ The development procedure is as follows: ...@@ -293,7 +307,7 @@ The development procedure is as follows:
1. Implement each function of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/pin_auth/hdi_service/service/src/executor_impl.cpp). 1. Implement functions of the executor. For details about the code, see [executor_impl.cpp](https://gitee.com/openharmony/drivers_peripheral/blob/master/pin_auth/hdi_service/service/src/executor_impl.cpp).
```c++ ```c++
// Obtain executor information (example only). // Obtain executor information (example only).
...@@ -535,7 +549,7 @@ The development procedure is as follows: ...@@ -535,7 +549,7 @@ The development procedure is as follows:
Verify whether PIN authentication can be successfully performed on the RK3568 platform as follows: Verify whether PIN authentication can be successfully performed on the RK3568 platform as follows:
1. Set a PIN. 1. Set a PIN.
Touch **Settings** > **Biometrics & passwords** > **Password**, and enter your password. Touch **Settings** > **Biometrics & passwords** > **Password**, and enter your password.
2. Verify PIN authentication. 2. Verify PIN authentication.
......
...@@ -21,7 +21,7 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -21,7 +21,7 @@ The identity authentication consists of the User_auth framework and basic authen
- Authentication credential template - Authentication credential template
The authentication credential template is generated and stored by the authentication service when a user sets the authentication credential. The template information needs to be compared with the authentication data generated during authentication to complete identity authentication. Each template has an ID to index a set of template information files. The authentication credential template is generated and stored by the authentication service when a user sets the authentication credential. Each template has an ID to index a set of template information files. The template information needs to be compared with the authentication data generated during authentication to complete identity authentication.
- Executor - Executor
...@@ -29,11 +29,11 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -29,11 +29,11 @@ The identity authentication consists of the User_auth framework and basic authen
- Executor role - Executor role
- Executor: independently completes the entire process of credential registration and identity authentication. The executor can collect, process, store, and compare data to complete the authentication. - Executor: independently completes the entire process of credential registration and identity authentication. The executor can collect, process, store, and compare data to complete the authentication.
- Collector: only collects data during user authentication. It needs to work with the authenticator to complete user authentication. - Collector: only collects data during user authentication. It needs to work with the authenticator to complete user authentication.
- Authenticator: processes data, obtains the stored credential template, and compares it with the authentication information generated. - Authenticator: processes data, obtains the stored credential template, and compares it with the authentication information generated.
- Executor type - Executor type
...@@ -41,7 +41,7 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -41,7 +41,7 @@ The identity authentication consists of the User_auth framework and basic authen
- Executor security level - Executor security level
Security level required for the execution environment of an executor. Security level of the runtime environment when an executor provides capabilities.
- User_auth public key & executor public key - User_auth public key & executor public key
...@@ -76,6 +76,18 @@ The identity authentication consists of the User_auth framework and basic authen ...@@ -76,6 +76,18 @@ The identity authentication consists of the User_auth framework and basic authen
Inner API is an API provided by OpenHarmony for system applications. Inner API is an API provided by OpenHarmony for system applications.
- IDL interface
An Interface Definition Language (IDL) is a language that lets a program or object written in one language communicate with another program written in an unknown language. An IDL compiler generates client stub files and server framework files. This document describes how to use the client and server generated by the IDL interface to implement communication between the User_auth service and driver. For details, see [IDL](https://gitee.com/openharmony/ability_idl_tool/blob/master/README.md).
- IPC
Inter-Process Communication (IPC) is a mechanism that allows processes to communicate with each other. For details, see [IPC](https://gitee.com/openharmony/communication_ipc/blob/master/README.md).
- HDI
The hardware device interface (HDI) is located between the basic system service layer and the device driver layer. It provides APIs for abstracting hardware device functions, which shields underlying hardware device differences for system services. For details, see [HDI Specifications](../../design/hdi-design-specifications.md).
### Working Principles ### Working Principles
The User_auth driver shields the differences of security devices and environments. It provides unified interfaces for the User_auth service to implement management of executors and credentials as well as authentication scheme generation. The User_auth driver shields the differences of security devices and environments. It provides unified interfaces for the User_auth service to implement management of executors and credentials as well as authentication scheme generation.
...@@ -97,30 +109,33 @@ The User_auth driver provides stable user credential management, authentication ...@@ -97,30 +109,33 @@ The User_auth driver provides stable user credential management, authentication
### Available APIs ### Available APIs
The following table describes the C++ APIs generated from the Interface Definition Language (IDL) interface description. For details about the interface declaration, see the .idl file in **/drivers/interface/user_auth/v1_0/**.
**Table 1** describes the HDI APIs for executor registration, credential enrollment and deletion, user authentication, and user identification.
**Table 1** Available APIs **Table 1** Available APIs
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | --------------------------- | --------------------------- |
| Init() | Initializes cached information. | | Init() | Initializes cached information. |
| AddExecutor(const ExecutorRegisterInfo& info, uint64_t& index, std::vector<uint8_t>& publicKey,<br> std::vector<uint64_t>& templateIds) | Adds an executor to obtain the authentication capability. | | AddExecutor(const ExecutorRegisterInfo& info, uint64_t& index, std::vector<uint8_t>& publicKey,<br> std::vector<uint64_t>& templateIds) | Adds an executor to obtain the authentication capability. |
| DeleteExecutor(uint64_t index) | Deletes an executor. | | DeleteExecutor(uint64_t index) | Deletes an executor. |
| OpenSession(int32_t userId, std::vector<uint8_t>& challenge) | Opens a session for authentication credential management. | | OpenSession(int32_t userId, std::vector<uint8_t>& challenge) | Opens a session for authentication credential management. |
| CloseSession(int32_t userId) | Closes a session for authentication credential management. | | CloseSession(int32_t userId) | Closes a session for authentication credential management. |
| BeginEnrollment(int32_t userId, const std::vector<uint8_t>& authToken, const EnrollParam& param,<br> ScheduleInfo& info) | Enrolls the user authentication credential. If a user has enrolled a PIN, the old PIN will be overwritten.| | BeginEnrollment(int32_t userId, const std::vector<uint8_t>& authToken, const EnrollParam& param,<br> ScheduleInfo& info) | Enrolls the user authentication credential. If a user has enrolled a PIN, the old PIN will be overwritten.|
| UpdateEnrollmentResult(int32_t userId, const std::vector<uint8_t>& scheduleResult, uint64_t& credentialId,<br> CredentialInfo& oldInfo) | Updates the data to complete this enrollment. | | UpdateEnrollmentResult(int32_t userId, const std::vector<uint8_t>& scheduleResult, uint64_t& credentialId,<br> CredentialInfo& oldInfo) | Updates the data to complete this enrollment. |
| CancelEnrollment(int32_t userId) | Cancels an enrollment operation. | | CancelEnrollment(int32_t userId) | Cancels an enrollment operation. |
| DeleteCredential(int32_t userId, uint64_t credentialId, const std::vector<uint8_t>& authToken,<br> CredentialInfo& info) | Deletes credential information based on the specified **credentialId**. | | DeleteCredential(int32_t userId, uint64_t credentialId, const std::vector<uint8_t>& authToken,<br> CredentialInfo& info) | Deletes credential information based on the specified **credentialId**. |
| DeleteUser(int32_t userId, const std::vector<uint8_t>& authToken,<br> std::vector<CredentialInfo>& deletedInfos) | Deletes a user PIN from User_auth. | | DeleteUser(int32_t userId, const std::vector<uint8_t>& authToken,<br> std::vector<CredentialInfo>& deletedInfos) | Deletes a user PIN from User_auth. |
| EnforceDeleteUser(int32_t userId, std::vector<CredentialInfo>& deletedInfos) | Forcibly deletes a user. This API will be called when a user is deleted from the system. | | EnforceDeleteUser(int32_t userId, std::vector<CredentialInfo>& deletedInfos) | Forcibly deletes a user. This API will be called when a user is deleted from the system. |
| GetCredential(int32_t userId, AuthType authType, std::vector<CredentialInfo>& infos) | Obtains user credential information by authentication type. | | GetCredential(int32_t userId, AuthType authType, std::vector<CredentialInfo>& infos) | Obtains user credential information by authentication type. |
| GetSecureInfo(int32_t userId, uint64_t& secureUid, std::vector<EnrolledInfo>& infos) | Obtains the secure user ID and the enrolled tag ID of each authentication type. | | GetSecureInfo(int32_t userId, uint64_t& secureUid, std::vector<EnrolledInfo>& infos) | Obtains the secure user ID and the enrolled tag ID of each authentication type. |
| BeginAuthentication(uint64_t contextId, const AuthSolution& param,<br> std::vector<ScheduleInfo>& scheduleInfos) | Starts an authentication to generate the authentication scheme and scheduling information. | | BeginAuthentication(uint64_t contextId, const AuthSolution& param,<br> std::vector<ScheduleInfo>& scheduleInfos) | Starts an authentication to generate the authentication scheme and scheduling information. |
| UpdateAuthenticationResult(uint64_t contextId, const std::vector<uint8_t>& scheduleResult,<br> AuthResultInfo& info) | Updates the authentication result to evaluate the authentication scheme. | | UpdateAuthenticationResult(uint64_t contextId, const std::vector<uint8_t>& scheduleResult,<br> AuthResultInfo& info) | Updates the authentication result to evaluate the authentication scheme. |
| CancelAuthentication(uint64_t contextId) | Cancels an authentication. | | CancelAuthentication(uint64_t contextId) | Cancels an authentication. |
| BeginIdentification(uint64_t contextId, AuthType authType, const std::vector<int8_t>& challenge,<br> uint32_t executorId, ScheduleInfo& scheduleInfo) | Starts an identification to generate the identification scheme and scheduling information. | | BeginIdentification(uint64_t contextId, AuthType authType, const std::vector<int8_t>& challenge,<br> uint32_t executorId, ScheduleInfo& scheduleInfo) | Starts an identification to generate the identification scheme and scheduling information. |
| UpdateIdentificationResult(uint64_t contextId, const std::vector<uint8_t>& scheduleResult,<br> IdentifyResultInfo& info) | Updates the identification result to evaluate the identification scheme. | | UpdateIdentificationResult(uint64_t contextId, const std::vector<uint8_t>& scheduleResult,<br> IdentifyResultInfo& info) | Updates the identification result to evaluate the identification scheme. |
| CancelIdentification(uint64_t contextId) | Cancels an identification. | | CancelIdentification(uint64_t contextId) | Cancels an identification. |
| GetAuthTrustLevel(int32_t userId, AuthType authType, uint32_t& authTrustLevel) | Obtains the authentication trust level of the specified authentication type. | | GetAuthTrustLevel(int32_t userId, AuthType authType, uint32_t& authTrustLevel) | Obtains the authentication trust level of the specified authentication type. |
| GetValidSolution(int32_t userId, const std::vector<AuthType>& authTypes, uint32_t authTrustLevel,<br> std::vector<AuthType>& validTypes) | Obtains the valid authentication scheme based on the authentication trust level for a user. | | GetValidSolution(int32_t userId, const std::vector<AuthType>& authTypes, uint32_t authTrustLevel,<br> std::vector<AuthType>& validTypes) | Obtains the valid authentication scheme based on the authentication trust level for a user. |
### How to Develop ### How to Develop
...@@ -129,13 +144,13 @@ The following uses the Hi3516D V300 development board as an example to demonstra ...@@ -129,13 +144,13 @@ The following uses the Hi3516D V300 development board as an example to demonstra
```undefined ```undefined
// drivers/peripheral/user_auth // drivers/peripheral/user_auth
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── bundle.json # Module description file ├── bundle.json # Component description file
└── hdi_service # User_auth driver implementation └── hdi_service # User_auth driver implementation
├── BUILD.gn # Build script ├── BUILD.gn # Build script
├── module # Implementation of functionalities ├── module # Implementation of functionalities
└── service └── service
├── user_auth_interface_driver.cpp # User_auth driver entry ├── user_auth_interface_driver.cpp # User_auth driver entry
└── user_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list └── user_auth_interface_service.cpp # Implementation of the APIs for obtaining the executor list
``` ```
...@@ -397,7 +412,7 @@ The development procedure is as follows: ...@@ -397,7 +412,7 @@ The development procedure is as follows:
{ {
IAM_LOGI("start"); IAM_LOGI("start");
if (param.challenge.size() != sizeof(uint64_t)) { if (param.challenge.size() != sizeof(uint64_t)) {
IAM_LOGE("challenge copy failed"); IAM_LOGE("Failed to copy the challenge");
return RESULT_BAD_PARAM; return RESULT_BAD_PARAM;
} }
GlobalLock(); GlobalLock();
...@@ -410,7 +425,7 @@ The development procedure is as follows: ...@@ -410,7 +425,7 @@ The development procedure is as follows:
solutionIn.authTrustLevel = param.authTrustLevel; solutionIn.authTrustLevel = param.authTrustLevel;
if (memcpy_s(&solutionIn.challenge, sizeof(uint64_t), &param.challenge[0], if (memcpy_s(&solutionIn.challenge, sizeof(uint64_t), &param.challenge[0],
param.challenge.size()) != EOK) { param.challenge.size()) != EOK) {
IAM_LOGE("challenge copy failed"); IAM_LOGE("Failed to copy the challenge");
GlobalUnLock(); GlobalUnLock();
return RESULT_BAD_COPY; return RESULT_BAD_COPY;
} }
...@@ -494,65 +509,59 @@ The development procedure is as follows: ...@@ -494,65 +509,59 @@ The development procedure is as follows:
Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The sample code for verifying and canceling the authentication is as follows: Use the [User Authentication APIs](../../application-dev/reference/apis/js-apis-useriam-userauth.md) to develop a JavaScript application and verify the application on the Hi3516D V300 development board. The sample code for verifying and canceling the authentication is as follows:
```js ```js
// API version 8 // API version 9
import userIAM_userAuth from '@ohos.userIAM.userAuth'; import userIAM_userAuth from '@ohos.userIAM.userAuth';
let auth = new userIAM_userAuth.UserAuth();
let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
export default { let authType = userIAM_userAuth.UserAuthType.FACE;
getVersion() { let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
console.info("start get version");
let version = this.auth.getVersion(); // Obtain an authentication object.
console.info("auth version = " + version); let auth;
}, try {
auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
startAuth() { console.log("get auth instance success");
console.info("start auth"); } catch (error) {
this.auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { console.log("get auth instance failed" + error);
onResult: (result, extraInfo) => { }
try {
console.info("auth onResult result = " + result); // Subscribe to the authentication result.
console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); try {
if (result == 'SUCCESS') { auth.on("result", {
// Add the logic to be executed when the authentication is successful. callback: (result: userIAM_userAuth.AuthResultInfo) => {
} else { console.log("authV9 result " + result.result);
// Add the logic to be executed when the authentication fails. console.log("authV9 token " + result.token);
} console.log("authV9 remainAttempts " + result.remainAttempts);
} catch (e) { console.log("authV9 lockoutDuration " + result.lockoutDuration);
console.info("auth onResult error = " + e);
}
},
onAcquireInfo: (module, acquire, extraInfo) => {
try {
console.info("auth onAcquireInfo module = " + module);
console.info("auth onAcquireInfo acquire = " + acquire);
console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
} catch (e) {
console.info("auth onAcquireInfo error = " + e);
}
}
});
},
cancelAuth() {
console.info("start cancel auth");
// Obtain contextId using auth().
let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
onResult: (result, extraInfo) => {
console.info("auth onResult result = " + result);
},
onAcquireInfo: (module, acquire, extraInfo) => {
console.info("auth onAcquireInfo module = " + module);
} }
}); });
let cancelCode = this.auth.cancel(contextId); console.log("subscribe authentication event success");
if (cancelCode == userIAM_userAuth.Result.SUCCESS) { } catch (error) {
console.info("Authentication canceled successfully"); console.log("subscribe authentication event failed " + error);
} else {
console.error("Failed to cancel authentication");
}
} }
}
``` // Start user authentication.
try {
auth.start();
console.info("authV9 start auth success");
} catch (error) {
console.info("authV9 start auth failed, error = " + error);
}
// Cancel the authentication.
try {
auth.cancel();
console.info("Authentication canceled successfully");
} catch (error) {
console.info("cancel auth failed, error = " + error);
}
// Unsubscribe from the authentication result.
try {
auth.off("result");
console.info("cancel subscribe authentication event success");
} catch (error) {
console.info("cancel subscribe authentication event failed, error = " + error);
}
```
...@@ -2,9 +2,9 @@ ...@@ -2,9 +2,9 @@
Application privileges are high-level capabilities of an application, for example, restricting an application from being uninstalled or restricting application data from being deleted. Application privileges are high-level capabilities of an application, for example, restricting an application from being uninstalled or restricting application data from being deleted.
OpenHarmony provides both general and device-specific application privileges. The latter can be configured by device vendors for applications on different devices. OpenHarmony provides both general and device-specific application privileges. The latter can be configured by device vendors for applications on different devices. The privileges configured in the **install_list_capability.json** file take precedence over the privileges configured in the signature certificate.
Note: To avoid user dissatisfaction or even infringement, do not abuse application privileges. > **NOTE**<br>To avoid user dissatisfaction or even infringement, do not abuse application privileges.
## General Application Privileges ## General Application Privileges
...@@ -15,24 +15,21 @@ General application privileges are privileges available to applications on all t ...@@ -15,24 +15,21 @@ General application privileges are privileges available to applications on all t
| Privilege| Description | | Privilege| Description |
| ---------------- | ------------------------------------------------------------ | | ---------------- | ------------------------------------------------------------ |
| AllowAppDataNotCleared | Allows application data not to be deleted.| | AllowAppDataNotCleared | Allows application data not to be deleted.|
| AllowAppMultiProcess | Allows the application to run on multiple processes.|
| AllowAppDesktopIconHide | Allows the application icon to be hidden from the home screen.| | AllowAppDesktopIconHide | Allows the application icon to be hidden from the home screen.|
| AllowAbilityPriorityQueried | Allows an ability to configure and query the priority. | | AllowAbilityPriorityQueried | Allows an ability to configure and query the priority. |
| AllowAbilityExcludeFromMissions | Allows an ability to be hidden in the mission stack.| | AllowAbilityExcludeFromMissions | Allows an ability to be hidden in the mission stack.|
| AllowAppUsePrivilegeExtension | Allows the application to use Service Extension and Data Extension abilities.|
| AllowFormVisibleNotify | Allows a widget to be visible on the home screen.|
### Configuration ### How to Configure
1. In the [HarmonyAppProvision file](../../application-dev/security/app-provision-structure.md), configure the general privileges in the **app-privilege-capabilities** field. 1. Add the **app-privilege-capabilities** field to the [**HarmonyAppProvision** file](../../application-dev/security/app-provision-structure.md) to configure general privilege capabilities as required.
2. Use the signing tool hapsigner to sign the HarmonyAppProvision file and generate a **.p7b** file. 2. Use the hapsigner tool to sign the [**HarmonyAppProvision** file](../../application-dev/security/app-provision-structure.md) to generate a .p7b file.
3. Use the **.p7b** file to sign the HAP. 3. Use the .p7b file to sign the HAP.
Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#README.md) Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#README.md)
### Example ### Example
``` ```json
{ {
"version-name": "1.0.0", "version-name": "1.0.0",
... ...
...@@ -41,12 +38,10 @@ Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#READ ...@@ -41,12 +38,10 @@ Reference: [hapsigner](https://gitee.com/openharmony/developtools_hapsigner#READ
... ...
}, },
"issuer": "pki_internal", "issuer": "pki_internal",
"app-privilege-capabilities": ["AllowAppDataNotCleared", "AllowAppDesktopIconHide"] // The application data cannot be deleted, and icons can be hidden on the home screen. "app-privilege-capabilities": ["AllowAppDataNotCleared", "AllowAppDesktopIconHide"] // The application data cannot be deleted, and the application icon can be hidden on the home screen.
} }
``` ```
## Device-specific Application Privileges ## Device-specific Application Privileges
### Introduction ### Introduction
...@@ -55,43 +50,55 @@ In addition to general application privileges, device vendors can define device- ...@@ -55,43 +50,55 @@ In addition to general application privileges, device vendors can define device-
| Privilege | Type | Default Value| Description | | Privilege | Type | Default Value| Description |
| --------------------- | -------- | ------ | ------------------------------------------------- | | --------------------- | -------- | ------ | ------------------------------------------------- |
| removable | bool | true | Allows the application to be uninstalled. This privilege takes effect only for preset applications. | | removable | bool | true | Allows an application to be uninstalled. This privilege takes effect only for preset applications. |
| keepAlive | bool | false | Allows the application to keep running in the background. | | keepAlive | bool | false | Allows an application to keep running in the background. |
| singleton | bool | false | Allows the application to be installed for a single user (U0). | | singleton | bool | false | Allows an application to be installed for a single user (User 0). |
| allowCommonEvent | string[] | - | Allows the application to be started by a static broadcast. | | allowCommonEvent | string[] | - | Allows an application to be started by a static broadcast. |
| associatedWakeUp | bool | false | Allows the application in the FA model to be woken up by an associated application. | | associatedWakeUp | bool | false | Allows an application in the FA model to be woken up by an associated application. |
| runningResourcesApply | bool | false | Allows the application to request running resources, such as the CPU, event notifications, and Bluetooth.| | runningResourcesApply | bool | false | Allows an application to request running resources, such as the CPU, event notifications, and Bluetooth.|
| allowAppDataNotCleared | bool | false|Allows application data not to be deleted.|
### Configuration | allowAppMultiProcess | bool | false| Allows an application to run on multiple processes.|
| allowAppDesktopIconHide | bool | false| Allows the application icon to be hidden from the home screen.|
Configure the required privileges in [configuration files](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568/preinstall-config). | allowAbilityPriorityQueried | bool | false| Allows an ability to configure and query the priority. |
| allowAbilityExcludeFromMissions | bool | false| Allows an ability to be hidden in the mission stack.|
| allowAppUsePrivilegeExtension | bool | false|Allows an application to use ServiceExtension and DataExtension abilities.|
| allowFormVisibleNotify | bool | false| Allows a widget to be visible on the home screen.|
### How to Configure
Configure the required privileges in the [configuration file](https://gitee.com/openharmony/vendor_hihope/tree/master/rk3568/preinstall-config).
### Example ### Example
#### Configuration in **install_list_capability.json** #### Configuration in install_list_capability.json
``` ```json
{ {
"install_list": [ "install_list": [
{ {
"bundleName": "com.example.kikakeyboard", "bundleName": "com.example.kikakeyboard",
"singleton": true, // The application is installed for a single user. "singleton": true, // The application is installed for a single user.
"keepAlive": true, // The application is running in the background. "keepAlive": true, // The application can be running in the background.
"runningResourcesApply": true, // The application can apply for running resources such as the CPU, event notifications, and Bluetooth. "runningResourcesApply": true, // The application can apply for running resources such as the CPU, event notifications, and Bluetooth.
"associatedWakeUp": true, // The application in the FA model can be woken up by an associated application. "associatedWakeUp": true, // The application in the FA model can be woken up by an associated application.
"app_signature": ["8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC"], // The settings take effect only when the configured certificate fingerprint is the same as the HAP certificate fingerprint. "app_signature": ["****"], // The setting takes effect only when the configured certificate fingerprint is the same as the HAP certificate fingerprint.
"allowCommonEvent": ["usual.event.SCREEN_ON", "usual.event.THERMAL_LEVEL_CHANGED"] "allowCommonEvent": ["usual.event.SCREEN_ON", "usual.event.THERMAL_LEVEL_CHANGED"]
"allowAppDataNotCleared": true, // The application data cannot be deleted.
"allowAppMultiProcess": true, // Allow the application to run on multiple processes.
"allowAppDesktopIconHide": true, // Allow the application icon to be hidden from the home screen.
"allowAbilityPriorityQueried": true, // Allow the ability to configure the query priority.
"allowAbilityExcludeFromMissions": true, // Allow the ability to be hidden in the mission stack.
"allowAppUsePrivilegeExtension": true, // Allow the application to use ServiceExtension and DataExtension abilities.
"allowFormVisibleNotify": true // Allow a widget to be visible on the home screen.
}, },
} }
``` ```
**Obtaining the Certificate Fingerprint** **Obtaining the Certificate Fingerprint**
1. Create the **profile.cer** file, and copy the certificate content under the **distribution-certificate** field of the HarmonyAppProvision file to the **profile.cer** file. 1. Create the **profile.cer** file, and copy the certificate content under the **distribution-certificate** field of the [**HarmonyAppProvision** file](../../application-dev/security/app-provision-structure.md) to the **profile.cer** file.
Example:
``` ```json
{ {
... ...
"bundle-info": { "bundle-info": {
...@@ -102,12 +109,7 @@ Configure the required privileges in [configuration files](https://gitee.com/ope ...@@ -102,12 +109,7 @@ Configure the required privileges in [configuration files](https://gitee.com/ope
} }
``` ```
2. Apply line breaks in the **profile.cer** content and remove the newline characters. 2. Apply line breaks in the **profile.cer** content and remove the newline characters.
Example:
``` ```
-----BEGIN CERTIFICATE----- -----BEGIN CERTIFICATE-----
MIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO MIICMzCCAbegAwIBAgIEaOC/zDAMBggqhkjOPQQDAwUAMGMxCzAJBgNVBAYTAkNO
...@@ -125,30 +127,28 @@ Configure the required privileges in [configuration files](https://gitee.com/ope ...@@ -125,30 +127,28 @@ Configure the required privileges in [configuration files](https://gitee.com/ope
-----END CERTIFICATE----- -----END CERTIFICATE-----
``` ```
3. Use keytool to run the following command to obtain the certificate fingerprint.
3. Use keytool to print the certificate fingerprint. > **NOTE**<br>You can obtain keytool from the **\tools\openjdk\bin** directory after DevEco Studio is installed.
Example: ```shell
```
keytool -printcert -file profile.cer keytool -printcert -file profile.cer
result:
Issued To: CN=OpenHarmony Application Release, OU=OpenHarmony Team, O=OpenHarmony, C=CN
Issued By: CN=OpenHarmony Application CA, OU=OpenHarmony Team, O=OpenHarmony, C=CN
SN: 68e0bfcc
Valid From: Tue Feb 02 20:19:31 CST 2021, Valid To: Fri Dec 31 20:19:31 CST 2049
Fingerprints:
SHA1 fingerprint: E3:E8:7C:65:B8:1D:02:52:24:6A:06:A4:3C:4A:02:39:19:92:D1:F5
SHA256 fingerprint: 8E:93:86:3F:C3:2E:E2:38:06:0B:F6:9A:9B:37:E2:60:8F:FF:B2:1F:93:C8:62:DD:51:1C:BA:C9:F3:00:24:B5 // After the colons are removed, the fingerprint is 8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC9F30024B5.
...
```
# Example
# result:
# Issued To: CN=OpenHarmony Application Release, OU=OpenHarmony Team, O=OpenHarmony, C=CN
# Issued By: CN=OpenHarmony Application CA, OU=OpenHarmony Team, O=OpenHarmony, C=CN
# SN: 68e0bfcc
# Valid From: Tue Feb 02 20:19:31 CST 2021, Valid To: Fri Dec 31 20:19:31 CST 2049
# Fingerprints:
# SHA1 fingerprint: E3:E8:7C:65:B8:1D:02:52:24:6A:06:A4:3C:4A:02:39:19:92:D1:F5
# SHA256 fingerprint: 8E:93:86:3F:C3:2E:E2:38:06:0B:F6:9A:9B:37:E2:60:8F:FF:B2:1F:93:C8:62:DD:51:1C:BA:C9:F3:00:24:B5 // After the colons are removed, the fingerprint is 8E93863FC32EE238060BF69A9B37E2608FFFB21F93C862DD511CBAC9F30024B5.
# ...
```
#### Configuration in **install_list.json** #### Configuration in install_list.json
``` ```json
{ {
"install_list" : [ "install_list" : [
{ {
......
...@@ -14,21 +14,12 @@ The table below describes the APIs for creating and deleting an RDB store. ...@@ -14,21 +14,12 @@ The table below describes the APIs for creating and deleting an RDB store.
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStoreConfig | RdbStoreConfig(const std::string &path, <br> StorageMode storageMode = StorageMode::MODE_DISK, <br> bool readOnly = false, <br> const std::vector<uint8_t> &encryptKey = std::vector<uint8_t>(), <br> const std::string &journalMode = "", <br> const std::string &syncMode = "", <br> const std::string &databaseFileType = "", <br> const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the RDB store name, storage mode, log mode, synchronization mode, and read-only mode, and whether to encrypt the RDB store.<br/> - **path**: path of the RDB store. <br>- **readOnly**: whether the RDB store is read-only. <br>- **storageMode**: storage mode. <br>- **encryptKey**: key used to encrypt the RDB store. <br>- **journalMode**: logging mode. <br>- **syncMode**: data synchronization mode. <br>- **databaseFileType**: RDB store type. <br>- **databaseFileSecurityLevel**: security level of the RDB store.| | RdbStoreConfig | RdbStoreConfig(const std::string &path, <br> StorageMode storageMode = StorageMode::MODE_DISK, <br> bool readOnly = false, <br> const std::vector<uint8_t> &encryptKey = std::vector<uint8_t>(), <br> const std::string &journalMode = "", <br> const std::string &syncMode = "", <br> const std::string &databaseFileType = "", <br> const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the RDB store name, storage mode, log mode, synchronization mode, and read-only mode, and whether to encrypt the RDB store.<br/> - **path**: path of the RDB store. <br>- **readOnly**: whether the RDB store is read-only. <br>- **storageMode**: storage mode. <br>- **encryptKey**: key used to encrypt the RDB store. <br>- **journalMode**: logging mode. <br>- **syncMode**: data synchronization mode. <br>- **databaseFileType**: RDB store type. <br>- **databaseFileSecurityLevel**: security level of the RDB store.|
| RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | Called when an RDB store is created. You can add the method for initializing the table structure and initialization data used by your application in this callback.| | RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | Called when an RDB store is created. You can add the method for initializing the table structure and data used by your application in this callback. |
| RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is upgraded.| | RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is upgraded.|
| RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is downgraded.| | RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is downgraded.|
| RdbHelper | std::shared_ptr\<RdbStore\> GetRdbStore(const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) | Creates or obtains an RDB store.| | RdbHelper | std::shared_ptr\<RdbStore\> GetRdbStore(const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) | Creates or obtains an RDB store.|
| RdbHelper | int DeleteRdbStore(const std::string &path) | Deletes an RDB store.| | RdbHelper | int DeleteRdbStore(const std::string &path) | Deletes an RDB store.|
### Encrypting an RDB Store
When creating an RDB store, you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key.
**Table 2** API for changing the key
| Class| API| Description|
| ---- | ---- | ---- |
| RdbStore | int ChangeEncryptKey(const std::vector<uint8_t> &newKey) | Changes the encryption key for an RDB store. <br>Note that the encryption key can be changed only for an encrypted RDB store.|
### Using Predicates ### Using Predicates
The RDB store provides **AbsRdbPredicates** for you to set database operation conditions. The **AbsRdbPredicates** class has the following child classes: The RDB store provides **AbsRdbPredicates** for you to set database operation conditions. The **AbsRdbPredicates** class has the following child classes:
...@@ -36,7 +27,7 @@ The RDB store provides **AbsRdbPredicates** for you to set database operation co ...@@ -36,7 +27,7 @@ The RDB store provides **AbsRdbPredicates** for you to set database operation co
- **RdbPredicates**: allows you to combine SQL statements by simply calling methods in this class, such as **equalTo**, **notEqualTo**, **groupBy**, **orderByAsc**, and **beginsWith**. With this class, you do not need to write complex SQL statements. - **RdbPredicates**: allows you to combine SQL statements by simply calling methods in this class, such as **equalTo**, **notEqualTo**, **groupBy**, **orderByAsc**, and **beginsWith**. With this class, you do not need to write complex SQL statements.
- **RawRdbPredicates**: allows you to write complex SQL statements, such as setting **whereClause** and **whereArgs**. However, this class does not support APIs such as **equalTo**. - **RawRdbPredicates**: allows you to write complex SQL statements, such as setting **whereClause** and **whereArgs**. However, this class does not support APIs such as **equalTo**.
**Table 3** APIs for setting RDB predicates **Table 2** APIs for setting RDB predicates
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbPredicates | AbsPredicates *EqualTo(std::string field, std::string value) | Sets an **AbsPredicates** to match the field that is equal to the specified value.| | RdbPredicates | AbsPredicates *EqualTo(std::string field, std::string value) | Sets an **AbsPredicates** to match the field that is equal to the specified value.|
...@@ -50,6 +41,7 @@ The RDB store provides **AbsRdbPredicates** for you to set database operation co ...@@ -50,6 +41,7 @@ The RDB store provides **AbsRdbPredicates** for you to set database operation co
| RdbPredicates | AbsRdbPredicates *InAllDevices() | Sets an **AbsPredicates** to connect to all remote devices on the network when synchronizing distributed databases.| | RdbPredicates | AbsRdbPredicates *InAllDevices() | Sets an **AbsPredicates** to connect to all remote devices on the network when synchronizing distributed databases.|
### Managing Data in an RDB Store ### Managing Data in an RDB Store
You can use the APIs provided by the RDB to insert, delete, update, and query local data. You can use the APIs provided by the RDB to insert, delete, update, and query local data.
...@@ -58,7 +50,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo ...@@ -58,7 +50,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo
Call **int Insert()** to insert data through **ValuesBucket**. If data is inserted, the row number of the data inserted is returned; otherwise, **-1** is returned. Call **int Insert()** to insert data through **ValuesBucket**. If data is inserted, the row number of the data inserted is returned; otherwise, **-1** is returned.
**Table 4** API for inserting data **Table 3** API for inserting data
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
...@@ -68,7 +60,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo ...@@ -68,7 +60,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo
Call **delete()** to delete the data that meets the conditions specified by **AbsRdbPredicates**. If data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned. Call **delete()** to delete the data that meets the conditions specified by **AbsRdbPredicates**. If data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned.
**Table 5** API for deleting data **Table 4** API for deleting data
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.<br> - **deletedRows**: number of rows to delete.<br> - **predicates**: table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies query conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only. | | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.<br> - **deletedRows**: number of rows to delete.<br> - **predicates**: table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies query conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only. |
...@@ -77,7 +69,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo ...@@ -77,7 +69,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo
Call **update()** to update data based on the passed data and the conditions specified by **AbsRdbPredicates**. If data is updated, the row number of the updated data is returned; otherwise, **0** is returned. Call **update()** to update data based on the passed data and the conditions specified by **AbsRdbPredicates**. If data is updated, the row number of the updated data is returned; otherwise, **0** is returned.
**Table 6** API for updating data **Table 5** API for updating data
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates.<br> - **changedRows**: number of rows to update.<br> - **values**: new data stored in **ValuesBucket**.<br> - **predicates**: table name and conditions for the update operation. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only. | | RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates.<br> - **changedRows**: number of rows to update.<br> - **values**: new data stored in **ValuesBucket**.<br> - **predicates**: table name and conditions for the update operation. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only. |
...@@ -89,7 +81,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo ...@@ -89,7 +81,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo
- Call the **query()** method to query data based on the predicates, without passing any SQL statement. - Call the **query()** method to query data based on the predicates, without passing any SQL statement.
- Run the native SQL statement. - Run the native SQL statement.
**Table 7** APIs for querying data **Table 6** APIs for querying data
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | std::unique_ptr<AbsSharedResultSet> Query(const AbsRdbPredicates &predicates, const std::vector\<std::string\> columns) | Queries data.<br> - **predicates**: query conditions. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies query conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only.<br> - **columns**: number of columns returned. | | RdbStore | std::unique_ptr<AbsSharedResultSet> Query(const AbsRdbPredicates &predicates, const std::vector\<std::string\> columns) | Queries data.<br> - **predicates**: query conditions. **AbsRdbPredicates** has the following classes:<br> - **RdbPredicates**: specifies query conditions by calling its methods, such as **equalTo**.<br> - **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only.<br> - **columns**: number of columns returned. |
...@@ -99,7 +91,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo ...@@ -99,7 +91,7 @@ You can use the APIs provided by the RDB to insert, delete, update, and query lo
You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. The table below describes the APIs of **ResultSet**. You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result. The table below describes the APIs of **ResultSet**.
**Table 8** APIs of **ResultSet** **Table 7** APIs of **ResultSet**
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| ResultSet | int GoTo(int offset) | Moves forwards or backwards by the specified offset relative to its current position.| | ResultSet | int GoTo(int offset) | Moves forwards or backwards by the specified offset relative to its current position.|
...@@ -120,7 +112,7 @@ You can use the APIs provided by **ResultSet** to traverse and access the data y ...@@ -120,7 +112,7 @@ You can use the APIs provided by **ResultSet** to traverse and access the data y
Call **bool SetDistributedTables()** to set distributed tables for data operations across devices. Call **bool SetDistributedTables()** to set distributed tables for data operations across devices.
**Table 9** API for setting distributed tables **Table 8** API for setting distributed tables
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | bool SetDistributedTables(const std::vector<std::string>& tables) | Sets distributed tables.<br> **tables**: names of the distributed tables to set. | | RdbStore | bool SetDistributedTables(const std::vector<std::string>& tables) | Sets distributed tables.<br> **tables**: names of the distributed tables to set. |
...@@ -129,28 +121,28 @@ Call **bool SetDistributedTables()** to set distributed tables for data operatio ...@@ -129,28 +121,28 @@ Call **bool SetDistributedTables()** to set distributed tables for data operatio
You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device.<br> You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device.<br>
**Table 10** API for obtaining the distributed table name of a remote device **Table 9** API for obtaining the distributed table name of a remote device
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | std::string ObtainDistributedTableName(const std::string& device, const std::string& table) | Obtains the distributed table name of a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device.<br> - **device**: ID of the remote device. <br>- **table**: name of the local table.| | RdbStore | std::string ObtainDistributedTableName(const std::string& device, const std::string& table) | Obtains the distributed table name of a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device.<br> - **device**: ID of the remote device. <br>- **table**: name of the local table.|
### Synchronizing Data Between Devices ### Synchronizing Data Between Devices
**Table 11** API for synchronizing data between devices **Table 10** API for synchronizing data between devices
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) | Synchronizes data between devices. <br/>- **option**: synchronization options, which include **mode** and **isBlock**. **mode** specifies how data is synchronized. The value **push** means to push data from the local device to the remote device; the value **pull** means to pull data from the remote device to the local device. **isBlock** specifies whether the invocation of this function is blocked. <br>- **callback**: callback used to return the result. | | RdbStore | bool Sync(const SyncOption& option, const AbsRdbPredicates& predicate, const SyncCallback& callback) | Synchronizes data between devices. <br/>- **option**: synchronization options, which include **mode** and **isBlock**. **mode** specifies how data is synchronized. The value **push** means to push data from the local device to the remote device; the value **pull** means to pull data from the remote device to the local device. **isBlock** specifies whether the invocation of this function is blocked. <br>- **callback**: callback used to return the result. |
### Registering an RDB Store Observer ### Registering an RDB Store Observer
**Table 12** API for registering an observer **Table 11** API for registering an observer
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Registers an observer for this RDB store to listen for distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes. <br/>- **option**: subscription type.<br>- **observer**: observer that listens for data changes in the RDB store. | | RdbStore | bool Subscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Registers an observer for this RDB store to listen for distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes. <br/>- **option**: subscription type.<br>- **observer**: observer that listens for data changes in the RDB store. |
### Unregistering an RDB Store Observer ### Unregistering an RDB Store Observer
**Table 13** API for unregistering an observer **Table 12** API for unregistering an observer
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Unregisters the observer of the specified type. <br/>- **option**: subscription type to unregister.<br>- **observer**: observer to unregister. | | RdbStore | bool UnSubscribe(const SubscribeOption& option, RdbStoreObserver *observer) | Unregisters the observer of the specified type. <br/>- **option**: subscription type to unregister.<br>- **observer**: observer to unregister. |
...@@ -163,7 +155,7 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab ...@@ -163,7 +155,7 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab
Call **int Backup()** to back up the current database file. **databasePath** specifies the name or path of the backup file to be generated. If the backup is successful, **0** is returned; otherwise, an error code is returned. Call **int Backup()** to back up the current database file. **databasePath** specifies the name or path of the backup file to be generated. If the backup is successful, **0** is returned; otherwise, an error code is returned.
Table 14 API for backing up an RDB store **Table 13** API for backing up an RDB store
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
...@@ -173,7 +165,7 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab ...@@ -173,7 +165,7 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab
Call **int Restore()** to restore an RDB from the backup file. **backupPath** specifies the name or path of the backup file. If the restore is successful, **0** is returned; otherwise, an error code is returned. Call **int Restore()** to restore an RDB from the backup file. **backupPath** specifies the name or path of the backup file. If the restore is successful, **0** is returned; otherwise, an error code is returned.
Table 15 API for restoring an RDB store **Table 14** API for restoring an RDB store
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
...@@ -181,15 +173,15 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab ...@@ -181,15 +173,15 @@ You can use the APIs provided by **rdbStore** to back up and restore local datab
### Transaction ### Transaction
A transaction is a unit of work performed in a database. If a transaction is successful, **0** is returned. Otherwise, an error code is returned. A transaction is a unit of work performed in a database. If a transaction is successful, **0** is returned. Otherwise, an error code is returned.
Table 16 Transaction APIs **Table 15** Transaction APIs
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | int BeginTransaction() | Starts a transaction.| | RdbStore | int BeginTransaction() | Starts a transaction.|
| RdbStore | int Commit() | Commits the changes.| | RdbStore | int Commit() | Commits the changes.|
| RdbStore | int RollBack() | Rolls back the changes.| | RdbStore | int RollBack() | Rolls back the changes.|
## Constraints ## Constraints
...@@ -338,7 +330,7 @@ None. ...@@ -338,7 +330,7 @@ None.
```c++ ```c++
std::string tableName = store->ObtainDistributedTableName("123456789abcd", "test"); std::string tableName = store->ObtainDistributedTableName("123456789abcd", "test");
auto resultSet = store->QuerySql("SELECT * from ?;", tableName); auto resultSet = store->QuerySql("SELECT * from ?;", tableName);
``` ```
8. Back up and restore an RDB store. 8. Back up and restore an RDB store.
...@@ -352,4 +344,4 @@ None. ...@@ -352,4 +344,4 @@ None.
std::vector<uint8_t> key; // Key used to encrypt the RDB store. std::vector<uint8_t> key; // Key used to encrypt the RDB store.
int errno = store->Backup(backupName, key); int errno = store->Backup(backupName, key);
errno = store->Restore(backupName, key); errno = store->Restore(backupName, key);
``` ```
...@@ -4,45 +4,45 @@ ...@@ -4,45 +4,45 @@
The user identity and access management (IAM) subsystem provides a unified framework for user credential management and user identity authentication in OpenHarmony. It allows multiple users to set their own authentication credential information and authenticates their identities based on the information set. The user identity and access management (IAM) subsystem provides a unified framework for user credential management and user identity authentication in OpenHarmony. It allows multiple users to set their own authentication credential information and authenticates their identities based on the information set.
This subsystem is widely used in security-sensitive scenarios such as screen lock. It also provides APIs for developers to call the identity authentication capabilities to control user access. This subsystem is widely used in security-sensitive scenarios such as screen lock and payment. In addition, the user IAM subsystem provides APIs for third-party applications to control user access.
**Figure 1** Subsystem architecture **Figure 1** Architecture
![](figures/User-IAM-subsystem-architecture.png) ![](figures/User-IAM-subsystem-architecture.png)
The user IAM subsystem consists of the unified user authentication framework and authentication executor. The unified user authentication framework consists of the following parts:
- Unified user authentication: provides unified user identity authentication externally and provides open biometric authentication capabilities for third-party applications to invoke. The user IAM subsystem consists of the unified user authentication framework and authentication executor. The unified user authentication framework consists of the following:
- User credential management: provides a unified user credential information management interface for the upper layer and invokes authentication resources in the system through the authentication executor management part to implement lifecycle management and secure storage of user credentials.
- Unified user authentication: provides unified user identity authentication externally and open biometric authentication capabilities for third-party applications to invoke.
- User credential management: provides a unified user credential information management interface for the upper layer and invokes authentication resources in the system through the authentication executor to implement lifecycle management and secure storage of user credentials.
- Authentication executor management: provides authentication resource management and authentication session management, and supports unified management, scheduling, and connection of various authentication executors in the system. - Authentication executor management: provides authentication resource management and authentication session management, and supports unified management, scheduling, and connection of various authentication executors in the system.
Based on the unified user authentication framework, the system can be extended to support multiple authentication capabilities. Currently, the authentication executors supported by OpenHarmony are password and facial authentication. To implement a new authentication executor, you only need to implement authentication capabilities in a new part and connect the new part to the unified user authentication framework based on the interfaces defined by the authentication executor management part. Based on the unified user authentication framework, the system supports multiple authentication capabilities. Currently, OpenHarmony supports PIN and facial authentication executors. To implement a new authentication executor, you only need to implement authentication capabilities in a new component and connect the new component to the unified user authentication framework based on the APIs defined by the authentication executor management component.
> **NOTE** > **NOTE**
> >
>In the user IAM subsystem, an authentication executor is the minimum execution unit of a user identity authentication operation. For example, a password authentication module is responsible for password collection, password processing and comparison, and secure storage, and therefore it can be abstracted as a password authentication executor. >In the user IAM subsystem, an authentication executor is the minimum execution unit of a user identity authentication operation. For example, a PIN authentication module is responsible for PIN collection, processing, comparison, and secure storage, and therefore it can be abstracted as a PIN authentication executor.
## Directory Structure ## Directory Structure
```undefined ```undefined
//base/user_iam //base/useriam
├── user_auth_framework # User authentication framework, including user authentication, credential management, and executor management ├── user_auth_framework # User authentication framework, including user authentication, credential management, and executor management.
├── face_auth # Facial authentication module, which connects to the authentication executor management part and supports facial information recording, deletion, and verification ├── face_auth # Facial authentication component, which interacts with the authentication executor to implement facial information enrollment, deletion, and authentication.
├── pin_auth # Password authentication module, which connects to the authentication executor management part and supports password recording, deletion, and verification ├── pin_auth # PIN authentication component, which interacts with the authentication executor to implement PIN enrollment, deletion, and authentication.
``` ```
## Constraints ## Constraints
- User credential management is a key operation in the system, and the interfaces used for user credential management can be invoked only by basic system applications. - User credential management involves critical operations in the system, and the related APIs can be called only by basic system applications.
- The authentication executors process user authentication credentials, and their capabilities can only be implemented by system services for interconnection with the authentication executor management part. - The authentication executors process user authentication credentials. Therefore, only system services can interact with the authentication executor management module to implement the executor functions.
## Usage ## Usage
### How to Use ### How to Use
1. The unified user authentication framework must work with an authentication executor. - The unified user authentication framework must work with an authentication executor.
2. The first default authentication executor in the system must be a password authentication executor. - By default, the first authentication executor in the system is the PIN authentication executor.
## Repositories Involved ## Repositories Involved
...@@ -54,4 +54,4 @@ Based on the unified user authentication framework, the system can be extended t ...@@ -54,4 +54,4 @@ Based on the unified user authentication framework, the system can be extended t
[drivers_interface](https://gitee.com/openharmony/drivers_interface) [drivers_interface](https://gitee.com/openharmony/drivers_interface)
[drivers_peripheral](https://gitee.com/openharmony/drivers_peripheral) [drivers_peripheral](https://gitee.com/openharmony/drivers_peripheral)
\ No newline at end of file
# OpenHarmony 3.1.5 Release
## Version Description
OpenHarmony 3.1.5 Release provides enhanced system security over OpenHarmony 3.1.4 Release by rectifying memory leak issues, certain known vulnerabilities in open-source components such as Linux kernel, and system stability issues. It also provides new SDK versions and resolves previewer issues.
## Version Mapping
**Table 1** Version mapping of software and tools
| Software/Tool| Version| Remarks|
| -------- | -------- | -------- |
| OpenHarmony | 3.1.5 Release| NA |
| Full SDK | Ohos_sdk_full 3.1.11.5 (API Version 8 Release)| This toolkit is intended for original equipment manufacturers (OEMs) and contains system APIs that require system permissions.<br>To use the Full SDK, you must manually obtain it from the mirror and switch to it in DevEco Studio. For details, see [Guide to Switching to Full SDK](../application-dev/quick-start/full-sdk-switch-guide.md).|
| Public SDK | Ohos_sdk_public 3.1.11.5 (API Version 8 Release)| This toolkit is intended for application developers and does not contain system APIs that require system permissions.<br>It is provided as standard in DevEco Studio 3.0 Beta4 or later.|
| (Optional) HUAWEI DevEco Studio| 3.1 Preview for OpenHarmony| Recommended for developing OpenHarmony applications|
| (Optional) HUAWEI DevEco Device Tool| 3.0 Release| Recommended for developing OpenHarmony smart devices|
## Source Code Acquisition
### Prerequisites
1. Register your account with Gitee.
2. Register an SSH public key for access to Gitee.
3. Install the [git client](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) and [git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading), and configure user information.
```
git config --global user.name "yourname"
git config --global user.email "your-email-address"
git config --global credential.helper store
```
4. Run the following commands to install the **repo** tool:
```
curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo # If you do not have the permission, download the tool to another directory and configure it as an environment variable by running the chmod a+x /usr/local/bin/repo command.
pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests
```
### Acquiring Source Code Using the repo Tool
**Method 1 (recommended)**
Use the **repo** tool to download the source code over SSH. (You must have an SSH public key for access to Gitee.)
```
repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.5-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
**Method 2**
Use the **repo** tool to download the source code over HTTPS.
```
repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.5-Release --no-repo-verify
repo sync -c
repo forall -c 'git lfs pull'
```
### Acquiring Source Code from Mirrors
**Table 2** Mirrors for acquiring source code
| Source Code| Version| Mirror| SHA-256 Checksum|
| -------- | -------- | -------- | -------- |
| Full code base (for mini, small, and standard systems)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz)| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/OpenHarmony-v3.1.5-Release.tar.gz.sha256) |
| Hi3516 standard system solution (binary)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_hi3516.tar.gz.sha256)|
| RK3568 standard system solution (binary)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/standard_rk3568.tar.gz.sha256)|
| Hi3861 mini system solution (binary)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz)| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_pegasus.tar.gz.sha256) |
| Hi3516 small system solution - LiteOS (binary)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus.tar.gz.sha256) |
| Hi3516 small system solution - Linux (binary)| 3.1.5 Release| [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/hispark_taurus_linux.tar.gz.sha256) |
| Full SDK package for the standard system (macOS)| 3.1.11.4 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-full.tar.gz.sha256) |
| Full SDK package for the standard system (Windows/Linux)| 3.1.11.4 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-full.tar.gz.sha256) |
| Public SDK package for the standard system (macOS)| 3.1.11.4 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-mac-public.tar.gz.sha256) |
| Public SDK package for the standard system (Windows/Linux)| 3.1.11.4 | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz) | [Download](https://mirrors.huaweicloud.com/openharmony/os/3.1.5/ohos-sdk-public.tar.gz.sha256) |
## Change History
This version has the following updates to OpenHarmony 3.1.4 Release.
### Feature Update
This version does not involve feature updates.
### API Updates
This version does not involve API updates.
### Chip and Development Board Adaptation
For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md).
### Resolved Issues
**Table 3** Resolved issues
| Subsystem | Description |
| -------------- | ------------------------------------------------------------ |
| SDK subsystem | Certain issues related to the previewer. |
| Network management subsystem| The exception stack libconnection.z.so occurs in thread 1.ui of the com.ohos.netmanagersocket process. ([I5IXWZ](https://gitee.com/openharmony/communication_netmanager_base/issues/I5IXWZ))|
| Misc subsystem | There is a possibility that the **complete** event is not reported when **request.download** is called. ([I5WZC6](https://gitee.com/openharmony/request_request/issues/I5WZC6))|
| DFX subsystem | There is a low probability that cpp_crash occurs in hdcd. ([I65P94](https://gitee.com/openharmony/developtools_hdc/issues/I65P94))|
| ArkUI development framework | The universal attributes of the focusable component are abnormal. ([I64YLA](https://gitee.com/openharmony/arkui_ace_engine/issues/I64YLA))|
### Fixed Security Vulnerabilities
**Table 4** Fixed security vulnerabilities
| Issue No.| Description| PR Link|
| -------- | -------- | -------- |
| I5UHSG | Security vulnerability of the das u-boot component: CVE-2022-2347| [PR](https://gitee.com/openharmony/third_party_u-boot/pulls/62) |
| I5UI3F/I5VGDV | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-3303, CVE-2022-42703, CVE-2022-20422, CVE-2022-41222, CVE-2022-3239, CVE-2022-20423 and CVE-2022-41850 | [PR](https://gitee.com/openharmony/third_party_expat/pulls/23) |
| I5XU3W | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-3586, CVE-2022-3625, CVE-2022-42432, CVE-2022-3633, CVE-2022-3635, CVE-2022-3629, CVE-2022-3623, CVE-2022-3646, CVE-2022-3621, CVE-2022-3567, CVE-2022-43750, CVE-2022-3545, CVE-2022-2978, CVE-2022-3523, CVE-2022-2602, and CVE-2022-3628| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/541) |
| I5XUCJ | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-40768, CVE-2022-3577, CVE-2022-20409, CVE-2022-3566, CVE-2022-3606, CVE-2022-3564 and CVE-2022-3649| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/505) |
| I5VGIU | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3169| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/553) |
| I63VFW | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-41858| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/569) |
| I63VG7 | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-45934, CVE-2022-4129, CVE-2022-4378, CVE-2022-3108, CVE-2022-47518, CVE-2022-47521, CVE-2022-47519, and CVE-2022-47520| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/586) |
| I66ZCI | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-3105, CVE-2022-3104, CVE-2022-3115, CVE-2022-3113, and CVE-2022-3112 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/579) |
| I66ZHX | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3111| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/584) |
| I66ZKM | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-3107| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/590) |
| I65T2H | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-20566| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/582) |
| I61HGX | Security vulnerabilities of the kernel_linux_5.10 component: CVE-2022-42895 and CVE-2022-42896| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/545) |
| I652LY | Security vulnerability of the kernel_linux_5.10 component: CVE-2022-4139| [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/567) |
| I65R2K | Security vulnerability of the python component: CVE-2022-42919| [PR](https://gitee.com/openharmony/third_party_python/pulls/36) |
| I65R59 | Security vulnerability of the python component: CVE-2022-45061| [PR](https://gitee.com/openharmony/third_party_python/pulls/37) |
| I65UJ8 | Security vulnerability of the python component: CVE-2022-45061| [PR](https://gitee.com/openharmony/third_party_python/pulls/35) |
| I60GOT | Security vulnerability of the pixman component: CVE-2022-37454| [PR](https://gitee.com/openharmony/third_party_pixman/pulls/11) |
| I5Z39U | Security vulnerabilities of the curl component: CVE-2022-32221, CVE-2022-42915, and CVE-2022-42916| [PR](https://gitee.com/openharmony/third_party_curl/pulls/91) |
| I61I8F | Security vulnerability of the ntfs-3g component: CVE-2022-40284| [PR](https://gitee.com/openharmony/third_party_ntfs-3g/pulls/33) |
| I63V9Z | Security vulnerabilities of the libxml2 component: CVE-2022-40303 and CVE-2022-40304| [PR](https://gitee.com/openharmony/third_party_libxml2/pulls/31) |
# 应用程序包安装和卸载流程 # 应用程序包安装和卸载流程
## 开发者
开发者可以通过调试命令进行应用的安装和卸载,可参考[多HAP的调试流程](multi-hap-release-deployment.md#调试)
OpenHarmony包管理服务模块对外提供安装、更新和卸载应用的功能,开发者可以调用包管理服务的安装和卸载接口来实现应用的安装、更新和卸载。开发者将应用上架应用市场后,用户可以在端侧设备上进行应用的安装和卸载。 **图1** 应用程序包安装和卸载流程(开发者)  
![hap-intall-uninstall](figures/hap-install-uninstall-developer.png)
## 终端设备用户
开发者将应用上架应用市场后,终端设备用户可以在终端设备上使用应用市场进行应用的安装和卸载。
**图2** 应用程序包安装和卸载流程(终端设备用户)
![hap-intall-uninstall](figures/hap-install-uninstall-user.png)
**图1** 应用程序包安装和卸载流程  
![hap-intall-uninstall](figures/hap-intall-uninstall.png)
...@@ -87,8 +87,8 @@ struct bindPopupPage { ...@@ -87,8 +87,8 @@ struct bindPopupPage {
2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
类型定义中的Length、Resource、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。 类型定义中的Length、ResourceStr、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、Resource、ResourceColor的定义请看文档[arkui-ts类型定义](../../application-dev/reference/arkui-ts/ts-types.md)。 Length、ResourceStr、ResourceColor的定义请看文档[arkui-ts类型定义](../../application-dev/reference/arkui-ts/ts-types.md)。
示例: 示例:
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **说明:** > **说明:**
> >
> - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> - 本模块接口从API9开始废弃。不建议使用以下接口,调用以下接口将抛出异常。 > - 本模块接口从API version 9开始废弃。不建议使用以下接口,调用以下接口将抛出异常。
## 导入模块 ## 导入模块
......
...@@ -627,7 +627,7 @@ mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string& ...@@ -627,7 +627,7 @@ mkDir(parentUri: string, displayName: string, callback: AsyncCallback&lt;string&
openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt; openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
以异步方法打开文件,返回文件句柄。使用Promise异步回调。 以异步方法打开文件,返回文件描述符。使用Promise异步回调。
**系统能力**:SystemCapability.FileManagement.UserFileService。 **系统能力**:SystemCapability.FileManagement.UserFileService。
...@@ -644,7 +644,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt; ...@@ -644,7 +644,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
| 类型 | 说明 | | 类型 | 说明 |
| --- | -- | | --- | -- |
| Promise&lt;number&gt; | 文件句柄 | | Promise&lt;number&gt; | 文件描述符 |
**示例:** **示例:**
...@@ -665,7 +665,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt; ...@@ -665,7 +665,7 @@ openFile(uri: string, flags: OPENFLAGS) : Promise&lt;number&gt;
openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void; openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : void;
以异步方法打开文件,返回文件句柄。使用callback异步回调。 以异步方法打开文件,返回文件描述符。使用callback异步回调。
**系统能力**:SystemCapability.FileManagement.UserFileService。 **系统能力**:SystemCapability.FileManagement.UserFileService。
...@@ -677,7 +677,7 @@ openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) : ...@@ -677,7 +677,7 @@ openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback&lt;number&gt;) :
| --- | --- | --- | -- | | --- | --- | --- | -- |
| uri | string | 是 | 待打开文件的uri | | uri | string | 是 | 待打开文件的uri |
| flags | [OPENFLAGS](#openflags) | 是 | 文件打开的标志 | | flags | [OPENFLAGS](#openflags) | 是 | 文件打开的标志 |
| callback | AsyncCallback&lt;number&gt; | 是 | 文件句柄 | | callback | AsyncCallback&lt;number&gt; | 是 | 文件描述符 |
**示例:** **示例:**
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
该模块提供文件存储管理能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。 该模块提供文件存储管理能力,包括文件基本管理、文件目录管理、文件信息统计、文件流式读写等常用功能。
> **说明:** > **说明:**
> 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 6开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块自API 9开始废弃,建议使用[@ohos.file.fs](./js-apis-file-fs.md)替代。 > - 本模块从API version 9开始废弃,建议使用[@ohos.file.fs](js-apis-file-fs.md)替代。
## 导入模块 ## 导入模块
......
...@@ -22,7 +22,7 @@ Context模块提供了ability或application的上下文的能力,包括访问 ...@@ -22,7 +22,7 @@ Context模块提供了ability或application的上下文的能力,包括访问
| preferencesDir | string | 是 | 否 | preferences目录。 | | preferencesDir | string | 是 | 否 | preferences目录。 |
| bundleCodeDir | string | 是 | 否 | 安装包目录。 | | bundleCodeDir | string | 是 | 否 | 安装包目录。 |
| distributedFilesDir | string | 是 | 否 | 分布式文件目录。 | | distributedFilesDir | string | 是 | 否 | 分布式文件目录。 |
| eventHub | string | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 | | eventHub | [EventHub](js-apis-inner-application-eventHub.md) | 是 | 否 | 事件中心,提供订阅、取消订阅、触发事件对象。 |
| area | [AreaMode](#areamode) | 是 | 否 | 文件分区信息。 | | area | [AreaMode](#areamode) | 是 | 否 | 文件分区信息。 |
## Context.createBundleContext ## Context.createBundleContext
......
...@@ -1351,8 +1351,6 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; ...@@ -1351,8 +1351,6 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
**参数:** **参数:**
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
......
...@@ -1195,7 +1195,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void ...@@ -1195,7 +1195,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ----------------------------------- | | -------- | --------------------------- | ---- | ----------------------------------- |
| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | | mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) |
| callback | AsyncCallback&lt;number&gt; | 是 | 回调返回文件句柄 | | callback | AsyncCallback&lt;number&gt; | 是 | 回调返回文件描述符 |
**示例:** **示例:**
...@@ -1237,7 +1237,7 @@ open(mode: string): Promise&lt;number&gt; ...@@ -1237,7 +1237,7 @@ open(mode: string): Promise&lt;number&gt;
| 类型 | 说明 | | 类型 | 说明 |
| --------------------- | ------------- | | --------------------- | ------------- |
| Promise&lt;number&gt; | Promise返回文件句柄 | | Promise&lt;number&gt; | Promise返回文件描述符 |
**示例:** **示例:**
......
...@@ -742,6 +742,7 @@ router.replace({ ...@@ -742,6 +742,7 @@ router.replace({
}); });
``` ```
<<<<<<< HEAD
<<<<<<< HEAD <<<<<<< HEAD
======= =======
## router.replace<sup>(deprecated)</sup> ## router.replace<sup>(deprecated)</sup>
...@@ -773,6 +774,8 @@ router.replace({ ...@@ -773,6 +774,8 @@ router.replace({
``` ```
>>>>>>> ccc442cafb6fdfbbc989e4614e23fb9d48f34cc6 >>>>>>> ccc442cafb6fdfbbc989e4614e23fb9d48f34cc6
=======
>>>>>>> b7ff5e905cd94af1b1d8c5d384704079dba71c6d
## router.enableAlertBeforeBackPage<sup>(deprecated)</sup> ## router.enableAlertBeforeBackPage<sup>(deprecated)</sup>
enableAlertBeforeBackPage(options: EnableAlertOptions): void enableAlertBeforeBackPage(options: EnableAlertOptions): void
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
该模块提供文件系统相关存储信息的功能,向应用程序提供获取文件系统总字节数、空闲字节数的JS接口。 该模块提供文件系统相关存储信息的功能,向应用程序提供获取文件系统总字节数、空闲字节数的JS接口。
> **说明:** > **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > - 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
> 本模块自API 9开始废弃,建议使用[@ohos.file.statvfs](./js-apis-file-statvfs.md)替代。 > - 本模块从API version 9开始废弃,建议使用[@ohos.file.statvfs](js-apis-file-statvfs.md)替代。
## 导入模块 ## 导入模块
......
...@@ -1100,7 +1100,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void ...@@ -1100,7 +1100,7 @@ open(mode: string, callback: AsyncCallback&lt;number&gt;): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | --------------------------- | ---- | ----------------------------------- | | -------- | --------------------------- | ---- | ----------------------------------- |
| mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) | | mode | string | 是 | 打开文件方式,如:'r'(只读), 'w'(只写), 'rw'(读写) |
| callback | AsyncCallback&lt;number&gt; | 是 | 回调返回文件句柄 | | callback | AsyncCallback&lt;number&gt; | 是 | 回调返回文件描述符 |
**示例:** **示例:**
...@@ -1142,7 +1142,7 @@ open(mode: string): Promise&lt;number&gt; ...@@ -1142,7 +1142,7 @@ open(mode: string): Promise&lt;number&gt;
| 类型 | 说明 | | 类型 | 说明 |
| --------------------- | ------------- | | --------------------- | ------------- |
| Promise&lt;number&gt; | Promise返回文件句柄 | | Promise&lt;number&gt; | Promise返回文件描述符 |
**示例:** **示例:**
......
...@@ -64,7 +64,7 @@ struct ScrollBarExample { ...@@ -64,7 +64,7 @@ struct ScrollBarExample {
.margin({ top: 5 }) .margin({ top: 5 })
} }
}, item => item) }, item => item)
}.margin({ left: 52 }) }.margin({ right: 52 })
} }
.scrollBar(BarState.Off) .scrollBar(BarState.Off)
.scrollable(ScrollDirection.Vertical) .scrollable(ScrollDirection.Vertical)
......
...@@ -4,13 +4,15 @@ ...@@ -4,13 +4,15 @@
下方将展示如何在单板上运行第一个应用程序,其中包括新建应用程序、编译、烧写、运行等步骤,最终输出“Hello World!”。 下方将展示如何在单板上运行第一个应用程序,其中包括新建应用程序、编译、烧写、运行等步骤,最终输出“Hello World!”。
## 示例目录 ## 示例目录
拉取openharmony项目代码,在代码根目录创建sample子系统文件夹,在子系统目录下创建hello部件文件夹,hello文件夹中创建hello源码目录,构建文件BUILD.gn及部件配置文件bundle.json。
示例完整目录如下。 示例完整目录如下。
``` ```
applications/sample/hello sample/hello
│── BUILD.gn │── BUILD.gn
│── include │── include
│ └── helloworld.h │ └── helloworld.h
...@@ -31,7 +33,7 @@ vendor/hihope ...@@ -31,7 +33,7 @@ vendor/hihope
1. 创建目录,编写业务代码。 1. 创建目录,编写业务代码。
新建applications/sample/hello/src/helloworld.c目录及文件,代码如下所示,用户可以自定义修改打印内容(例如:修改World为OHOS)。其中helloworld.h包含字符串打印函数HelloPrint的声明。当前应用程序可支持标准C及C++的代码开发。 新建sample/hello/src/helloworld.c目录及文件,代码如下所示,用户可以自定义修改打印内容(例如:修改World为OHOS)。其中helloworld.h包含字符串打印函数HelloPrint的声明。当前应用程序可支持标准C及C++的代码开发。
``` ```
...@@ -52,7 +54,7 @@ vendor/hihope ...@@ -52,7 +54,7 @@ vendor/hihope
} }
``` ```
再添加头文件applications/sample/hello/include/helloworld.h,代码如下所示。 再添加头文件sample/hello/include/helloworld.h,代码如下所示。
``` ```
...@@ -75,85 +77,115 @@ vendor/hihope ...@@ -75,85 +77,115 @@ vendor/hihope
``` ```
2. 新建编译组织文件。 2. 新建编译组织文件。
1. 新建applications/sample/hello/BUILD.gn文件,内容如下所示:
新建sample/hello/BUILD.gn,创建方法可参考:[模块配置规则](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-build-module.md)
创建
BUILD.gn内容如下所示:
``` ```
import("//build/ohos.gni") # 导入编译模板 import("//build/ohos.gni") # 导入编译模板
ohos_executable("helloworld") { # 可执行模块 ohos_executable("helloworld") { # 可执行模块
sources = [ # 模块源码 sources = [ # 模块源码
"src/helloworld.c" "src/helloworld.c"
] ]
include_dirs = [ # 模块依赖头文件目录 include_dirs = [ # 模块依赖头文件目录
"include" "include"
] ]
cflags = [] cflags = []
cflags_c = [] cflags_c = []
cflags_cc = [] cflags_cc = []
ldflags = [] ldflags = []
configs = [] configs = []
deps =[] # 部件内部依赖 deps =[] # 部件内部依赖
part_name = "hello" # 所属部件名称,必选 part_name = "hello" # 所属部件名称,必选
install_enable = true # 是否默认安装(缺省默认不安装),可选 install_enable = true # 是否默认安装(缺省默认不安装),可选
} }
``` ```
2. 新建applications/sample/hello/bundle.json文件,添加sample部件描述,内容如下所示。
3. 新建部件配置规则文件
新建sample/hello/bundle.json文件,添加sample部件描述,创建方法可参考:[部件配置规则](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-build-component.md)
bundle.json内容如下所示。
``` ```
{ {
"name": "@ohos/hello", "name": "@ohos/hello",
"description": "Hello world example.", "description": "Hello world example.",
"version": "3.1", "version": "3.1",
"license": "Apache License 2.0", "license": "Apache License 2.0",
"publishAs": "code-segment", "publishAs": "code-segment",
"segment": { "segment": {
"destPath": "applications/sample/hello" "destPath": "sample/hello"
},
"dirs": {},
"scripts": {},
"component": {
"name": "hello",
"subsystem": "sample",
"syscap": [],
"features": [],
"adapted_system_type": [ "mini", "small", "standard" ],
"rom": "10KB",
"ram": "10KB",
"deps": {
"components": [],
"third_party": []
}, },
"dirs": {}, "build": {
"scripts": {}, "sub_component": [
"component": { "//sample/hello:helloworld"
"name": "hello", ],
"subsystem": "sample", "inner_kits": [],
"syscap": [], "test": []
"features": [],
"adapted_system_type": [ "mini", "small", "standard" ],
"rom": "10KB",
"ram": "10KB",
"deps": {
"components": [],
"third_party": []
},
"build": {
"sub_component": [
"//applications/sample/hello:helloworld"
],
"inner_kits": [],
"test": []
}
} }
} }
``` }
```
bundle.json文件包含两个部分,第一部分描述该部件所属子系统的信息,第二部分component则定义该部件构建相关配置。添加的时候需要指明该部件包含的模块sub_component,假如有提供给其它部件的接口,需要在inner_kits中说明,假如有测试用例,需要在test中说明,inner_kits与test没有也可以不添加。 bundle.json文件包含两个部分,第一部分描述该部件所属子系统的信息,第二部分component则定义该部件构建相关配置。添加的时候需要指明该部件包含的模块sub_component,假如有提供给其它部件的接口,需要在inner_kits中说明,假如有测试用例,需要在test中说明,inner_kits与test没有也可以不添加。
3. 修改子系统配置文件。 4. 修改子系统配置文件。
在build/subsystem_config.json中添加新建的子系统的配置。 在build/subsystem_config.json中添加新建的子系统的配置。修改方法可参考:[子系统配置规则](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-build-subsystem.md)
新增子系统的配置如下所示。
``` ```
"sample": { "sample": {
"path": "applications/sample/hello", "path": "sample",
"name": "sample" "name": "sample"
}, },
``` ```
4. 修改产品配置文件。 5. 修改产品配置文件。
在vendor/hihope/rk3568/config.json中添加对应的hello部件,直接添加到原有部件后即可。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> OpenHarmony-v3.2-Beta2之前版本,RK3568的产品配置文件为productdefine/common/products/rk3568.json;从OpenHarmony-v3.2-Beta2版本开始,RK3568的产品配置文件为vendor/hihope/rk3568/config.json。
```
"usb:usb_manager_native":{}, - 3.2-Beta2之前版本
"applications:prebuilt_hap":{},
"sample:hello":{}, 在productdefine/common/products/rk3568.json中添加对应的hello部件,直接添加到原有部件后即可。
"wpa_supplicant-2.9:wpa_supplicant-2.9":{},
``` ```
"usb:usb_manager_native":{},
"applications:prebuilt_hap":{},
"sample:hello":{},
"wpa_supplicant-2.9:wpa_supplicant-2.9":{},
```
- 3.2-Beta2及之后版本
在vendor/hihope/rk3568/config.json中添加对应的hello部件,直接添加到原有部件后即可。
```
{
"subsystem": "sample",
"components": [
{
"component": "hello",
"features": []
}
]
},
```
...@@ -43,8 +43,8 @@ ...@@ -43,8 +43,8 @@
2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。 2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
类型定义中的Length、Resource、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。 类型定义中的Length、ResourceStr、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、Resource、ResourceColor的定义请看文档[arkui-ts类型定义](../../../application-dev/reference/arkui-ts/ts-types.md)。 Length、ResourceStr、ResourceColor的定义请看文档[arkui-ts类型定义](../../../application-dev/reference/arkui-ts/ts-types.md)。
示例: 示例:
......
# arkui子系统ChangeLog
## cl.arkui.1 状态变量数据类型声明使用限制。
1. 所有的状态装饰器变量需要显式声明变量类型,不允许声明any,不支持Date数据类型。
示例:
```ts
// xxx.ets
@Entry
@Component
struct DatePickerExample {
// 错误写法: @State isLunar: any = false
@State isLunar: boolean = false
// 错误写法: @State selectedDate: Date = new Date('2021-08-08')
private selectedDate: Date = new Date('2021-08-08')
build() {
Column() {
Button('切换公历农历')
.margin({ top: 30 })
.onClick(() => {
this.isLunar = !this.isLunar
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
.lunar(this.isLunar)
.onChange((value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info('select current date is: ' + JSON.stringify(value))
})
}.width('100%')
}
}
```
![datePicker](../../../application-dev/reference/arkui-ts/figures/datePicker.gif)
2. @State、@Provide、 @Link和@Consume四种状态变量的数据类型声明只能由简单数据类型或引用数据类型的其中一种构成。
类型定义中的Length、ResourceStr、ResourceColor三个类型是简单数据类型或引用数据类型的组合,所以不能被以上四种状态装饰器变量使用。
Length、ResourceStr、ResourceColor的定义请看文档[arkui-ts类型定义](../../../application-dev/reference/arkui-ts/ts-types.md)。
示例:
```ts
// xxx.ets
@Entry
@Component
struct IndexPage {
// 错误写法: @State message: string | Resource = 'Hello World'
@State message: string = 'Hello World'
// 错误写法: @State message: ResourceStr = $r('app.string.hello')
@State resourceStr: Resource = $r('app.string.hello')
build() {
Row() {
Column() {
Text(`${this.message}`)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}
```
![hello](../../../application-dev/quick-start/figures/hello.PNG)
**变更影响**
1. 如果状态装饰器变量没有显式声明变量类型,声明any,编译拦截报错;
```ts
// ArkTS:ERROR Please define an explicit type, not any.
@State isLunar: any = false
```
2. 状态装饰器变量声明变量类型为Date,编译拦截报错;
```ts
// ArkTS:ERROR The @State property 'selectedDate' cannot be a 'Date' object.
@State selectedDate: Date = new Date('2021-08-08')
```
3. @State、@Provide、 @Link和@Consume四种状态变量使用框架提供的Length、ResourceStr、ResourceColor,
编译拦截报错。
```ts
/* ArkTS:ERROR The state variable type here is 'ResourceStr', it contains both a simple type and an object type,
which are not allowed to be defined for state variable of a struct.*/
@State message: ResourceStr = $r('app.string.hello')
```
**关键的接口/组件变更**
不涉及。
**适配指导**
1. 状态装饰器变量声明具体的变量类型替代any;
2. 使用Date对象的状态装饰器变量,修改为不加状态装饰器修饰的常规变量;
3. 因为Length(string|number|Resource), ResourceStr(string|Resource), ResourceColor(string|number|Color|Resource)
的三个类型是简单数据类型或引用数据类型的组合,使用@State、@Provide、 @Link和@Consume四种状态变量场景参考以下修改:
```ts
// 错误写法:
@State message: ResourceStr = $r('app.string.hello')
// 修正后的写法:
@State resourceStr: Resource = $r('app.string.hello')
```
## cl.arkui.2 自定义组件成员变量初始化的规则与约束。
通过构造函数方法初始化成员变量,需要遵循如下规则:
| **从父组件中的变量(右)到子组件中的变量(下)** | **regular** | **@State** | **@Link** | **@Prop** | **@Provide** | **@Consume** | **@ObjectLink** |
|---------------------------------|----------------------------|------------|-----------|-----------|--------------|--------------|------------------|
| **regular** | 支持 | 支持 | 支持 | 支持 | 不支持 | 不支持 | 支持 |
| **@State** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Link** | 不支持 | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) | 支持(1) |
| **@Prop** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Provide** | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 | 支持 |
| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 |
| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 | 不支持 |
| **从父组件中的变量(右)到子组件中的变量(下)** | **@StorageLink** | **@StorageProp** | **@LocalStorageLink** | **@LocalStorageProp** |
|------------------|------------------|------------------|-----------------------|------------------------|
| **regular** | 支持 | 不支持 | 不支持 | 不支持 |
| **@State** | 支持 | 支持 | 支持 | 支持 |
| **@Link** | 支持(1) | 支持(1) | 支持(1) | 支持(1) |
| **@Prop** | 支持 | 支持 | 支持 | 支持 |
| **@Provide** | 支持 | 支持 | 支持 | 支持 |
| **@Consume** | 不支持 | 不支持 | 不支持 | 不支持 |
| **@ObjectLink** | 不支持 | 不支持 | 不支持 | 不支持 |
> **说明**
>
> **支持(1)**:必须使用`$`, 例如 `this.$varA`。
> **regular**:未加修饰的常规变量。
不允许从父组件初始化`@StorageLink`, `@StorageProp`, `@LocalStorageLink`, `@LocalStorageProp`修饰的变量。
**变更影响**
1. 不允许从父组件初始化`@LocalStorageLink`, `@LocalStorageProp`修饰的变量。
```ts
@Entry
@Component
struct LocalStorageComponent {
build() {
Column() {
Child({
/* ArkTS:ERROR Property 'simpleVarName' in the custom component 'Child' cannot
initialize here (forbidden to specify). */
simpleVarName: 1,
/* ArkTS:ERROR Property 'objectName' in the custom component 'Child' cannot
initialize here (forbidden to specify). */
objectName: new ClassA("x")
})
}
}
}
@Component
struct Child {
@LocalStorageLink("storageSimpleProp") simpleVarName: number = 0;
@LocalStorageProp("storageObjectProp") objectName: ClassA = new ClassA("x");
build() {}
}
```
2. 子组件的@ObjectLink变量不支持父组件装饰器变量的直接赋值,其父组件的源必须是数组的项或对象的属性,该数组或对象必现用`@State``@Link``@Provide``@Consume``@ObjectLink`装饰器修饰。
```ts
let NextID : number = 0;
@Observed class ClassA {
public id : number;
public c: number;
constructor(c: number) {
this.id = NextID++;
this.c = c;
}
}
@Component
struct Child {
@ObjectLink varA : ClassA;
build() {
Row() {
Text('ViewA-' + this.varA.id)
}
}
}
@Component
struct Parent {
@Link linkValue: ClassA
build() {
Column() {
/* ArkTS:ERROR The @Link property 'linkValue' cannot be assigned to
the @ObjectLink property 'varA'.*/
Child({ varA: this.linkValue })
}
}
}
```
**关键的接口/组件变更**
不涉及。
**适配指导**
1. 构造子组件时,不对子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量进行。
如果需要在父组件中修改子组件的`@LocalStorageLink`, `@LocalStorageProp`修饰的变量,则使用LocalStorage提供的API接口方法(比如set方法)赋值。
2. @ObjectLink的使用指导请参考文档[@ObjectLink使用指导](../../../application-dev/quick-start/arkts-state-mgmt-page-level.md)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册